blob: 4b5e68b7211d631bee766a02ad0cb2b192a53910 [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;
Chris Wrenc3919c02013-09-18 09:48:33 -040042import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080043import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070044import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070045import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010046
Kenny Guyed131872014-04-30 03:02:21 +010047import com.android.launcher3.compat.LauncherActivityInfoCompat;
48import com.android.launcher3.compat.LauncherAppsCompat;
49import com.android.launcher3.compat.UserHandleCompat;
50import com.android.launcher3.compat.UserManagerCompat;
Daniel Sandler325dc232013-06-05 22:57:57 -040051import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080052
Michael Jurkac2f801e2011-07-12 14:19:46 -070053import java.lang.ref.WeakReference;
54import java.net.URISyntaxException;
55import java.text.Collator;
56import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070057import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070058import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070059import java.util.Collections;
60import java.util.Comparator;
61import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070062import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070063import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070064import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070065import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070066import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070067import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070068
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069/**
70 * Maintains in-memory state of the Launcher. It is expected that there should be only one
71 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070072 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073 */
Kenny Guyed131872014-04-30 03:02:21 +010074public class LauncherModel extends BroadcastReceiver
75 implements LauncherAppsCompat.OnAppsChangedListenerCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080076 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040077 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
78
Joe Onorato9c1289c2009-08-17 11:03:03 -040079 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070080
Daniel Sandler8707e0f2013-08-15 15:54:18 -070081 // true = use a "More Apps" folder for non-workspace apps on upgrade
82 // false = strew non-workspace apps across the workspace on upgrade
83 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050084 public static final int LOADER_FLAG_NONE = 0;
85 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
86 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
87
Joe Onorato36115782010-06-17 13:28:48 -040088 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050089 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080090
Winson Chungee055712013-07-30 14:46:24 -070091 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -080092 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -040093
Daniel Sandlercc8befa2013-06-11 14:45:48 -040094 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040095 private final Object mLock = new Object();
96 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040097 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070098 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020099 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Winson Chung81b52252012-08-27 15:34:29 -0700101 // Specific runnable types that are run on the main thread deferred handler, this allows us to
102 // clear all queued binding runnables when the Launcher activity is destroyed.
103 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
104 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
105
106
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700107 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
108 static {
109 sWorkerThread.start();
110 }
111 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
112
Joe Onoratocc67f472010-06-08 10:54:30 -0700113 // We start off with everything not loaded. After that, we assume that
114 // our monitoring of the package manager provides all updates and we never
115 // need to do a requery. These are only ever touched from the loader thread.
116 private boolean mWorkspaceLoaded;
117 private boolean mAllAppsLoaded;
118
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700119 // When we are loading pages synchronously, we can't just post the binding of items on the side
120 // pages as this delays the rotation process. Instead, we wait for a callback from the first
121 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
122 // a normal load, we also clear this set of Runnables.
123 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
124
Joe Onorato9c1289c2009-08-17 11:03:03 -0400125 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700127 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700128 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800129
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700130 // The lock that must be acquired before referencing any static bg data structures. Unlike
131 // other locks, this one can generally be held long-term because we never expect any of these
132 // static data structures to be referenced outside of the worker thread except on the first
133 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700134 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700135
Adam Cohen487f7dd2012-06-28 18:12:10 -0700136 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700138 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139
Adam Cohen487f7dd2012-06-28 18:12:10 -0700140 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
141 // created by LauncherModel that are directly on the home screen (however, no widgets or
142 // shortcuts within folders).
143 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700144
Adam Cohen487f7dd2012-06-28 18:12:10 -0700145 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
146 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 new ArrayList<LauncherAppWidgetInfo>();
148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
150 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700151
Adam Cohen487f7dd2012-06-28 18:12:10 -0700152 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
153 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700154
155 // sBgWorkspaceScreens is the ordered set of workspace screens.
156 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
157
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 // </ only access in worker thread >
159
160 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800161
Reena Lee99a73f32011-10-24 17:27:37 -0700162 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700163
Kenny Guyed131872014-04-30 03:02:21 +0100164 private final LauncherAppsCompat mLauncherApps;
165 private final UserManagerCompat mUserManager;
166
Joe Onorato9c1289c2009-08-17 11:03:03 -0400167 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700168 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400169 public int getCurrentWorkspaceScreen();
170 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700171 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
172 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700173 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700174 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500175 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700176 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400177 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200178 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700179 public void bindAppsAdded(ArrayList<Long> newScreens,
180 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700181 ArrayList<ItemInfo> addAnimated,
182 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200183 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500184 public void updatePackageState(String pkgName, int state);
Winson Chung83892cc2013-05-01 16:53:33 -0700185 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100186 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200187 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100188 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700189 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700190 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700191 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400192 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193
Winson Chung64359a52013-07-08 17:17:08 -0700194 public interface ItemInfoFilter {
195 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
196 }
197
Bjorn Bringert1307f632013-10-03 22:31:03 +0100198 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800199 Context context = app.getContext();
200 ContentResolver contentResolver = context.getContentResolver();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400201
Winson Chungee055712013-07-30 14:46:24 -0700202 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700203 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Winson Chungeb23cb22014-03-06 10:39:43 -0800204 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Jason Monk0bfcceb2014-03-21 15:42:06 -0400205 Uri.parse(context.getString(R.string.old_launcher_provider_uri)));
Adam Cohen71483f42014-05-15 14:04:01 -0700206
207 Log.d(TAG, "Old launcher provider: " + oldProvider);
Winson Chungeb23cb22014-03-06 10:39:43 -0800208 mOldContentProviderExists = (client != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700209
210 if (mOldContentProviderExists) {
211 Log.d(TAG, "Old launcher provider exists.");
212 } else {
213 Log.d(TAG, "Old launcher provider does not exist.");
214 }
215
Winson Chungeb23cb22014-03-06 10:39:43 -0800216 if (client != null) {
217 client.release();
218 }
Daniel Sandlere4f98912013-06-25 15:13:26 -0400219 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100220 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800221 mIconCache = iconCache;
222
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400223 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700224 Configuration config = res.getConfiguration();
225 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100226 mLauncherApps = LauncherAppsCompat.getInstance(context);
227 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800228 }
229
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700230 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
231 * posted on the main thread handler. */
232 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700233 runOnMainThread(r, 0);
234 }
235 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700236 if (sWorkerThread.getThreadId() == Process.myTid()) {
237 // If we are on the worker thread, post onto the main handler
238 mHandler.post(r);
239 } else {
240 r.run();
241 }
242 }
243
244 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
245 * posted on the worker thread handler. */
246 private static void runOnWorkerThread(Runnable r) {
247 if (sWorkerThread.getThreadId() == Process.myTid()) {
248 r.run();
249 } else {
250 // If we are not on the worker thread, then post to the worker handler
251 sWorker.post(r);
252 }
253 }
254
Winson Chunge43a1e72014-01-15 10:33:02 -0800255 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
256 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800257 }
258
Winson Chungc9168342013-06-26 14:54:55 -0700259 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
260 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700261 LauncherAppState app = LauncherAppState.getInstance();
262 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
263 final int xCount = (int) grid.numColumns;
264 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700265 boolean[][] occupied = new boolean[xCount][yCount];
266
267 int cellX, cellY, spanX, spanY;
268 for (int i = 0; i < items.size(); ++i) {
269 final ItemInfo item = items.get(i);
270 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
271 if (item.screenId == screen) {
272 cellX = item.cellX;
273 cellY = item.cellY;
274 spanX = item.spanX;
275 spanY = item.spanY;
276 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
277 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
278 occupied[x][y] = true;
279 }
280 }
281 }
282 }
283 }
284
285 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
286 }
287 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700288 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700289 int firstScreenIndex,
290 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700291 // Lock on the app so that we don't try and get the items while apps are being added
292 LauncherAppState app = LauncherAppState.getInstance();
293 LauncherModel model = app.getModel();
294 boolean found = false;
295 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700296 if (sWorkerThread.getThreadId() != Process.myTid()) {
297 // Flush the LauncherModel worker thread, so that if we just did another
298 // processInstallShortcut, we give it time for its shortcut to get added to the
299 // database (getItemsInLocalCoordinates reads the database)
300 model.flushWorkerThread();
301 }
Winson Chungc9168342013-06-26 14:54:55 -0700302 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700303
304 // Try adding to the workspace screens incrementally, starting at the default or center
305 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700306 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
307 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700308 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700309 int[] tmpCoordinates = new int[2];
310 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700311 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700312 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700313 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700314 }
315 }
316 }
Winson Chungc9168342013-06-26 14:54:55 -0700317 return null;
318 }
319
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500320 public void setPackageState(final String pkgName, final int state) {
321 // Process the updated package state
322 Runnable r = new Runnable() {
323 public void run() {
324 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
325 if (callbacks != null) {
326 callbacks.updatePackageState(pkgName, state);
327 }
328 }
329 };
330 mHandler.post(r);
331 }
332
Adam Cohen76a47a12014-02-05 11:47:43 -0800333 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
334 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
335
336 if (allAppsApps == null) {
337 throw new RuntimeException("allAppsApps must not be null");
338 }
339 if (allAppsApps.isEmpty()) {
340 return;
341 }
342
Chris Wrenb6d4c282014-01-27 14:17:08 -0500343 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
344 Iterator<AppInfo> iter = allAppsApps.iterator();
345 while (iter.hasNext()) {
346 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100347 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500348 restoredAppsFinal.add((AppInfo) a);
349 }
350 }
351
Adam Cohen76a47a12014-02-05 11:47:43 -0800352 // Process the newly added applications and add them to the database first
353 Runnable r = new Runnable() {
354 public void run() {
355 runOnMainThread(new Runnable() {
356 public void run() {
357 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
358 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500359 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500360 for (AppInfo info : restoredAppsFinal) {
361 final Intent intent = info.getIntent();
362 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100363 mIconCache.deletePreloadedIcon(intent.getComponent(),
364 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500365 }
366 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500367 callbacks.bindAppsUpdated(restoredAppsFinal);
368 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500369 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800370 }
371 }
372 });
373 }
374 };
375 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700376 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800377
378 public void addAndBindAddedWorkspaceApps(final Context context,
379 final ArrayList<ItemInfo> workspaceApps) {
380 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
381
382 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800383 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
384 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800385 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700386 return;
Winson Chung997a9232013-07-24 15:33:46 -0700387 }
Winson Chung64359a52013-07-08 17:17:08 -0700388 // Process the newly added applications and add them to the database first
389 Runnable r = new Runnable() {
390 public void run() {
391 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
392 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500393 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700394
Winson Chung76828c82013-08-19 15:43:29 -0700395 // Get the list of workspace screens. We need to append to this list and
396 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
397 // called.
398 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
399 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
400 for (Integer i : orderedScreens.keySet()) {
401 long screenId = orderedScreens.get(i);
402 workspaceScreens.add(screenId);
403 }
404
Winson Chung64359a52013-07-08 17:17:08 -0700405 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700406 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700407 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700408 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700409 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700410 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700411
412 // Short-circuit this logic if the icon exists somewhere on the workspace
413 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500414 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
415 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100416 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500417 restoredAppsFinal.add((AppInfo) a);
418 }
Winson Chung64359a52013-07-08 17:17:08 -0700419 continue;
420 }
421
Winson Chung87412982013-10-03 18:34:14 -0700422 // Add this icon to the db, creating a new page if necessary. If there
423 // is only the empty page then we just add items to the first page.
424 // Otherwise, we add them to the next pages.
425 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700426 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700427 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700428 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200429 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700430
431 // If we can't find a valid position, then just add a new screen.
432 // This takes time so we need to re-queue the add until the new
433 // page is added. Create as many screens as necessary to satisfy
434 // the startSearchPageIndex.
435 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700436 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700437 while (numPagesToAdd > 0) {
438 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700439 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700440 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700441 addedWorkspaceScreensFinal.add(screenId);
442 numPagesToAdd--;
443 }
Winson Chung76828c82013-08-19 15:43:29 -0700444
Winson Chung64359a52013-07-08 17:17:08 -0700445 // Find the coordinate again
446 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700447 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700448 }
449 if (coords == null) {
450 throw new RuntimeException("Coordinates should not be null");
451 }
452
Winson Chung997a9232013-07-24 15:33:46 -0700453 ShortcutInfo shortcutInfo;
454 if (a instanceof ShortcutInfo) {
455 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200456 } else if (a instanceof AppInfo) {
457 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700458 } else {
459 throw new RuntimeException("Unexpected info type");
460 }
Winson Chung94d67682013-09-25 16:29:40 -0700461
Winson Chung64359a52013-07-08 17:17:08 -0700462 // Add the shortcut to the db
463 addItemToDatabase(context, shortcutInfo,
464 LauncherSettings.Favorites.CONTAINER_DESKTOP,
465 coords.first, coords.second[0], coords.second[1], false);
466 // Save the ShortcutInfo for binding in the workspace
467 addedShortcutsFinal.add(shortcutInfo);
468 }
469 }
470
Winson Chung76828c82013-08-19 15:43:29 -0700471 // Update the workspace screens
472 updateWorkspaceScreenOrder(context, workspaceScreens);
473
Adam Cohen76a47a12014-02-05 11:47:43 -0800474 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700475 runOnMainThread(new Runnable() {
476 public void run() {
477 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
478 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700479 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
480 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700481 if (!addedShortcutsFinal.isEmpty()) {
482 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
483 long lastScreenId = info.screenId;
484 for (ItemInfo i : addedShortcutsFinal) {
485 if (i.screenId == lastScreenId) {
486 addAnimated.add(i);
487 } else {
488 addNotAnimated.add(i);
489 }
Winson Chung997a9232013-07-24 15:33:46 -0700490 }
491 }
Winson Chungd64d1762013-08-20 14:37:16 -0700492 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800493 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500494 if (!restoredAppsFinal.isEmpty()) {
495 callbacks.bindAppsUpdated(restoredAppsFinal);
496 }
Winson Chung997a9232013-07-24 15:33:46 -0700497 }
Winson Chung64359a52013-07-08 17:17:08 -0700498 }
Winson Chung997a9232013-07-24 15:33:46 -0700499 });
500 }
Winson Chung64359a52013-07-08 17:17:08 -0700501 }
502 };
503 runOnWorkerThread(r);
504 }
505
Winson Chung81b52252012-08-27 15:34:29 -0700506 public void unbindItemInfosAndClearQueuedBindRunnables() {
507 if (sWorkerThread.getThreadId() == Process.myTid()) {
508 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
509 "main thread");
510 }
511
512 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400513 synchronized (mDeferredBindRunnables) {
514 mDeferredBindRunnables.clear();
515 }
Winson Chung81b52252012-08-27 15:34:29 -0700516 // Remove any queued bind runnables
517 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
518 // Unbind all the workspace items
519 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700520 }
521
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700522 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700523 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700524 // Ensure that we don't use the same workspace items data structure on the main thread
525 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700526 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
527 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700528 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700529 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
530 tmpAppWidgets.addAll(sBgAppWidgets);
531 }
532 Runnable r = new Runnable() {
533 @Override
534 public void run() {
535 for (ItemInfo item : tmpWorkspaceItems) {
536 item.unbind();
537 }
538 for (ItemInfo item : tmpAppWidgets) {
539 item.unbind();
540 }
541 }
542 };
543 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700544 }
545
Joe Onorato9c1289c2009-08-17 11:03:03 -0400546 /**
547 * Adds an item to the DB if it was not created previously, or move it to a new
548 * <container, screen, cellX, cellY>
549 */
550 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700551 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400552 if (item.container == ItemInfo.NO_ID) {
553 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700554 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400555 } else {
556 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700557 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800558 }
559 }
560
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700561 static void checkItemInfoLocked(
562 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
563 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
564 if (modelItem != null && item != modelItem) {
565 // check all the data is consistent
566 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
567 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
568 ShortcutInfo shortcut = (ShortcutInfo) item;
569 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
570 modelShortcut.intent.filterEquals(shortcut.intent) &&
571 modelShortcut.id == shortcut.id &&
572 modelShortcut.itemType == shortcut.itemType &&
573 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700574 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700575 modelShortcut.cellX == shortcut.cellX &&
576 modelShortcut.cellY == shortcut.cellY &&
577 modelShortcut.spanX == shortcut.spanX &&
578 modelShortcut.spanY == shortcut.spanY &&
579 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
580 (modelShortcut.dropPos != null &&
581 shortcut.dropPos != null &&
582 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
583 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
584 // For all intents and purposes, this is the same object
585 return;
586 }
587 }
588
589 // the modelItem needs to match up perfectly with item if our model is
590 // to be consistent with the database-- for now, just require
591 // modelItem == item or the equality check above
592 String msg = "item: " + ((item != null) ? item.toString() : "null") +
593 "modelItem: " +
594 ((modelItem != null) ? modelItem.toString() : "null") +
595 "Error: ItemInfo passed to checkItemInfo doesn't match original";
596 RuntimeException e = new RuntimeException(msg);
597 if (stackTrace != null) {
598 e.setStackTrace(stackTrace);
599 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800600 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700601 }
602 }
603
Michael Jurka816474f2012-06-25 14:49:02 -0700604 static void checkItemInfo(final ItemInfo item) {
605 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
606 final long itemId = item.id;
607 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700608 public void run() {
609 synchronized (sBgLock) {
610 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700611 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700612 }
613 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700614 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700615 }
616
Michael Jurkac9d95c52011-08-29 14:03:34 -0700617 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
618 final ItemInfo item, final String callingFunction) {
619 final long itemId = item.id;
620 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
621 final ContentResolver cr = context.getContentResolver();
622
Adam Cohen487f7dd2012-06-28 18:12:10 -0700623 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700624 Runnable r = new Runnable() {
625 public void run() {
626 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700627 updateItemArrays(item, itemId, stackTrace);
628 }
629 };
630 runOnWorkerThread(r);
631 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700632
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700633 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
634 final ArrayList<ItemInfo> items, final String callingFunction) {
635 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700636
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700637 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
638 Runnable r = new Runnable() {
639 public void run() {
640 ArrayList<ContentProviderOperation> ops =
641 new ArrayList<ContentProviderOperation>();
642 int count = items.size();
643 for (int i = 0; i < count; i++) {
644 ItemInfo item = items.get(i);
645 final long itemId = item.id;
646 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
647 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700648
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700649 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
650 updateItemArrays(item, itemId, stackTrace);
651
652 }
653 try {
654 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
655 } catch (Exception e) {
656 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700657 }
658 }
659 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700660 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700661 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700662
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700663 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
664 // Lock on mBgLock *after* the db operation
665 synchronized (sBgLock) {
666 checkItemInfoLocked(itemId, item, stackTrace);
667
668 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
669 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
670 // Item is in a folder, make sure this folder exists
671 if (!sBgFolders.containsKey(item.container)) {
672 // An items container is being set to a that of an item which is not in
673 // the list of Folders.
674 String msg = "item: " + item + " container being set to: " +
675 item.container + ", not in the list of folders";
676 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700677 }
678 }
679
680 // Items are added/removed from the corresponding FolderInfo elsewhere, such
681 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
682 // that are on the desktop, as appropriate
683 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800684 if (modelItem != null &&
685 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
686 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700687 switch (modelItem.itemType) {
688 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
689 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
690 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
691 if (!sBgWorkspaceItems.contains(modelItem)) {
692 sBgWorkspaceItems.add(modelItem);
693 }
694 break;
695 default:
696 break;
697 }
698 } else {
699 sBgWorkspaceItems.remove(modelItem);
700 }
701 }
702 }
703
Michael Jurkac7700af2013-05-14 20:17:58 +0200704 public void flushWorkerThread() {
705 mFlushingWorkerThread = true;
706 Runnable waiter = new Runnable() {
707 public void run() {
708 synchronized (this) {
709 notifyAll();
710 mFlushingWorkerThread = false;
711 }
712 }
713 };
714
715 synchronized(waiter) {
716 runOnWorkerThread(waiter);
717 if (mLoaderTask != null) {
718 synchronized(mLoaderTask) {
719 mLoaderTask.notify();
720 }
721 }
722 boolean success = false;
723 while (!success) {
724 try {
725 waiter.wait();
726 success = true;
727 } catch (InterruptedException e) {
728 }
729 }
730 }
731 }
732
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800733 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400734 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700735 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700736 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700737 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400738 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400739 item.cellX = cellX;
740 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700741
Winson Chung3d503fb2011-07-13 17:25:49 -0700742 // We store hotseat items in canonical form which is this orientation invariant position
743 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700744 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700745 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700746 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700747 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700748 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700749 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400750
751 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400752 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700753 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
754 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700755 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400756
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700758 }
759
760 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700761 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
762 * cellX, cellY have already been updated on the ItemInfos.
763 */
764 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
765 final long container, final int screen) {
766
767 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
768 int count = items.size();
769
770 for (int i = 0; i < count; i++) {
771 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700772 item.container = container;
773
774 // We store hotseat items in canonical form which is this orientation invariant position
775 // in the hotseat
776 if (context instanceof Launcher && screen < 0 &&
777 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700778 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700779 item.cellY);
780 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700781 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700782 }
783
784 final ContentValues values = new ContentValues();
785 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
786 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
787 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700788 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700789
790 contentValues.add(values);
791 }
792 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
793 }
794
795 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700796 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800797 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700798 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700799 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700800 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800801 item.cellX = cellX;
802 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700803 item.spanX = spanX;
804 item.spanY = spanY;
805
806 // We store hotseat items in canonical form which is this orientation invariant position
807 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700808 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700809 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700810 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700811 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700812 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700813 }
Adam Cohend4844c32011-02-18 19:25:06 -0800814
Adam Cohend4844c32011-02-18 19:25:06 -0800815 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800816 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700817 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
818 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
819 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
820 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700821 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800822
Michael Jurka816474f2012-06-25 14:49:02 -0700823 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700824 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700825
826 /**
827 * Update an item to the database in a specified container.
828 */
829 static void updateItemInDatabase(Context context, final ItemInfo item) {
830 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100831 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700832 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
833 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800834 }
835
836 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400837 * Returns true if the shortcuts already exists in the database.
838 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800839 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400840 static boolean shortcutExists(Context context, String title, Intent intent) {
841 final ContentResolver cr = context.getContentResolver();
842 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
843 new String[] { "title", "intent" }, "title=? and intent=?",
844 new String[] { title, intent.toUri(0) }, null);
845 boolean result = false;
846 try {
847 result = c.moveToFirst();
848 } finally {
849 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800850 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400851 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700852 }
853
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500855 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100856 * we identify a shortcut by the component name of the intent
857 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500858 */
Kenny Guyed131872014-04-30 03:02:21 +0100859 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500860 final ContentResolver cr = context.getContentResolver();
861 final ComponentName component = intent.getComponent();
862 if (component == null) {
863 return false;
864 }
865 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400866 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100867 long serialNumber = UserManagerCompat.getInstance(context)
868 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400869 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
870 "intent glob \"*component=" + shortName + "*\")" +
871 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500872 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100873 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500874 boolean result = false;
875 try {
876 result = c.moveToFirst();
877 } finally {
878 c.close();
879 }
880 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
881 return result;
882 }
883
884 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700885 * Returns an ItemInfo array containing all the items in the LauncherModel.
886 * The ItemInfo.id is not set through this function.
887 */
888 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
889 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
890 final ContentResolver cr = context.getContentResolver();
891 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
892 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100893 LauncherSettings.Favorites.SCREEN,
894 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
895 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
896 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700897
898 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
899 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
900 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
901 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
902 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
903 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
904 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100905 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
906 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700907 try {
908 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700909 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700910 item.cellX = c.getInt(cellXIndex);
911 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700912 item.spanX = Math.max(1, c.getInt(spanXIndex));
913 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700914 item.container = c.getInt(containerIndex);
915 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700916 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100917 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100918 item.user = userManager.getUserForSerialNumber(serialNumber);
919 // Skip if user has been deleted.
920 if (item.user != null) {
921 items.add(item);
922 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700923 }
924 } catch (Exception e) {
925 items.clear();
926 } finally {
927 c.close();
928 }
929
930 return items;
931 }
932
933 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400934 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
935 */
936 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
937 final ContentResolver cr = context.getContentResolver();
938 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
939 "_id=? and (itemType=? or itemType=?)",
940 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700941 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700942
Joe Onorato9c1289c2009-08-17 11:03:03 -0400943 try {
944 if (c.moveToFirst()) {
945 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
946 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
947 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
948 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
949 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
950 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800951
Joe Onorato9c1289c2009-08-17 11:03:03 -0400952 FolderInfo folderInfo = null;
953 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700954 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
955 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400956 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700957 }
958
Joe Onorato9c1289c2009-08-17 11:03:03 -0400959 folderInfo.title = c.getString(titleIndex);
960 folderInfo.id = id;
961 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700962 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700963 folderInfo.cellX = c.getInt(cellXIndex);
964 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965
966 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700967 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968 } finally {
969 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700970 }
971
972 return null;
973 }
974
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975 /**
976 * Add an item to the database in a specified container. Sets the container, screen, cellX and
977 * cellY fields of the item. Also assigns an ID to the item.
978 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700979 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700980 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982 item.cellX = cellX;
983 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700984 // We store hotseat items in canonical form which is this orientation invariant position
985 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700986 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700987 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700989 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700990 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700991 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400992
993 final ContentValues values = new ContentValues();
994 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +0100995 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996
Michael Jurka414300a2013-08-27 15:42:35 +0200997 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700998 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700999 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001000
Jason Monk8e19cf22014-03-20 15:06:57 -04001001 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001002 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001003 public void run() {
1004 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1005 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001007 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001008 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001009 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001010 sBgItemsIdMap.put(item.id, item);
1011 switch (item.itemType) {
1012 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1013 sBgFolders.put(item.id, (FolderInfo) item);
1014 // Fall through
1015 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1016 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1017 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1018 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1019 sBgWorkspaceItems.add(item);
1020 } else {
1021 if (!sBgFolders.containsKey(item.container)) {
1022 // Adding an item to a folder that doesn't exist.
1023 String msg = "adding item: " + item + " to a folder that " +
1024 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001025 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001026 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001027 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001028 break;
1029 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1030 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1031 break;
1032 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001033 }
1034 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001035 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001036 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001037 }
1038
Joe Onorato9c1289c2009-08-17 11:03:03 -04001039 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001040 * Creates a new unique child id, for a given cell span across all layouts.
1041 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001042 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001043 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001044 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001045 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001046 }
1047
Winson Chungaafa03c2010-06-11 17:34:16 -07001048 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001049 * Removes the specified item from the database
1050 * @param context
1051 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001052 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001053 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001054 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001055 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001056
Michael Jurka83df1882011-08-31 20:59:26 -07001057 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001058 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001059 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001060
1061 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001062 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001063 switch (item.itemType) {
1064 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1065 sBgFolders.remove(item.id);
1066 for (ItemInfo info: sBgItemsIdMap.values()) {
1067 if (info.container == item.id) {
1068 // We are deleting a folder which still contains items that
1069 // think they are contained by that folder.
1070 String msg = "deleting a folder (" + item + ") which still " +
1071 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001072 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001073 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001074 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001075 sBgWorkspaceItems.remove(item);
1076 break;
1077 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1078 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1079 sBgWorkspaceItems.remove(item);
1080 break;
1081 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1082 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1083 break;
1084 }
1085 sBgItemsIdMap.remove(item.id);
1086 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001087 }
1088 }
Michael Jurka83df1882011-08-31 20:59:26 -07001089 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001090 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001091 }
1092
1093 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001094 * Update the order of the workspace screens in the database. The array list contains
1095 * a list of screen ids in the order that they should appear.
1096 */
Winson Chungc9168342013-06-26 14:54:55 -07001097 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001098 // Log to disk
1099 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1100 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1101
Winson Chung64359a52013-07-08 17:17:08 -07001102 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001103 final ContentResolver cr = context.getContentResolver();
1104 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1105
1106 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001107 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001108 while (iter.hasNext()) {
1109 long id = iter.next();
1110 if (id < 0) {
1111 iter.remove();
1112 }
1113 }
1114
1115 Runnable r = new Runnable() {
1116 @Override
1117 public void run() {
Yura085c8532014-02-11 15:15:29 +00001118 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001119 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001120 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001121 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001122 for (int i = 0; i < count; i++) {
1123 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001124 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001125 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1126 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001127 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001128 }
Yura085c8532014-02-11 15:15:29 +00001129
1130 try {
1131 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1132 } catch (Exception ex) {
1133 throw new RuntimeException(ex);
1134 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001135
Winson Chungba9c37f2013-08-30 14:11:37 -07001136 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001137 sBgWorkspaceScreens.clear();
1138 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001139 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 }
1141 };
1142 runOnWorkerThread(r);
1143 }
1144
1145 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001146 * Remove the contents of the specified folder from the database
1147 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001148 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001149 final ContentResolver cr = context.getContentResolver();
1150
Michael Jurkac9d95c52011-08-29 14:03:34 -07001151 Runnable r = new Runnable() {
1152 public void run() {
1153 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001154 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001155 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001156 sBgItemsIdMap.remove(info.id);
1157 sBgFolders.remove(info.id);
1158 sBgDbIconCache.remove(info);
1159 sBgWorkspaceItems.remove(info);
1160 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001161
Michael Jurkac9d95c52011-08-29 14:03:34 -07001162 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1163 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001164 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001165 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001166 for (ItemInfo childInfo : info.contents) {
1167 sBgItemsIdMap.remove(childInfo.id);
1168 sBgDbIconCache.remove(childInfo);
1169 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001170 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001171 }
1172 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001173 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001174 }
1175
1176 /**
1177 * Set this as the current Launcher activity object for the loader.
1178 */
1179 public void initialize(Callbacks callbacks) {
1180 synchronized (mLock) {
1181 mCallbacks = new WeakReference<Callbacks>(callbacks);
1182 }
1183 }
1184
Kenny Guyed131872014-04-30 03:02:21 +01001185 @Override
1186 public void onPackageChanged(UserHandleCompat user, String packageName) {
1187 int op = PackageUpdatedTask.OP_UPDATE;
1188 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1189 user));
1190 }
1191
1192 @Override
1193 public void onPackageRemoved(UserHandleCompat user, String packageName) {
1194 int op = PackageUpdatedTask.OP_REMOVE;
1195 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1196 user));
1197 }
1198
1199 @Override
1200 public void onPackageAdded(UserHandleCompat user, String packageName) {
1201 int op = PackageUpdatedTask.OP_ADD;
1202 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1203 user));
1204 }
1205
1206 @Override
1207 public void onPackagesAvailable(UserHandleCompat user, String[] packageNames,
1208 boolean replacing) {
1209 if (!replacing) {
1210 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1211 user));
1212 if (mAppsCanBeOnRemoveableStorage) {
1213 // Only rebind if we support removable storage. It catches the
1214 // case where
1215 // apps on the external sd card need to be reloaded
1216 startLoaderFromBackground();
1217 }
1218 } else {
1219 // If we are replacing then just update the packages in the list
1220 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1221 packageNames, user));
1222 }
1223 }
1224
1225 @Override
1226 public void onPackagesUnavailable(UserHandleCompat user, String[] packageNames,
1227 boolean replacing) {
1228 if (!replacing) {
1229 enqueuePackageUpdated(new PackageUpdatedTask(
1230 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1231 user));
1232 }
1233
1234 }
1235
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001236 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001237 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1238 * ACTION_PACKAGE_CHANGED.
1239 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001240 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001241 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001242 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001243
Joe Onorato36115782010-06-17 13:28:48 -04001244 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001245 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001246 // If we have changed locale we need to clear out the labels in all apps/workspace.
1247 forceReload();
1248 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1249 // Check if configuration change was an mcc/mnc change which would affect app resources
1250 // and we would need to clear out the labels in all apps/workspace. Same handling as
1251 // above for ACTION_LOCALE_CHANGED
1252 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001253 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001254 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001255 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001256 forceReload();
1257 }
1258 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001259 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001260 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1261 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001262 if (mCallbacks != null) {
1263 Callbacks callbacks = mCallbacks.get();
1264 if (callbacks != null) {
1265 callbacks.bindSearchablesChanged();
1266 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001267 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001268 }
1269 }
1270
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001271 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001272 resetLoadedState(true, true);
1273
Reena Lee93f824a2011-09-23 17:20:28 -07001274 // Do this here because if the launcher activity is running it will be restarted.
1275 // If it's not running startLoaderFromBackground will merely tell it that it needs
1276 // to reload.
1277 startLoaderFromBackground();
1278 }
1279
Winson Chungf0c6ae02012-03-21 16:10:31 -07001280 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1281 synchronized (mLock) {
1282 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1283 // mWorkspaceLoaded to true later
1284 stopLoaderLocked();
1285 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1286 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1287 }
1288 }
1289
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001290 /**
1291 * When the launcher is in the background, it's possible for it to miss paired
1292 * configuration changes. So whenever we trigger the loader from the background
1293 * tell the launcher that it needs to re-run the loader when it comes back instead
1294 * of doing it now.
1295 */
1296 public void startLoaderFromBackground() {
1297 boolean runLoader = false;
1298 if (mCallbacks != null) {
1299 Callbacks callbacks = mCallbacks.get();
1300 if (callbacks != null) {
1301 // Only actually run the loader if they're not paused.
1302 if (!callbacks.setLoadOnResume()) {
1303 runLoader = true;
1304 }
1305 }
1306 }
1307 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001308 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001309 }
Joe Onorato36115782010-06-17 13:28:48 -04001310 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001311
Reena Lee93f824a2011-09-23 17:20:28 -07001312 // If there is already a loader task running, tell it to stop.
1313 // returns true if isLaunching() was true on the old task
1314 private boolean stopLoaderLocked() {
1315 boolean isLaunching = false;
1316 LoaderTask oldTask = mLoaderTask;
1317 if (oldTask != null) {
1318 if (oldTask.isLaunching()) {
1319 isLaunching = true;
1320 }
1321 oldTask.stopLocked();
1322 }
1323 return isLaunching;
1324 }
1325
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001326 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001327 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1328 }
1329
1330 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001331 synchronized (mLock) {
1332 if (DEBUG_LOADERS) {
1333 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1334 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001335
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001336 // Clear any deferred bind-runnables from the synchronized load process
1337 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001338 synchronized (mDeferredBindRunnables) {
1339 mDeferredBindRunnables.clear();
1340 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001341
Joe Onorato36115782010-06-17 13:28:48 -04001342 // Don't bother to start the thread if we know it's not going to do anything
1343 if (mCallbacks != null && mCallbacks.get() != null) {
1344 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001345 // also, don't downgrade isLaunching if we're already running
1346 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001347 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001348 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1349 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001350 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1351 } else {
1352 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1353 sWorker.post(mLoaderTask);
1354 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001355 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001356 }
1357 }
1358
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001359 void bindRemainingSynchronousPages() {
1360 // Post the remaining side pages to be loaded
1361 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001362 Runnable[] deferredBindRunnables = null;
1363 synchronized (mDeferredBindRunnables) {
1364 deferredBindRunnables = mDeferredBindRunnables.toArray(
1365 new Runnable[mDeferredBindRunnables.size()]);
1366 mDeferredBindRunnables.clear();
1367 }
1368 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001369 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001371 }
1372 }
1373
Joe Onorato36115782010-06-17 13:28:48 -04001374 public void stopLoader() {
1375 synchronized (mLock) {
1376 if (mLoaderTask != null) {
1377 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001378 }
1379 }
Joe Onorato36115782010-06-17 13:28:48 -04001380 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001381
Winson Chung76828c82013-08-19 15:43:29 -07001382 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1383 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1384 final ContentResolver contentResolver = context.getContentResolver();
1385 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1386 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1387 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1388
1389 try {
1390 final int idIndex = sc.getColumnIndexOrThrow(
1391 LauncherSettings.WorkspaceScreens._ID);
1392 final int rankIndex = sc.getColumnIndexOrThrow(
1393 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1394 while (sc.moveToNext()) {
1395 try {
1396 long screenId = sc.getLong(idIndex);
1397 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001398 orderedScreens.put(rank, screenId);
1399 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001400 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001401 }
1402 }
1403 } finally {
1404 sc.close();
1405 }
Winson Chunga90303b2013-11-15 13:05:06 -08001406
1407 // Log to disk
1408 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1409 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1410 for (Integer i : orderedScreens.keySet()) {
1411 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1412 }
1413 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1414 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001415 return orderedScreens;
1416 }
1417
Michael Jurkac57b7a82011-08-09 22:02:20 -07001418 public boolean isAllAppsLoaded() {
1419 return mAllAppsLoaded;
1420 }
1421
Winson Chung36a62fe2012-05-06 18:04:42 -07001422 boolean isLoadingWorkspace() {
1423 synchronized (mLock) {
1424 if (mLoaderTask != null) {
1425 return mLoaderTask.isLoadingWorkspace();
1426 }
1427 }
1428 return false;
1429 }
1430
Joe Onorato36115782010-06-17 13:28:48 -04001431 /**
1432 * Runnable for the thread that loads the contents of the launcher:
1433 * - workspace icons
1434 * - widgets
1435 * - all apps icons
1436 */
1437 private class LoaderTask implements Runnable {
1438 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001439 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001440 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001441 private boolean mStopped;
1442 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001443 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001444
Winson Chungc3eecff2011-07-11 17:44:15 -07001445 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001446
Dan Sandlerd5024042014-01-09 15:01:33 -05001447 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001448 mContext = context;
1449 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001450 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001451 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001452 }
1453
Joe Onorato36115782010-06-17 13:28:48 -04001454 boolean isLaunching() {
1455 return mIsLaunching;
1456 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001457
Winson Chung36a62fe2012-05-06 18:04:42 -07001458 boolean isLoadingWorkspace() {
1459 return mIsLoadingAndBindingWorkspace;
1460 }
1461
Winson Chungc763c4e2013-07-19 13:49:06 -07001462 /** Returns whether this is an upgrade path */
1463 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001464 mIsLoadingAndBindingWorkspace = true;
1465
Joe Onorato36115782010-06-17 13:28:48 -04001466 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001467 if (DEBUG_LOADERS) {
1468 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001469 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001470
Winson Chungc763c4e2013-07-19 13:49:06 -07001471 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001472 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001473 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001474 synchronized (LoaderTask.this) {
1475 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001476 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001477 }
1478 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001479 }
1480 }
1481
Joe Onorato36115782010-06-17 13:28:48 -04001482 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001483 bindWorkspace(-1, isUpgradePath);
1484 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001485 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001486
Joe Onorato36115782010-06-17 13:28:48 -04001487 private void waitForIdle() {
1488 // Wait until the either we're stopped or the other threads are done.
1489 // This way we don't start loading all apps until the workspace has settled
1490 // down.
1491 synchronized (LoaderTask.this) {
1492 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001493
Joe Onorato36115782010-06-17 13:28:48 -04001494 mHandler.postIdle(new Runnable() {
1495 public void run() {
1496 synchronized (LoaderTask.this) {
1497 mLoadAndBindStepFinished = true;
1498 if (DEBUG_LOADERS) {
1499 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001500 }
Joe Onorato36115782010-06-17 13:28:48 -04001501 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001502 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001503 }
Joe Onorato36115782010-06-17 13:28:48 -04001504 });
1505
Michael Jurkac7700af2013-05-14 20:17:58 +02001506 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001507 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001508 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1509 // wait no longer than 1sec at a time
1510 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001511 } catch (InterruptedException ex) {
1512 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001513 }
1514 }
Joe Onorato36115782010-06-17 13:28:48 -04001515 if (DEBUG_LOADERS) {
1516 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001517 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001518 + "ms for previous step to finish binding");
1519 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001520 }
Joe Onorato36115782010-06-17 13:28:48 -04001521 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001522
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001523 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001524 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001525 // Ensure that we have a valid page index to load synchronously
1526 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1527 "valid page index");
1528 }
1529 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1530 // Ensure that we don't try and bind a specified page when the pages have not been
1531 // loaded already (we should load everything asynchronously in that case)
1532 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1533 }
1534 synchronized (mLock) {
1535 if (mIsLoaderTaskRunning) {
1536 // Ensure that we are never running the background loading at this point since
1537 // we also touch the background collections
1538 throw new RuntimeException("Error! Background loading is already running");
1539 }
1540 }
1541
1542 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1543 // data structures, we can't allow any other thread to touch that data, but because
1544 // this call is synchronous, we can get away with not locking).
1545
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001546 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001547 // operations from the previous activity. We need to ensure that all queued operations
1548 // are executed before any synchronous binding work is done.
1549 mHandler.flush();
1550
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001551 // Divide the set of loaded items into those that we are binding synchronously, and
1552 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001553 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1555 // arise from that.
1556 onlyBindAllApps();
1557 }
1558
Joe Onorato36115782010-06-17 13:28:48 -04001559 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001560 boolean isUpgrade = false;
1561
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001562 synchronized (mLock) {
1563 mIsLoaderTaskRunning = true;
1564 }
Joe Onorato36115782010-06-17 13:28:48 -04001565 // Optimize for end-user experience: if the Launcher is up and // running with the
1566 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1567 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001568 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001569 // Elevate priority when Home launches for the first time to avoid
1570 // starving at boot time. Staring at a blank home is not cool.
1571 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001572 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1573 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001574 android.os.Process.setThreadPriority(mIsLaunching
1575 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1576 }
Winson Chung64359a52013-07-08 17:17:08 -07001577 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001578 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001579
Joe Onorato36115782010-06-17 13:28:48 -04001580 if (mStopped) {
1581 break keep_running;
1582 }
1583
1584 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1585 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001586 synchronized (mLock) {
1587 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001588 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001589 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1590 }
1591 }
Joe Onorato36115782010-06-17 13:28:48 -04001592 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001593
1594 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001595 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1596 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001597
1598 // Restore the default thread priority after we are done loading items
1599 synchronized (mLock) {
1600 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1601 }
Joe Onorato36115782010-06-17 13:28:48 -04001602 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001603
Winson Chungaac01e12011-08-17 10:37:13 -07001604 // Update the saved icons if necessary
1605 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001606 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001607 for (Object key : sBgDbIconCache.keySet()) {
1608 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1609 }
1610 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001611 }
Winson Chungaac01e12011-08-17 10:37:13 -07001612
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001613 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001614 // Ensure that all the applications that are in the system are
1615 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001616 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001617 verifyApplications();
1618 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001619 }
1620
Joe Onorato36115782010-06-17 13:28:48 -04001621 // Clear out this reference, otherwise we end up holding it until all of the
1622 // callback runnables are done.
1623 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001624
Joe Onorato36115782010-06-17 13:28:48 -04001625 synchronized (mLock) {
1626 // If we are still the last one to be scheduled, remove ourselves.
1627 if (mLoaderTask == this) {
1628 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001629 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001630 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001631 }
Joe Onorato36115782010-06-17 13:28:48 -04001632 }
1633
1634 public void stopLocked() {
1635 synchronized (LoaderTask.this) {
1636 mStopped = true;
1637 this.notify();
1638 }
1639 }
1640
1641 /**
1642 * Gets the callbacks object. If we've been stopped, or if the launcher object
1643 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1644 * object that was around when the deferred message was scheduled, and if there's
1645 * a new Callbacks object around then also return null. This will save us from
1646 * calling onto it with data that will be ignored.
1647 */
1648 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1649 synchronized (mLock) {
1650 if (mStopped) {
1651 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001652 }
Joe Onorato36115782010-06-17 13:28:48 -04001653
1654 if (mCallbacks == null) {
1655 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001656 }
Joe Onorato36115782010-06-17 13:28:48 -04001657
1658 final Callbacks callbacks = mCallbacks.get();
1659 if (callbacks != oldCallbacks) {
1660 return null;
1661 }
1662 if (callbacks == null) {
1663 Log.w(TAG, "no mCallbacks");
1664 return null;
1665 }
1666
1667 return callbacks;
1668 }
1669 }
1670
Winson Chungc763c4e2013-07-19 13:49:06 -07001671 private void verifyApplications() {
1672 final Context context = mApp.getContext();
1673
1674 // Cross reference all the applications in our apps list with items in the workspace
1675 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001676 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001677 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001678 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001679 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001680 if (tmpInfos.isEmpty()) {
1681 // We are missing an application icon, so add this to the workspace
1682 added.add(app);
1683 // This is a rare event, so lets log it
1684 Log.e(TAG, "Missing Application on load: " + app);
1685 }
1686 }
1687 }
1688 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001689 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001690 }
1691 }
1692
Joe Onorato36115782010-06-17 13:28:48 -04001693 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001694 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001695 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001696 LauncherAppState app = LauncherAppState.getInstance();
1697 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001698 final int countX = (int) grid.numColumns;
1699 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001700
Adam Cohendcd297f2013-06-18 13:13:40 -07001701 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001702 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001703 // Return early if we detect that an item is under the hotseat button
1704 if (mCallbacks == null ||
1705 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001706 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001707 Log.e(TAG, "Error loading shortcut into hotseat " + item
1708 + " into position (" + item.screenId + ":" + item.cellX + ","
1709 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001710 return false;
1711 }
1712
Dan Sandler295ae182013-12-10 16:05:47 -05001713 final ItemInfo[][] hotseatItems =
1714 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1715
Adam Cohenae4409d2013-11-26 10:34:59 -08001716 if (item.screenId >= grid.numHotseatIcons) {
1717 Log.e(TAG, "Error loading shortcut " + item
1718 + " into hotseat position " + item.screenId
1719 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1720 + ")");
1721 return false;
1722 }
1723
Dan Sandler295ae182013-12-10 16:05:47 -05001724 if (hotseatItems != null) {
1725 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001726 Log.e(TAG, "Error loading shortcut into hotseat " + item
1727 + " into position (" + item.screenId + ":" + item.cellX + ","
1728 + item.cellY + ") occupied by "
1729 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1730 [(int) item.screenId][0]);
1731 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001732 } else {
1733 hotseatItems[(int) item.screenId][0] = item;
1734 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001735 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001736 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001737 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001738 items[(int) item.screenId][0] = item;
1739 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001740 return true;
1741 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001742 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1743 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001744 return true;
1745 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001746
Adam Cohendcd297f2013-06-18 13:13:40 -07001747 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001748 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001749 occupied.put(item.screenId, items);
1750 }
1751
Dan Sandler295ae182013-12-10 16:05:47 -05001752 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001753 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1754 item.cellX < 0 || item.cellY < 0 ||
1755 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1756 Log.e(TAG, "Error loading shortcut " + item
1757 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1758 + item.cellX + "," + item.cellY
1759 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1760 return false;
1761 }
1762
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001763 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001764 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1765 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001767 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001768 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001769 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001770 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001771 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001772 return false;
1773 }
1774 }
1775 }
1776 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1777 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001778 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001779 }
1780 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001781
Joe Onorato36115782010-06-17 13:28:48 -04001782 return true;
1783 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001784
Winson Chungba9c37f2013-08-30 14:11:37 -07001785 /** Clears all the sBg data structures */
1786 private void clearSBgDataStructures() {
1787 synchronized (sBgLock) {
1788 sBgWorkspaceItems.clear();
1789 sBgAppWidgets.clear();
1790 sBgFolders.clear();
1791 sBgItemsIdMap.clear();
1792 sBgDbIconCache.clear();
1793 sBgWorkspaceScreens.clear();
1794 }
1795 }
1796
Dan Sandlerd5024042014-01-09 15:01:33 -05001797 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001798 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001799 // Log to disk
1800 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1801
Joe Onorato36115782010-06-17 13:28:48 -04001802 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001803
Joe Onorato36115782010-06-17 13:28:48 -04001804 final Context context = mContext;
1805 final ContentResolver contentResolver = context.getContentResolver();
1806 final PackageManager manager = context.getPackageManager();
1807 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1808 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001809
Winson Chung892c74d2013-08-22 16:15:50 -07001810 LauncherAppState app = LauncherAppState.getInstance();
1811 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1812 int countX = (int) grid.numColumns;
1813 int countY = (int) grid.numRows;
1814
Dan Sandlerd5024042014-01-09 15:01:33 -05001815 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1816 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1817 LauncherAppState.getLauncherProvider().deleteDatabase();
1818 }
1819
1820 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1821 // append the user's Launcher2 shortcuts
1822 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1823 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1824 } else {
1825 // Make sure the default workspace is loaded
1826 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1827 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1828 }
Adam Cohene25af792013-06-06 23:08:25 -07001829
Adam Cohen71483f42014-05-15 14:04:01 -07001830 // This code path is for our old migration code and should no longer be exercised
1831 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001832
Winson Chung9f9f00b2013-11-15 13:27:00 -08001833 // Log to disk
1834 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001835
Winson Chung2abf94d2012-07-18 18:16:38 -07001836 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001837 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001838
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001839 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001840 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001841 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001842 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001843 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001844
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001845 // +1 for the hotseat (it can be larger than the workspace)
1846 // Load workspace in reverse order to ensure that latest items are loaded first (and
1847 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001848 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001849
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001850 try {
1851 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1852 final int intentIndex = c.getColumnIndexOrThrow
1853 (LauncherSettings.Favorites.INTENT);
1854 final int titleIndex = c.getColumnIndexOrThrow
1855 (LauncherSettings.Favorites.TITLE);
1856 final int iconTypeIndex = c.getColumnIndexOrThrow(
1857 LauncherSettings.Favorites.ICON_TYPE);
1858 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1859 final int iconPackageIndex = c.getColumnIndexOrThrow(
1860 LauncherSettings.Favorites.ICON_PACKAGE);
1861 final int iconResourceIndex = c.getColumnIndexOrThrow(
1862 LauncherSettings.Favorites.ICON_RESOURCE);
1863 final int containerIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.CONTAINER);
1865 final int itemTypeIndex = c.getColumnIndexOrThrow(
1866 LauncherSettings.Favorites.ITEM_TYPE);
1867 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1868 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001869 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1870 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 final int screenIndex = c.getColumnIndexOrThrow(
1872 LauncherSettings.Favorites.SCREEN);
1873 final int cellXIndex = c.getColumnIndexOrThrow
1874 (LauncherSettings.Favorites.CELLX);
1875 final int cellYIndex = c.getColumnIndexOrThrow
1876 (LauncherSettings.Favorites.CELLY);
1877 final int spanXIndex = c.getColumnIndexOrThrow
1878 (LauncherSettings.Favorites.SPANX);
1879 final int spanYIndex = c.getColumnIndexOrThrow(
1880 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001881 final int restoredIndex = c.getColumnIndexOrThrow(
1882 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001883 final int profileIdIndex = c.getColumnIndexOrThrow(
1884 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001885 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1886 //final int displayModeIndex = c.getColumnIndexOrThrow(
1887 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001888
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001889 ShortcutInfo info;
1890 String intentDescription;
1891 LauncherAppWidgetInfo appWidgetInfo;
1892 int container;
1893 long id;
1894 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001895 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001896
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001897 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001898 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001899 try {
1900 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001901 boolean restored = 0 != c.getInt(restoredIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001902
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001903 switch (itemType) {
1904 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1905 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001906 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001907 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001908 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001909 user = mUserManager.getUserForSerialNumber(serialNumber);
1910 if (user == null) {
1911 // User has been deleted remove the item.
1912 itemsToRemove.add(id);
1913 continue;
1914 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 try {
1916 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001917 ComponentName cn = intent.getComponent();
Kenny Guyed131872014-04-30 03:02:21 +01001918 if (cn != null && !isValidPackageActivity(context, cn, user)) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001919 if (restored) {
1920 // might be installed later
1921 Launcher.addDumpLog(TAG,
1922 "package not yet restored: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001923 } else {
Chris Wrenf4d08112014-01-16 18:13:56 -05001924 if (!mAppsCanBeOnRemoveableStorage) {
1925 // Log the invalid package, and remove it
1926 Launcher.addDumpLog(TAG,
1927 "Invalid package removed: " + cn, true);
1928 itemsToRemove.add(id);
1929 } else {
1930 // If apps can be on external storage, then we just
1931 // leave them for the user to remove (maybe add
1932 // visual treatment to it)
1933 Launcher.addDumpLog(TAG,
1934 "Invalid package found: " + cn, true);
1935 }
1936 continue;
Winson Chungee055712013-07-30 14:46:24 -07001937 }
Chris Wrenf4d08112014-01-16 18:13:56 -05001938 } else if (restored) {
1939 // no special handling necessary for this restored item
1940 restoredRows.add(id);
1941 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07001942 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001944 Launcher.addDumpLog(TAG,
1945 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001946 continue;
1947 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001948
Chris Wrenf4d08112014-01-16 18:13:56 -05001949 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01001950 if (user.equals(UserHandleCompat.myUserHandle())) {
1951 Launcher.addDumpLog(TAG,
1952 "constructing info for partially restored package",
1953 true);
1954 info = getRestoredItemInfo(c, titleIndex, intent);
1955 intent = getRestoredItemIntent(c, context, intent);
1956 } else {
1957 // Don't restore items for other profiles.
1958 itemsToRemove.add(id);
1959 continue;
1960 }
Chris Wrenf4d08112014-01-16 18:13:56 -05001961 } else if (itemType ==
1962 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Kenny Guyed131872014-04-30 03:02:21 +01001963 info = getShortcutInfo(manager, intent, user, context, c, iconIndex,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 titleIndex, mLabelCache);
1965 } else {
1966 info = getShortcutInfo(c, context, iconTypeIndex,
1967 iconPackageIndex, iconResourceIndex, iconIndex,
1968 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001969
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001970 // App shortcuts that used to be automatically added to Launcher
1971 // didn't always have the correct intent flags set, so do that
1972 // here
1973 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001974 intent.getCategories() != null &&
1975 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001976 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001977 intent.addFlags(
1978 Intent.FLAG_ACTIVITY_NEW_TASK |
1979 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1980 }
Michael Jurka96879562012-03-22 05:54:33 -07001981 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001982
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001983 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001984 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001985 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001986 container = c.getInt(containerIndex);
1987 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001988 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001989 info.cellX = c.getInt(cellXIndex);
1990 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001991 info.spanX = 1;
1992 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01001993 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Adam Cohenae4409d2013-11-26 10:34:59 -08001994
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001995 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001996 deleteOnInvalidPlacement.set(false);
1997 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
1998 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001999 itemsToRemove.add(id);
2000 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002001 break;
2002 }
2003
2004 switch (container) {
2005 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2006 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2007 sBgWorkspaceItems.add(info);
2008 break;
2009 default:
2010 // Item is in a user folder
2011 FolderInfo folderInfo =
2012 findOrMakeFolder(sBgFolders, container);
2013 folderInfo.add(info);
2014 break;
2015 }
2016 sBgItemsIdMap.put(info.id, info);
2017
2018 // now that we've loaded everthing re-save it with the
2019 // icon in case it disappears somehow.
2020 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002021 } else {
2022 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002023 }
2024 break;
2025
2026 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2027 id = c.getLong(idIndex);
2028 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2029
2030 folderInfo.title = c.getString(titleIndex);
2031 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002032 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002033 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002034 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002035 folderInfo.cellX = c.getInt(cellXIndex);
2036 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002037 folderInfo.spanX = 1;
2038 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002039
Daniel Sandler8802e962010-05-26 16:28:16 -04002040 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002041 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002042 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002043 deleteOnInvalidPlacement)) {
2044 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002045 itemsToRemove.add(id);
2046 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002047 break;
2048 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002049
Joe Onorato9c1289c2009-08-17 11:03:03 -04002050 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002051 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2052 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2053 sBgWorkspaceItems.add(folderInfo);
2054 break;
Joe Onorato36115782010-06-17 13:28:48 -04002055 }
Joe Onorato17a89222011-02-08 17:26:11 -08002056
Chris Wrenf4d08112014-01-16 18:13:56 -05002057 if (restored) {
2058 // no special handling required for restored folders
2059 restoredRows.add(id);
2060 }
2061
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002062 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2063 sBgFolders.put(folderInfo.id, folderInfo);
2064 break;
2065
2066 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2067 // Read all Launcher-specific widget details
2068 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002069 String savedProvider = c.getString(appWidgetProviderIndex);
2070
Joe Onorato36115782010-06-17 13:28:48 -04002071 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002072
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002073 final AppWidgetProviderInfo provider =
2074 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04002075
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 if (!isSafeMode && (provider == null || provider.provider == null ||
2077 provider.provider.getPackageName() == null)) {
2078 String log = "Deleting widget that isn't installed anymore: id="
2079 + id + " appWidgetId=" + appWidgetId;
2080 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002081 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 itemsToRemove.add(id);
2083 } else {
2084 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2085 provider.provider);
2086 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002087 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 appWidgetInfo.cellX = c.getInt(cellXIndex);
2089 appWidgetInfo.cellY = c.getInt(cellYIndex);
2090 appWidgetInfo.spanX = c.getInt(spanXIndex);
2091 appWidgetInfo.spanY = c.getInt(spanYIndex);
2092 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2093 appWidgetInfo.minSpanX = minSpan[0];
2094 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04002095
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002096 container = c.getInt(containerIndex);
2097 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2098 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2099 Log.e(TAG, "Widget found where container != " +
2100 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2101 continue;
2102 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002103
Adam Cohene25af792013-06-06 23:08:25 -07002104 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002106 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002107 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002108 deleteOnInvalidPlacement)) {
2109 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002110 itemsToRemove.add(id);
2111 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 break;
2113 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002114 String providerName = provider.provider.flattenToString();
2115 if (!providerName.equals(savedProvider)) {
2116 ContentValues values = new ContentValues();
2117 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2118 providerName);
2119 String where = BaseColumns._ID + "= ?";
2120 String[] args = {Integer.toString(c.getInt(idIndex))};
2121 contentResolver.update(contentUri, values, where, args);
2122 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002123 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2124 sBgAppWidgets.add(appWidgetInfo);
2125 }
Joe Onorato36115782010-06-17 13:28:48 -04002126 break;
2127 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002128 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002129 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002130 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 }
2132 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002133 if (c != null) {
2134 c.close();
2135 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002136 }
2137
Winson Chungba9c37f2013-08-30 14:11:37 -07002138 // Break early if we've stopped loading
2139 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002140 clearSBgDataStructures();
2141 return false;
2142 }
2143
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 if (itemsToRemove.size() > 0) {
2145 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002146 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 // Remove dead items
2148 for (long id : itemsToRemove) {
2149 if (DEBUG_LOADERS) {
2150 Log.d(TAG, "Removed id = " + id);
2151 }
2152 // Don't notify content observers
2153 try {
2154 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2155 null, null);
2156 } catch (RemoteException e) {
2157 Log.w(TAG, "Could not remove id = " + id);
2158 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002159 }
2160 }
2161
Chris Wrenf4d08112014-01-16 18:13:56 -05002162 if (restoredRows.size() > 0) {
2163 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2164 LauncherSettings.Favorites.CONTENT_URI);
2165 // Update restored items that no longer require special handling
2166 try {
2167 StringBuilder selectionBuilder = new StringBuilder();
2168 selectionBuilder.append(LauncherSettings.Favorites._ID);
2169 selectionBuilder.append(" IN (");
2170 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2171 selectionBuilder.append(")");
2172 ContentValues values = new ContentValues();
2173 values.put(LauncherSettings.Favorites.RESTORED, 0);
2174 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2175 values, selectionBuilder.toString(), null);
2176 } catch (RemoteException e) {
2177 Log.w(TAG, "Could not update restored rows");
2178 }
2179 }
2180
Winson Chungc763c4e2013-07-19 13:49:06 -07002181 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002182 long maxScreenId = 0;
2183 // If we're importing we use the old screen order.
2184 for (ItemInfo item: sBgItemsIdMap.values()) {
2185 long screenId = item.screenId;
2186 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2187 !sBgWorkspaceScreens.contains(screenId)) {
2188 sBgWorkspaceScreens.add(screenId);
2189 if (screenId > maxScreenId) {
2190 maxScreenId = screenId;
2191 }
2192 }
2193 }
2194 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002195 // Log to disk
2196 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2197 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2198 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002199
Michael Jurka414300a2013-08-27 15:42:35 +02002200 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002201 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002202
2203 // Update the max item id after we load an old db
2204 long maxItemId = 0;
2205 // If we're importing we use the old screen order.
2206 for (ItemInfo item: sBgItemsIdMap.values()) {
2207 maxItemId = Math.max(maxItemId, item.id);
2208 }
Michael Jurka414300a2013-08-27 15:42:35 +02002209 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002210 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002211 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2212 for (Integer i : orderedScreens.keySet()) {
2213 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002214 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002215 // Log to disk
2216 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2217 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002218
2219 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002220 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002221 for (ItemInfo item: sBgItemsIdMap.values()) {
2222 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002223 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2224 unusedScreens.contains(screenId)) {
2225 unusedScreens.remove(screenId);
2226 }
2227 }
2228
2229 // If there are any empty screens remove them, and update.
2230 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002231 // Log to disk
2232 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2233 TextUtils.join(", ", unusedScreens), true);
2234
Winson Chung933bae62013-08-29 11:42:30 -07002235 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002236 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2237 }
2238 }
2239
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 if (DEBUG_LOADERS) {
2241 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2242 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002243 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002244 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002246
Daniel Sandler566da102013-06-25 23:43:45 -04002247 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002248 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002249 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002250 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251 line += " | ";
2252 }
Winson Chung892c74d2013-08-22 16:15:50 -07002253 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002254 ItemInfo[][] screen = occupied.get(screenId);
2255 if (x < screen.length && y < screen[x].length) {
2256 line += (screen[x][y] != null) ? "#" : ".";
2257 } else {
2258 line += "!";
2259 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002260 }
Joe Onorato36115782010-06-17 13:28:48 -04002261 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002263 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002264 }
Joe Onorato36115782010-06-17 13:28:48 -04002265 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002266 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002267 }
2268
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002269 /** Filters the set of items who are directly or indirectly (via another container) on the
2270 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002271 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002272 ArrayList<ItemInfo> allWorkspaceItems,
2273 ArrayList<ItemInfo> currentScreenItems,
2274 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002275 // Purge any null ItemInfos
2276 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2277 while (iter.hasNext()) {
2278 ItemInfo i = iter.next();
2279 if (i == null) {
2280 iter.remove();
2281 }
2282 }
2283
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002284 // Order the set of items by their containers first, this allows use to walk through the
2285 // list sequentially, build up a list of containers that are in the specified screen,
2286 // as well as all items in those containers.
2287 Set<Long> itemsOnScreen = new HashSet<Long>();
2288 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2289 @Override
2290 public int compare(ItemInfo lhs, ItemInfo rhs) {
2291 return (int) (lhs.container - rhs.container);
2292 }
2293 });
2294 for (ItemInfo info : allWorkspaceItems) {
2295 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002296 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002297 currentScreenItems.add(info);
2298 itemsOnScreen.add(info.id);
2299 } else {
2300 otherScreenItems.add(info);
2301 }
2302 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2303 currentScreenItems.add(info);
2304 itemsOnScreen.add(info.id);
2305 } else {
2306 if (itemsOnScreen.contains(info.container)) {
2307 currentScreenItems.add(info);
2308 itemsOnScreen.add(info.id);
2309 } else {
2310 otherScreenItems.add(info);
2311 }
2312 }
2313 }
2314 }
2315
2316 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002317 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002318 ArrayList<LauncherAppWidgetInfo> appWidgets,
2319 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2320 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002321
2322 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002323 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002324 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002325 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002326 currentScreenWidgets.add(widget);
2327 } else {
2328 otherScreenWidgets.add(widget);
2329 }
2330 }
2331 }
2332
2333 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002334 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002335 HashMap<Long, ItemInfo> itemsIdMap,
2336 HashMap<Long, FolderInfo> folders,
2337 HashMap<Long, FolderInfo> currentScreenFolders,
2338 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002339
2340 for (long id : folders.keySet()) {
2341 ItemInfo info = itemsIdMap.get(id);
2342 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002343 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002344 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002345 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002346 currentScreenFolders.put(id, folder);
2347 } else {
2348 otherScreenFolders.put(id, folder);
2349 }
2350 }
2351 }
2352
2353 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2354 * right) */
2355 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002356 final LauncherAppState app = LauncherAppState.getInstance();
2357 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002358 // XXX: review this
2359 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002360 @Override
2361 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002362 int cellCountX = (int) grid.numColumns;
2363 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002364 int screenOffset = cellCountX * cellCountY;
2365 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002367 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002368 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002369 rhs.cellY * cellCountX + rhs.cellX);
2370 return (int) (lr - rr);
2371 }
2372 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002373 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002374
Adam Cohendcd297f2013-06-18 13:13:40 -07002375 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2376 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 final Runnable r = new Runnable() {
2378 @Override
2379 public void run() {
2380 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2381 if (callbacks != null) {
2382 callbacks.bindScreens(orderedScreens);
2383 }
2384 }
2385 };
2386 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2387 }
2388
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002389 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2390 final ArrayList<ItemInfo> workspaceItems,
2391 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2392 final HashMap<Long, FolderInfo> folders,
2393 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002394
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002395 final boolean postOnMainThread = (deferredBindRunnables != null);
2396
2397 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002398 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002399 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002400 final int start = i;
2401 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002402 final Runnable r = new Runnable() {
2403 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002404 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002405 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002406 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002407 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2408 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002409 }
2410 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002411 };
2412 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002413 synchronized (deferredBindRunnables) {
2414 deferredBindRunnables.add(r);
2415 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002416 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002417 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002418 }
Joe Onorato36115782010-06-17 13:28:48 -04002419 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002420
2421 // Bind the folders
2422 if (!folders.isEmpty()) {
2423 final Runnable r = new Runnable() {
2424 public void run() {
2425 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2426 if (callbacks != null) {
2427 callbacks.bindFolders(folders);
2428 }
2429 }
2430 };
2431 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002432 synchronized (deferredBindRunnables) {
2433 deferredBindRunnables.add(r);
2434 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002436 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002437 }
2438 }
2439
2440 // Bind the widgets, one at a time
2441 N = appWidgets.size();
2442 for (int i = 0; i < N; i++) {
2443 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2444 final Runnable r = new Runnable() {
2445 public void run() {
2446 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2447 if (callbacks != null) {
2448 callbacks.bindAppWidget(widget);
2449 }
2450 }
2451 };
2452 if (postOnMainThread) {
2453 deferredBindRunnables.add(r);
2454 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002455 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 }
2457 }
2458 }
2459
2460 /**
2461 * Binds all loaded data to actual views on the main thread.
2462 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002463 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002464 final long t = SystemClock.uptimeMillis();
2465 Runnable r;
2466
2467 // Don't use these two variables in any of the callback runnables.
2468 // Otherwise we hold a reference to them.
2469 final Callbacks oldCallbacks = mCallbacks.get();
2470 if (oldCallbacks == null) {
2471 // This launcher has exited and nobody bothered to tell us. Just bail.
2472 Log.w(TAG, "LoaderTask running with no launcher");
2473 return;
2474 }
2475
Winson Chung9b9fb962013-11-15 15:39:34 -08002476 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002477 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2478 ArrayList<LauncherAppWidgetInfo> appWidgets =
2479 new ArrayList<LauncherAppWidgetInfo>();
2480 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2481 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002482 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002483 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484 workspaceItems.addAll(sBgWorkspaceItems);
2485 appWidgets.addAll(sBgAppWidgets);
2486 folders.putAll(sBgFolders);
2487 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002488 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 }
2490
Derek Prothro7aff3992013-12-10 14:00:37 -05002491 final boolean isLoadingSynchronously =
2492 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002493 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002494 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002495 if (currScreen >= orderedScreenIds.size()) {
2496 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002497 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002498 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002499 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002500 final long currentScreenId = currentScreen < 0
2501 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002502
2503 // Load all the items that are on the current page first (and in the process, unbind
2504 // all the existing workspace items before we call startBinding() below.
2505 unbindWorkspaceItemsOnMainThread();
2506
2507 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2509 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2510 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2511 new ArrayList<LauncherAppWidgetInfo>();
2512 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2513 new ArrayList<LauncherAppWidgetInfo>();
2514 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2515 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2516
Winson Chung9b9fb962013-11-15 15:39:34 -08002517 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002518 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002519 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002521 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 otherFolders);
2523 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2524 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2525
2526 // Tell the workspace that we're about to start binding items
2527 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002528 public void run() {
2529 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2530 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002531 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002532 }
2533 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 };
Winson Chung81b52252012-08-27 15:34:29 -07002535 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536
Adam Cohendcd297f2013-06-18 13:13:40 -07002537 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2538
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 // Load items on the current page
2540 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2541 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002542 if (isLoadingSynchronously) {
2543 r = new Runnable() {
2544 public void run() {
2545 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002546 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002547 callbacks.onPageBoundSynchronously(currentScreen);
2548 }
2549 }
2550 };
Winson Chung81b52252012-08-27 15:34:29 -07002551 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002552 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553
Winson Chung4a2afa32012-07-19 14:53:05 -07002554 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2555 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002556 synchronized (mDeferredBindRunnables) {
2557 mDeferredBindRunnables.clear();
2558 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002559 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002560 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002561
2562 // Tell the workspace that we're done binding items
2563 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002564 public void run() {
2565 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2566 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002567 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002568 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569
Winson Chung98e030b2012-05-07 16:01:11 -07002570 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002571 if (DEBUG_LOADERS) {
2572 Log.d(TAG, "bound workspace in "
2573 + (SystemClock.uptimeMillis()-t) + "ms");
2574 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002575
2576 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002577 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002578 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002579 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002580 synchronized (mDeferredBindRunnables) {
2581 mDeferredBindRunnables.add(r);
2582 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002583 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002584 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002585 }
Joe Onorato36115782010-06-17 13:28:48 -04002586 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002587
Joe Onorato36115782010-06-17 13:28:48 -04002588 private void loadAndBindAllApps() {
2589 if (DEBUG_LOADERS) {
2590 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2591 }
2592 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002593 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002594 synchronized (LoaderTask.this) {
2595 if (mStopped) {
2596 return;
2597 }
2598 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002599 }
Joe Onorato36115782010-06-17 13:28:48 -04002600 } else {
2601 onlyBindAllApps();
2602 }
2603 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002604
Joe Onorato36115782010-06-17 13:28:48 -04002605 private void onlyBindAllApps() {
2606 final Callbacks oldCallbacks = mCallbacks.get();
2607 if (oldCallbacks == null) {
2608 // This launcher has exited and nobody bothered to tell us. Just bail.
2609 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2610 return;
2611 }
2612
2613 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002614 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002615 final ArrayList<AppInfo> list
2616 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002617 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002618 public void run() {
2619 final long t = SystemClock.uptimeMillis();
2620 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2621 if (callbacks != null) {
2622 callbacks.bindAllApplications(list);
2623 }
2624 if (DEBUG_LOADERS) {
2625 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2626 + (SystemClock.uptimeMillis()-t) + "ms");
2627 }
2628 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002629 };
2630 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002631 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002632 r.run();
2633 } else {
2634 mHandler.post(r);
2635 }
Joe Onorato36115782010-06-17 13:28:48 -04002636 }
2637
Winson Chung64359a52013-07-08 17:17:08 -07002638 private void loadAllApps() {
2639 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002640
Joe Onorato36115782010-06-17 13:28:48 -04002641 final Callbacks oldCallbacks = mCallbacks.get();
2642 if (oldCallbacks == null) {
2643 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002644 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002645 return;
2646 }
2647
2648 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2649 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2650
Kenny Guyed131872014-04-30 03:02:21 +01002651 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2652
Winson Chung64359a52013-07-08 17:17:08 -07002653 // Clear the list of apps
2654 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002655 for (UserHandleCompat user : profiles) {
2656 // Query for the set of apps
2657 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2658 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2659 if (DEBUG_LOADERS) {
2660 Log.d(TAG, "getActivityList took "
2661 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2662 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2663 }
2664 // Fail if we don't have any apps
2665 if (apps == null || apps.isEmpty()) {
2666 return;
2667 }
2668 // Sort the applications by name
2669 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2670 Collections.sort(apps,
2671 new LauncherModel.ShortcutNameComparator(mLabelCache));
2672 if (DEBUG_LOADERS) {
2673 Log.d(TAG, "sort took "
2674 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2675 }
Joe Onorato36115782010-06-17 13:28:48 -04002676
Kenny Guyed131872014-04-30 03:02:21 +01002677 // Create the ApplicationInfos
2678 for (int i = 0; i < apps.size(); i++) {
2679 LauncherActivityInfoCompat app = apps.get(i);
2680 // This builds the icon bitmaps.
2681 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2682 }
Winson Chung64359a52013-07-08 17:17:08 -07002683 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002684 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002685 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2686 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002687
2688 // Post callback on main thread
2689 mHandler.post(new Runnable() {
2690 public void run() {
2691 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002692 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002693 if (callbacks != null) {
2694 callbacks.bindAllApplications(added);
2695 if (DEBUG_LOADERS) {
2696 Log.d(TAG, "bound " + added.size() + " apps in "
2697 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2698 }
2699 } else {
2700 Log.i(TAG, "not binding apps: no Launcher activity");
2701 }
2702 }
2703 });
2704
Joe Onorato36115782010-06-17 13:28:48 -04002705 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002706 Log.d(TAG, "Icons processed in "
2707 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002708 }
2709 }
2710
2711 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002712 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002713 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2714 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2715 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2716 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2717 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2718 }
Joe Onorato36115782010-06-17 13:28:48 -04002719 }
2720 }
2721
2722 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002723 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002724 }
2725
2726 private class PackageUpdatedTask implements Runnable {
2727 int mOp;
2728 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002729 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002730
2731 public static final int OP_NONE = 0;
2732 public static final int OP_ADD = 1;
2733 public static final int OP_UPDATE = 2;
2734 public static final int OP_REMOVE = 3; // uninstlled
2735 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2736
2737
Kenny Guyed131872014-04-30 03:02:21 +01002738 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002739 mOp = op;
2740 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002741 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002742 }
2743
2744 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002745 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002746
2747 final String[] packages = mPackages;
2748 final int N = packages.length;
2749 switch (mOp) {
2750 case OP_ADD:
2751 for (int i=0; i<N; i++) {
2752 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002753 mIconCache.remove(packages[i], mUser);
2754 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002755 }
2756 break;
2757 case OP_UPDATE:
2758 for (int i=0; i<N; i++) {
2759 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002760 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002761 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002762 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002763 }
2764 break;
2765 case OP_REMOVE:
2766 case OP_UNAVAILABLE:
2767 for (int i=0; i<N; i++) {
2768 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002769 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002770 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002771 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002772 }
2773 break;
2774 }
2775
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002776 ArrayList<AppInfo> added = null;
2777 ArrayList<AppInfo> modified = null;
2778 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002779
Adam Cohen487f7dd2012-06-28 18:12:10 -07002780 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002781 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002782 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002783 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002784 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002785 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002786 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002787 }
Winson Chung5d55f332012-07-16 20:45:03 -07002788 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002789 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002790 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002791 }
2792
Joe Onorato36115782010-06-17 13:28:48 -04002793 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2794 if (callbacks == null) {
2795 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2796 return;
2797 }
2798
2799 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002800 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002801 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002802 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002803 addAndBindAddedWorkspaceApps(context, addedInfos);
2804 } else {
2805 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002806 }
Joe Onorato36115782010-06-17 13:28:48 -04002807 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002808
Joe Onorato36115782010-06-17 13:28:48 -04002809 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002810 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002811
2812 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002813 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002814 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002815 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002816 for (ItemInfo i : infos) {
2817 if (isShortcutInfoUpdateable(i)) {
2818 ShortcutInfo info = (ShortcutInfo) i;
2819 info.title = a.title.toString();
2820 updateItemInDatabase(context, info);
2821 }
2822 }
2823 }
2824
Joe Onorato36115782010-06-17 13:28:48 -04002825 mHandler.post(new Runnable() {
2826 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002827 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2828 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002829 callbacks.bindAppsUpdated(modifiedFinal);
2830 }
2831 }
2832 });
2833 }
Winson Chung83892cc2013-05-01 16:53:33 -07002834
Winson Chungdf95eb12013-10-16 14:57:07 -07002835 final ArrayList<String> removedPackageNames =
2836 new ArrayList<String>();
2837 if (mOp == OP_REMOVE) {
2838 // Mark all packages in the broadcast to be removed
2839 removedPackageNames.addAll(Arrays.asList(packages));
2840 } else if (mOp == OP_UPDATE) {
2841 // Mark disabled packages in the broadcast to be removed
2842 final PackageManager pm = context.getPackageManager();
2843 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002844 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002845 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002846 }
2847 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002848 }
2849 // Remove all the components associated with this package
2850 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002851 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002852 for (ItemInfo i : infos) {
2853 deleteItemFromDatabase(context, i);
2854 }
2855 }
2856 // Remove all the specific components
2857 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002858 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002859 for (ItemInfo i : infos) {
2860 deleteItemFromDatabase(context, i);
2861 }
2862 }
2863 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2864 // Remove any queued items from the install queue
2865 String spKey = LauncherAppState.getSharedPreferencesKey();
2866 SharedPreferences sp =
2867 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2868 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2869 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002870 mHandler.post(new Runnable() {
2871 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002872 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2873 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01002874 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002875 }
2876 }
2877 });
Joe Onoratobe386092009-11-17 17:32:16 -08002878 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002879
Michael Jurkac402cd92013-05-20 15:49:32 +02002880 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01002881 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002882 mHandler.post(new Runnable() {
2883 @Override
2884 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002885 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2886 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002887 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002888 }
2889 }
2890 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002891
2892 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002893 mHandler.post(new Runnable() {
2894 public void run() {
2895 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2896 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002897 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002898 }
2899 }
2900 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002901 }
2902 }
2903
Michael Jurkac402cd92013-05-20 15:49:32 +02002904 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2905 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2906 PackageManager packageManager = context.getPackageManager();
2907 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2908 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2909 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2910 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2911 Collections.sort(widgetsAndShortcuts,
2912 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2913 return widgetsAndShortcuts;
2914 }
2915
Kenny Guyed131872014-04-30 03:02:21 +01002916 private static boolean isPackageDisabled(Context context, String packageName,
2917 UserHandleCompat user) {
2918 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
2919 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07002920 }
Adam Cohen556f6132014-01-15 15:18:08 -08002921
Kenny Guyed131872014-04-30 03:02:21 +01002922 public static boolean isValidPackageActivity(Context context, ComponentName cn,
2923 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07002924 if (cn == null) {
2925 return false;
2926 }
Kenny Guyed131872014-04-30 03:02:21 +01002927 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
2928 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002929 return false;
2930 }
Kenny Guyed131872014-04-30 03:02:21 +01002931 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07002932 }
2933
Joe Onorato9c1289c2009-08-17 11:03:03 -04002934 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05002935 * Make an ShortcutInfo object for a restored application or shortcut item that points
2936 * to a package that is not yet installed on the system.
2937 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05002938 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002939 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05002940 if (cursor != null) {
2941 info.title = cursor.getString(titleIndex);
2942 } else {
2943 info.title = "";
2944 }
Kenny Guyed131872014-04-30 03:02:21 +01002945 info.user = UserHandleCompat.myUserHandle();
2946 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user));
Chris Wrenf4d08112014-01-16 18:13:56 -05002947 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05002948 info.restoredIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05002949 return info;
2950 }
2951
2952 /**
2953 * Make an Intent object for a restored application or shortcut item that points
2954 * to the market page for the item.
2955 */
2956 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05002957 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05002958 ComponentName componentName = intent.getComponent();
2959 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
2960 Uri marketUri = new Uri.Builder()
2961 .scheme("market")
2962 .authority("details")
2963 .appendQueryParameter("id", componentName.getPackageName())
2964 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05002965 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05002966 marketIntent.setData(marketUri);
2967 return marketIntent;
2968 }
2969
2970 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002971 * This is called from the code that adds shortcuts from the intent receiver. This
2972 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002973 */
Kenny Guyed131872014-04-30 03:02:21 +01002974 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
2975 UserHandleCompat user, Context context) {
2976 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002977 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002978
Joe Onorato56d82912010-03-07 14:32:10 -05002979 /**
2980 * Make an ShortcutInfo object for a shortcut that is an application.
2981 *
2982 * If c is not null, then it will be used to fill in missing data like the title and icon.
2983 */
Kenny Guyed131872014-04-30 03:02:21 +01002984 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
2985 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
2986 HashMap<Object, CharSequence> labelCache) {
2987 if (user == null) {
2988 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002989 return null;
2990 }
2991
Kenny Guyed131872014-04-30 03:02:21 +01002992 ComponentName componentName = intent.getComponent();
2993 if (componentName == null) {
2994 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
2995 return null;
2996 }
2997
2998 Intent newIntent = new Intent(intent.getAction(), null);
2999 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3000 newIntent.setComponent(componentName);
3001 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
3002 if (lai == null) {
3003 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3004 return null;
3005 }
3006
3007 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003008
Joe Onorato56d82912010-03-07 14:32:10 -05003009 // the resource -- This may implicitly give us back the fallback icon,
3010 // but don't worry about that. All we're doing with usingFallbackIcon is
3011 // to avoid saving lots of copies of that in the database, and most apps
3012 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003013 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003014
Joe Onorato56d82912010-03-07 14:32:10 -05003015 // the db
3016 if (icon == null) {
3017 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003018 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003019 }
3020 }
3021 // the fallback icon
3022 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003023 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003024 info.usingFallbackIcon = true;
3025 }
3026 info.setIcon(icon);
3027
Kenny Guyed131872014-04-30 03:02:21 +01003028 // From the cache.
3029 if (labelCache != null) {
3030 info.title = labelCache.get(componentName);
3031 }
3032
Joe Onorato56d82912010-03-07 14:32:10 -05003033 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003034 if (info.title == null && lai != null) {
3035 info.title = lai.getLabel();
3036 if (labelCache != null) {
3037 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003038 }
Joe Onorato56d82912010-03-07 14:32:10 -05003039 }
3040 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003041 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003042 if (c != null) {
3043 info.title = c.getString(titleIndex);
3044 }
3045 }
3046 // fall back to the class name of the activity
3047 if (info.title == null) {
3048 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003049 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003050 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003051 info.user = user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003052 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003053 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003054
Winson Chung64359a52013-07-08 17:17:08 -07003055 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3056 ItemInfoFilter f) {
3057 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3058 for (ItemInfo i : infos) {
3059 if (i instanceof ShortcutInfo) {
3060 ShortcutInfo info = (ShortcutInfo) i;
3061 ComponentName cn = info.intent.getComponent();
3062 if (cn != null && f.filterItem(null, info, cn)) {
3063 filtered.add(info);
3064 }
3065 } else if (i instanceof FolderInfo) {
3066 FolderInfo info = (FolderInfo) i;
3067 for (ShortcutInfo s : info.contents) {
3068 ComponentName cn = s.intent.getComponent();
3069 if (cn != null && f.filterItem(info, s, cn)) {
3070 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003071 }
3072 }
Winson Chung64359a52013-07-08 17:17:08 -07003073 } else if (i instanceof LauncherAppWidgetInfo) {
3074 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3075 ComponentName cn = info.providerName;
3076 if (cn != null && f.filterItem(null, info, cn)) {
3077 filtered.add(info);
3078 }
Winson Chung8a435102012-08-30 17:16:53 -07003079 }
3080 }
Winson Chung64359a52013-07-08 17:17:08 -07003081 return new ArrayList<ItemInfo>(filtered);
3082 }
3083
Kenny Guyed131872014-04-30 03:02:21 +01003084 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3085 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003086 ItemInfoFilter filter = new ItemInfoFilter() {
3087 @Override
3088 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003089 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003090 }
3091 };
3092 return filterItemInfos(sBgItemsIdMap.values(), filter);
3093 }
3094
Kenny Guyed131872014-04-30 03:02:21 +01003095 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3096 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003097 ItemInfoFilter filter = new ItemInfoFilter() {
3098 @Override
3099 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003100 if (info.user == null) {
3101 return cn.equals(cname);
3102 } else {
3103 return cn.equals(cname) && info.user.equals(user);
3104 }
Winson Chung64359a52013-07-08 17:17:08 -07003105 }
3106 };
3107 return filterItemInfos(sBgItemsIdMap.values(), filter);
3108 }
3109
3110 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3111 if (i instanceof ShortcutInfo) {
3112 ShortcutInfo info = (ShortcutInfo) i;
3113 // We need to check for ACTION_MAIN otherwise getComponent() might
3114 // return null for some shortcuts (for instance, for shortcuts to
3115 // web pages.)
3116 Intent intent = info.intent;
3117 ComponentName name = intent.getComponent();
3118 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3119 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3120 return true;
3121 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003122 // placeholder shortcuts get special treatment, let them through too.
3123 if (info.getRestoredIntent() != null) {
3124 return true;
3125 }
Winson Chung64359a52013-07-08 17:17:08 -07003126 }
3127 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003128 }
3129
3130 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003131 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003132 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003133 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003134 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3135 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003136
Joe Onorato56d82912010-03-07 14:32:10 -05003137 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003138 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003139 // Non-app shortcuts are only supported for current user.
3140 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003141 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003142
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003143 // TODO: If there's an explicit component and we can't install that, delete it.
3144
Joe Onorato56d82912010-03-07 14:32:10 -05003145 info.title = c.getString(titleIndex);
3146
Joe Onorato9c1289c2009-08-17 11:03:03 -04003147 int iconType = c.getInt(iconTypeIndex);
3148 switch (iconType) {
3149 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3150 String packageName = c.getString(iconPackageIndex);
3151 String resourceName = c.getString(iconResourceIndex);
3152 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003153 info.customIcon = false;
3154 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003155 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003156 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003157 if (resources != null) {
3158 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003159 icon = Utilities.createIconBitmap(
3160 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003161 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003162 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003163 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003164 }
Joe Onorato56d82912010-03-07 14:32:10 -05003165 // the db
3166 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003167 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003168 }
3169 // the fallback icon
3170 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003171 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003172 info.usingFallbackIcon = true;
3173 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003174 break;
3175 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003176 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003177 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003178 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003179 info.customIcon = false;
3180 info.usingFallbackIcon = true;
3181 } else {
3182 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003183 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003184 break;
3185 default:
Kenny Guyed131872014-04-30 03:02:21 +01003186 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003187 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003188 info.customIcon = false;
3189 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003190 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003191 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003192 return info;
3193 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003194
Michael Jurka931dc972011-08-05 15:08:15 -07003195 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003196 @SuppressWarnings("all") // suppress dead code warning
3197 final boolean debug = false;
3198 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003199 Log.d(TAG, "getIconFromCursor app="
3200 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3201 }
3202 byte[] data = c.getBlob(iconIndex);
3203 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003204 return Utilities.createIconBitmap(
3205 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003206 } catch (Exception e) {
3207 return null;
3208 }
3209 }
3210
Winson Chung3d503fb2011-07-13 17:25:49 -07003211 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3212 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003213 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003214 if (info == null) {
3215 return null;
3216 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003217 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003218
3219 return info;
3220 }
3221
Winson Chunga9abd0e2010-10-27 17:18:37 -07003222 /**
Winson Chung55cef262010-10-28 14:14:18 -07003223 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3224 */
3225 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3226 ComponentName component) {
3227 List<AppWidgetProviderInfo> widgets =
3228 AppWidgetManager.getInstance(context).getInstalledProviders();
3229 for (AppWidgetProviderInfo info : widgets) {
3230 if (info.provider.equals(component)) {
3231 return info;
3232 }
3233 }
3234 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003235 }
3236
Winson Chung68846fd2010-10-29 11:00:27 -07003237 /**
3238 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3239 */
3240 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3241 final PackageManager packageManager = context.getPackageManager();
3242 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3243 new ArrayList<WidgetMimeTypeHandlerData>();
3244
3245 final Intent supportsIntent =
3246 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3247 supportsIntent.setType(mimeType);
3248
3249 // Create a set of widget configuration components that we can test against
3250 final List<AppWidgetProviderInfo> widgets =
3251 AppWidgetManager.getInstance(context).getInstalledProviders();
3252 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3253 new HashMap<ComponentName, AppWidgetProviderInfo>();
3254 for (AppWidgetProviderInfo info : widgets) {
3255 configurationComponentToWidget.put(info.configure, info);
3256 }
3257
3258 // Run through each of the intents that can handle this type of clip data, and cross
3259 // reference them with the components that are actual configuration components
3260 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3261 PackageManager.MATCH_DEFAULT_ONLY);
3262 for (ResolveInfo info : activities) {
3263 final ActivityInfo activityInfo = info.activityInfo;
3264 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3265 activityInfo.name);
3266 if (configurationComponentToWidget.containsKey(infoComponent)) {
3267 supportedConfigurationActivities.add(
3268 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3269 configurationComponentToWidget.get(infoComponent)));
3270 }
3271 }
3272 return supportedConfigurationActivities;
3273 }
3274
Winson Chunga9abd0e2010-10-27 17:18:37 -07003275 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003276 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3277 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3278 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3279
Adam Cohend9198822011-11-22 16:42:47 -08003280 if (intent == null) {
3281 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3282 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3283 return null;
3284 }
3285
Joe Onorato0589f0f2010-02-08 13:44:00 -08003286 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003287 boolean customIcon = false;
3288 ShortcutIconResource iconResource = null;
3289
3290 if (bitmap != null && bitmap instanceof Bitmap) {
3291 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003292 customIcon = true;
3293 } else {
3294 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3295 if (extra != null && extra instanceof ShortcutIconResource) {
3296 try {
3297 iconResource = (ShortcutIconResource) extra;
3298 final PackageManager packageManager = context.getPackageManager();
3299 Resources resources = packageManager.getResourcesForApplication(
3300 iconResource.packageName);
3301 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003302 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003303 mIconCache.getFullResIcon(resources, id),
3304 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003305 } catch (Exception e) {
3306 Log.w(TAG, "Could not load shortcut icon: " + extra);
3307 }
3308 }
3309 }
3310
Michael Jurkac9d95c52011-08-29 14:03:34 -07003311 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003312
Kenny Guyed131872014-04-30 03:02:21 +01003313 // Only support intents for current user for now. Intents sent from other
3314 // users wouldn't get here without intent forwarding anyway.
3315 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003316 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003317 if (fallbackIcon != null) {
3318 icon = fallbackIcon;
3319 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003320 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003321 info.usingFallbackIcon = true;
3322 }
Joe Onorato56d82912010-03-07 14:32:10 -05003323 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003324 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003325
Joe Onorato0589f0f2010-02-08 13:44:00 -08003326 info.title = name;
3327 info.intent = intent;
3328 info.customIcon = customIcon;
3329 info.iconResource = iconResource;
3330
3331 return info;
3332 }
3333
Winson Chungaac01e12011-08-17 10:37:13 -07003334 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3335 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003336 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003337 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003338 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003339 }
Joe Onorato56d82912010-03-07 14:32:10 -05003340 // If this icon doesn't have a custom icon, check to see
3341 // what's stored in the DB, and if it doesn't match what
3342 // we're going to show, store what we are going to show back
3343 // into the DB. We do this so when we're loading, if the
3344 // package manager can't find an icon (for example because
3345 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003346 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003347 cache.put(info, c.getBlob(iconIndex));
3348 return true;
3349 }
3350 return false;
3351 }
3352 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3353 boolean needSave = false;
3354 try {
3355 if (data != null) {
3356 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3357 Bitmap loaded = info.getIcon(mIconCache);
3358 needSave = !saved.sameAs(loaded);
3359 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003360 needSave = true;
3361 }
Winson Chungaac01e12011-08-17 10:37:13 -07003362 } catch (Exception e) {
3363 needSave = true;
3364 }
3365 if (needSave) {
3366 Log.d(TAG, "going to save icon bitmap for info=" + info);
3367 // This is slower than is ideal, but this only happens once
3368 // or when the app is updated with a new icon.
3369 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003370 }
3371 }
3372
Joe Onorato9c1289c2009-08-17 11:03:03 -04003373 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003374 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003375 * or make a new one.
3376 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003377 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003378 // See if a placeholder was created for us already
3379 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003380 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003381 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003382 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003383 folders.put(id, folderInfo);
3384 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003385 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003386 }
3387
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003388 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003389 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003390 return new Comparator<AppInfo>() {
3391 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003392 if (a.user.equals(b.user)) {
3393 int result = collator.compare(a.title.toString().trim(),
3394 b.title.toString().trim());
3395 if (result == 0) {
3396 result = a.componentName.compareTo(b.componentName);
3397 }
3398 return result;
3399 } else {
3400 // TODO Need to figure out rules for sorting
3401 // profiles, this puts work second.
3402 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003403 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003404 }
Winson Chung11904872012-09-17 16:58:46 -07003405 };
3406 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003407 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3408 = new Comparator<AppInfo>() {
3409 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003410 if (a.firstInstallTime < b.firstInstallTime) return 1;
3411 if (a.firstInstallTime > b.firstInstallTime) return -1;
3412 return 0;
3413 }
3414 };
Winson Chung11904872012-09-17 16:58:46 -07003415 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3416 final Collator collator = Collator.getInstance();
3417 return new Comparator<AppWidgetProviderInfo>() {
3418 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003419 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003420 }
3421 };
3422 }
Winson Chung5308f242011-08-18 12:12:41 -07003423 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3424 if (info.activityInfo != null) {
3425 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3426 } else {
3427 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3428 }
3429 }
Kenny Guyed131872014-04-30 03:02:21 +01003430 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003431 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003432 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003433 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003434 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003435 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003436 }
Kenny Guyed131872014-04-30 03:02:21 +01003437 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003438 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003439 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003440 }
Kenny Guyed131872014-04-30 03:02:21 +01003441 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003442 CharSequence labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003443 ComponentName keyA = a.getComponentName();
3444 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003445 if (mLabelCache.containsKey(keyA)) {
3446 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003447 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003448 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003449
Winson Chung5308f242011-08-18 12:12:41 -07003450 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003451 }
Winson Chung5308f242011-08-18 12:12:41 -07003452 if (mLabelCache.containsKey(keyB)) {
3453 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003454 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003455 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003456
Winson Chung5308f242011-08-18 12:12:41 -07003457 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003458 }
Winson Chung11904872012-09-17 16:58:46 -07003459 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003460 }
3461 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003462 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003463 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003464 private PackageManager mPackageManager;
3465 private HashMap<Object, String> mLabelCache;
3466 WidgetAndShortcutNameComparator(PackageManager pm) {
3467 mPackageManager = pm;
3468 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003469 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003470 }
3471 public final int compare(Object a, Object b) {
3472 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003473 if (mLabelCache.containsKey(a)) {
3474 labelA = mLabelCache.get(a);
3475 } else {
3476 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003477 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003478 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003479 mLabelCache.put(a, labelA);
3480 }
3481 if (mLabelCache.containsKey(b)) {
3482 labelB = mLabelCache.get(b);
3483 } else {
3484 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003485 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003486 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003487 mLabelCache.put(b, labelB);
3488 }
Winson Chung11904872012-09-17 16:58:46 -07003489 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003490 }
3491 };
Joe Onoratobe386092009-11-17 17:32:16 -08003492
3493 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003494 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003495 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3496 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3497 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3498 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003499 if (mLoaderTask != null) {
3500 mLoaderTask.dumpState();
3501 } else {
3502 Log.d(TAG, "mLoaderTask=null");
3503 }
Joe Onoratobe386092009-11-17 17:32:16 -08003504 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003505}