blob: 141368c208932981338ca79d99540dbd17d82acb [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;
Jason Monkbbe1e242014-05-16 17:37:34 -040028import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080029import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070030import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080031import android.content.res.Resources;
32import android.database.Cursor;
33import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
35import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080036import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040037import android.os.Handler;
38import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080039import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070041import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040042import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040043import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080044import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070045import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070046import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010047
Kenny Guyed131872014-04-30 03:02:21 +010048import com.android.launcher3.compat.LauncherActivityInfoCompat;
49import com.android.launcher3.compat.LauncherAppsCompat;
50import com.android.launcher3.compat.UserHandleCompat;
51import com.android.launcher3.compat.UserManagerCompat;
Daniel Sandler325dc232013-06-05 22:57:57 -040052import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080053
Michael Jurkac2f801e2011-07-12 14:19:46 -070054import java.lang.ref.WeakReference;
55import java.net.URISyntaxException;
56import java.text.Collator;
57import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070058import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070059import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060import java.util.Collections;
61import java.util.Comparator;
62import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070063import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070064import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070066import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070068import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070/**
71 * Maintains in-memory state of the Launcher. It is expected that there should be only one
72 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070073 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074 */
Kenny Guyed131872014-04-30 03:02:21 +010075public class LauncherModel extends BroadcastReceiver
76 implements LauncherAppsCompat.OnAppsChangedListenerCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080077 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040078 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
79
Joe Onorato9c1289c2009-08-17 11:03:03 -040080 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070081
Daniel Sandler8707e0f2013-08-15 15:54:18 -070082 // true = use a "More Apps" folder for non-workspace apps on upgrade
83 // false = strew non-workspace apps across the workspace on upgrade
84 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050085 public static final int LOADER_FLAG_NONE = 0;
86 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
87 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
88
Joe Onorato36115782010-06-17 13:28:48 -040089 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050090 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080091
Winson Chungee055712013-07-30 14:46:24 -070092 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -080093 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -040094
Daniel Sandlercc8befa2013-06-11 14:45:48 -040095 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040096 private final Object mLock = new Object();
97 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040098 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070099 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200100 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Winson Chung81b52252012-08-27 15:34:29 -0700102 // Specific runnable types that are run on the main thread deferred handler, this allows us to
103 // clear all queued binding runnables when the Launcher activity is destroyed.
104 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
105 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
106
Jason Monkbbe1e242014-05-16 17:37:34 -0400107 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700108
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700109 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
110 static {
111 sWorkerThread.start();
112 }
113 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
114
Joe Onoratocc67f472010-06-08 10:54:30 -0700115 // We start off with everything not loaded. After that, we assume that
116 // our monitoring of the package manager provides all updates and we never
117 // need to do a requery. These are only ever touched from the loader thread.
118 private boolean mWorkspaceLoaded;
119 private boolean mAllAppsLoaded;
120
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700121 // When we are loading pages synchronously, we can't just post the binding of items on the side
122 // pages as this delays the rotation process. Instead, we wait for a callback from the first
123 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
124 // a normal load, we also clear this set of Runnables.
125 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
126
Joe Onorato9c1289c2009-08-17 11:03:03 -0400127 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700130 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // The lock that must be acquired before referencing any static bg data structures. Unlike
133 // other locks, this one can generally be held long-term because we never expect any of these
134 // static data structures to be referenced outside of the worker thread except on the first
135 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700136 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700137
Adam Cohen487f7dd2012-06-28 18:12:10 -0700138 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700140 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141
Adam Cohen487f7dd2012-06-28 18:12:10 -0700142 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
143 // created by LauncherModel that are directly on the home screen (however, no widgets or
144 // shortcuts within folders).
145 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700146
Adam Cohen487f7dd2012-06-28 18:12:10 -0700147 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
148 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149 new ArrayList<LauncherAppWidgetInfo>();
150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
152 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700153
Adam Cohen487f7dd2012-06-28 18:12:10 -0700154 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
155 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700156
157 // sBgWorkspaceScreens is the ordered set of workspace screens.
158 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
159
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 // </ only access in worker thread >
161
162 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163
Reena Lee99a73f32011-10-24 17:27:37 -0700164 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700165
Kenny Guyed131872014-04-30 03:02:21 +0100166 private final LauncherAppsCompat mLauncherApps;
167 private final UserManagerCompat mUserManager;
168
Joe Onorato9c1289c2009-08-17 11:03:03 -0400169 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700170 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400171 public int getCurrentWorkspaceScreen();
172 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700173 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
174 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700175 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700176 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500177 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700178 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400179 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200180 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700181 public void bindAppsAdded(ArrayList<Long> newScreens,
182 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700183 ArrayList<ItemInfo> addAnimated,
184 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200185 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500186 public void updatePackageState(String pkgName, int state);
Winson Chung83892cc2013-05-01 16:53:33 -0700187 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100188 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200189 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100190 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700191 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700192 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700193 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195
Winson Chung64359a52013-07-08 17:17:08 -0700196 public interface ItemInfoFilter {
197 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
198 }
199
Bjorn Bringert1307f632013-10-03 22:31:03 +0100200 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800201 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400202
Winson Chungee055712013-07-30 14:46:24 -0700203 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700204 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400205 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
206 // resource string.
207 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
208 ProviderInfo providerInfo =
209 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
210 ProviderInfo redirectProvider =
211 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700212
213 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400214 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700215
216 if (mOldContentProviderExists) {
217 Log.d(TAG, "Old launcher provider exists.");
218 } else {
219 Log.d(TAG, "Old launcher provider does not exist.");
220 }
221
Daniel Sandlere4f98912013-06-25 15:13:26 -0400222 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100223 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800224 mIconCache = iconCache;
225
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400226 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700227 Configuration config = res.getConfiguration();
228 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100229 mLauncherApps = LauncherAppsCompat.getInstance(context);
230 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800231 }
232
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700233 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
234 * posted on the main thread handler. */
235 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700236 runOnMainThread(r, 0);
237 }
238 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700239 if (sWorkerThread.getThreadId() == Process.myTid()) {
240 // If we are on the worker thread, post onto the main handler
241 mHandler.post(r);
242 } else {
243 r.run();
244 }
245 }
246
247 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
248 * posted on the worker thread handler. */
249 private static void runOnWorkerThread(Runnable r) {
250 if (sWorkerThread.getThreadId() == Process.myTid()) {
251 r.run();
252 } else {
253 // If we are not on the worker thread, then post to the worker handler
254 sWorker.post(r);
255 }
256 }
257
Winson Chunge43a1e72014-01-15 10:33:02 -0800258 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
259 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800260 }
261
Winson Chungc9168342013-06-26 14:54:55 -0700262 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
263 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700264 LauncherAppState app = LauncherAppState.getInstance();
265 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
266 final int xCount = (int) grid.numColumns;
267 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700268 boolean[][] occupied = new boolean[xCount][yCount];
269
270 int cellX, cellY, spanX, spanY;
271 for (int i = 0; i < items.size(); ++i) {
272 final ItemInfo item = items.get(i);
273 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
274 if (item.screenId == screen) {
275 cellX = item.cellX;
276 cellY = item.cellY;
277 spanX = item.spanX;
278 spanY = item.spanY;
279 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
280 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
281 occupied[x][y] = true;
282 }
283 }
284 }
285 }
286 }
287
288 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
289 }
290 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700291 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700292 int firstScreenIndex,
293 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700294 // Lock on the app so that we don't try and get the items while apps are being added
295 LauncherAppState app = LauncherAppState.getInstance();
296 LauncherModel model = app.getModel();
297 boolean found = false;
298 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700299 if (sWorkerThread.getThreadId() != Process.myTid()) {
300 // Flush the LauncherModel worker thread, so that if we just did another
301 // processInstallShortcut, we give it time for its shortcut to get added to the
302 // database (getItemsInLocalCoordinates reads the database)
303 model.flushWorkerThread();
304 }
Winson Chungc9168342013-06-26 14:54:55 -0700305 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700306
307 // Try adding to the workspace screens incrementally, starting at the default or center
308 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700309 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
310 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700311 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700312 int[] tmpCoordinates = new int[2];
313 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700314 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700315 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700316 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700317 }
318 }
319 }
Winson Chungc9168342013-06-26 14:54:55 -0700320 return null;
321 }
322
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500323 public void setPackageState(final String pkgName, final int state) {
324 // Process the updated package state
325 Runnable r = new Runnable() {
326 public void run() {
327 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
328 if (callbacks != null) {
329 callbacks.updatePackageState(pkgName, state);
330 }
331 }
332 };
333 mHandler.post(r);
334 }
335
Adam Cohen76a47a12014-02-05 11:47:43 -0800336 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
337 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
338
339 if (allAppsApps == null) {
340 throw new RuntimeException("allAppsApps must not be null");
341 }
342 if (allAppsApps.isEmpty()) {
343 return;
344 }
345
Chris Wrenb6d4c282014-01-27 14:17:08 -0500346 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
347 Iterator<AppInfo> iter = allAppsApps.iterator();
348 while (iter.hasNext()) {
349 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100350 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500351 restoredAppsFinal.add((AppInfo) a);
352 }
353 }
354
Adam Cohen76a47a12014-02-05 11:47:43 -0800355 // Process the newly added applications and add them to the database first
356 Runnable r = new Runnable() {
357 public void run() {
358 runOnMainThread(new Runnable() {
359 public void run() {
360 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
361 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500362 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500363 for (AppInfo info : restoredAppsFinal) {
364 final Intent intent = info.getIntent();
365 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100366 mIconCache.deletePreloadedIcon(intent.getComponent(),
367 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500368 }
369 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500370 callbacks.bindAppsUpdated(restoredAppsFinal);
371 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500372 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800373 }
374 }
375 });
376 }
377 };
378 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700379 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800380
381 public void addAndBindAddedWorkspaceApps(final Context context,
382 final ArrayList<ItemInfo> workspaceApps) {
383 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
384
385 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800386 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
387 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800388 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700389 return;
Winson Chung997a9232013-07-24 15:33:46 -0700390 }
Winson Chung64359a52013-07-08 17:17:08 -0700391 // Process the newly added applications and add them to the database first
392 Runnable r = new Runnable() {
393 public void run() {
394 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
395 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500396 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700397
Winson Chung76828c82013-08-19 15:43:29 -0700398 // Get the list of workspace screens. We need to append to this list and
399 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
400 // called.
401 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
402 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
403 for (Integer i : orderedScreens.keySet()) {
404 long screenId = orderedScreens.get(i);
405 workspaceScreens.add(screenId);
406 }
407
Winson Chung64359a52013-07-08 17:17:08 -0700408 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700409 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700410 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700411 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700412 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700413 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700414
415 // Short-circuit this logic if the icon exists somewhere on the workspace
416 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500417 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
418 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100419 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500420 restoredAppsFinal.add((AppInfo) a);
421 }
Winson Chung64359a52013-07-08 17:17:08 -0700422 continue;
423 }
424
Winson Chung87412982013-10-03 18:34:14 -0700425 // Add this icon to the db, creating a new page if necessary. If there
426 // is only the empty page then we just add items to the first page.
427 // Otherwise, we add them to the next pages.
428 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700429 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700430 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700431 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200432 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700433
434 // If we can't find a valid position, then just add a new screen.
435 // This takes time so we need to re-queue the add until the new
436 // page is added. Create as many screens as necessary to satisfy
437 // the startSearchPageIndex.
438 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700439 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700440 while (numPagesToAdd > 0) {
441 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700442 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700443 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700444 addedWorkspaceScreensFinal.add(screenId);
445 numPagesToAdd--;
446 }
Winson Chung76828c82013-08-19 15:43:29 -0700447
Winson Chung64359a52013-07-08 17:17:08 -0700448 // Find the coordinate again
449 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700450 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700451 }
452 if (coords == null) {
453 throw new RuntimeException("Coordinates should not be null");
454 }
455
Winson Chung997a9232013-07-24 15:33:46 -0700456 ShortcutInfo shortcutInfo;
457 if (a instanceof ShortcutInfo) {
458 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200459 } else if (a instanceof AppInfo) {
460 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700461 } else {
462 throw new RuntimeException("Unexpected info type");
463 }
Winson Chung94d67682013-09-25 16:29:40 -0700464
Winson Chung64359a52013-07-08 17:17:08 -0700465 // Add the shortcut to the db
466 addItemToDatabase(context, shortcutInfo,
467 LauncherSettings.Favorites.CONTAINER_DESKTOP,
468 coords.first, coords.second[0], coords.second[1], false);
469 // Save the ShortcutInfo for binding in the workspace
470 addedShortcutsFinal.add(shortcutInfo);
471 }
472 }
473
Winson Chung76828c82013-08-19 15:43:29 -0700474 // Update the workspace screens
475 updateWorkspaceScreenOrder(context, workspaceScreens);
476
Adam Cohen76a47a12014-02-05 11:47:43 -0800477 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700478 runOnMainThread(new Runnable() {
479 public void run() {
480 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
481 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700482 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
483 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700484 if (!addedShortcutsFinal.isEmpty()) {
485 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
486 long lastScreenId = info.screenId;
487 for (ItemInfo i : addedShortcutsFinal) {
488 if (i.screenId == lastScreenId) {
489 addAnimated.add(i);
490 } else {
491 addNotAnimated.add(i);
492 }
Winson Chung997a9232013-07-24 15:33:46 -0700493 }
494 }
Winson Chungd64d1762013-08-20 14:37:16 -0700495 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800496 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500497 if (!restoredAppsFinal.isEmpty()) {
498 callbacks.bindAppsUpdated(restoredAppsFinal);
499 }
Winson Chung997a9232013-07-24 15:33:46 -0700500 }
Winson Chung64359a52013-07-08 17:17:08 -0700501 }
Winson Chung997a9232013-07-24 15:33:46 -0700502 });
503 }
Winson Chung64359a52013-07-08 17:17:08 -0700504 }
505 };
506 runOnWorkerThread(r);
507 }
508
Winson Chung81b52252012-08-27 15:34:29 -0700509 public void unbindItemInfosAndClearQueuedBindRunnables() {
510 if (sWorkerThread.getThreadId() == Process.myTid()) {
511 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
512 "main thread");
513 }
514
515 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400516 synchronized (mDeferredBindRunnables) {
517 mDeferredBindRunnables.clear();
518 }
Winson Chung81b52252012-08-27 15:34:29 -0700519 // Remove any queued bind runnables
520 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
521 // Unbind all the workspace items
522 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700523 }
524
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700525 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700526 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700527 // Ensure that we don't use the same workspace items data structure on the main thread
528 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700529 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
530 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700531 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700532 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
533 tmpAppWidgets.addAll(sBgAppWidgets);
534 }
535 Runnable r = new Runnable() {
536 @Override
537 public void run() {
538 for (ItemInfo item : tmpWorkspaceItems) {
539 item.unbind();
540 }
541 for (ItemInfo item : tmpAppWidgets) {
542 item.unbind();
543 }
544 }
545 };
546 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700547 }
548
Joe Onorato9c1289c2009-08-17 11:03:03 -0400549 /**
550 * Adds an item to the DB if it was not created previously, or move it to a new
551 * <container, screen, cellX, cellY>
552 */
553 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700554 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400555 if (item.container == ItemInfo.NO_ID) {
556 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700557 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400558 } else {
559 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700560 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 }
562 }
563
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700564 static void checkItemInfoLocked(
565 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
566 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
567 if (modelItem != null && item != modelItem) {
568 // check all the data is consistent
569 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
570 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
571 ShortcutInfo shortcut = (ShortcutInfo) item;
572 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
573 modelShortcut.intent.filterEquals(shortcut.intent) &&
574 modelShortcut.id == shortcut.id &&
575 modelShortcut.itemType == shortcut.itemType &&
576 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700577 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700578 modelShortcut.cellX == shortcut.cellX &&
579 modelShortcut.cellY == shortcut.cellY &&
580 modelShortcut.spanX == shortcut.spanX &&
581 modelShortcut.spanY == shortcut.spanY &&
582 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
583 (modelShortcut.dropPos != null &&
584 shortcut.dropPos != null &&
585 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
586 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
587 // For all intents and purposes, this is the same object
588 return;
589 }
590 }
591
592 // the modelItem needs to match up perfectly with item if our model is
593 // to be consistent with the database-- for now, just require
594 // modelItem == item or the equality check above
595 String msg = "item: " + ((item != null) ? item.toString() : "null") +
596 "modelItem: " +
597 ((modelItem != null) ? modelItem.toString() : "null") +
598 "Error: ItemInfo passed to checkItemInfo doesn't match original";
599 RuntimeException e = new RuntimeException(msg);
600 if (stackTrace != null) {
601 e.setStackTrace(stackTrace);
602 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800603 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700604 }
605 }
606
Michael Jurka816474f2012-06-25 14:49:02 -0700607 static void checkItemInfo(final ItemInfo item) {
608 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
609 final long itemId = item.id;
610 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700611 public void run() {
612 synchronized (sBgLock) {
613 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700614 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700615 }
616 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700617 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700618 }
619
Michael Jurkac9d95c52011-08-29 14:03:34 -0700620 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
621 final ItemInfo item, final String callingFunction) {
622 final long itemId = item.id;
623 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
624 final ContentResolver cr = context.getContentResolver();
625
Adam Cohen487f7dd2012-06-28 18:12:10 -0700626 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700627 Runnable r = new Runnable() {
628 public void run() {
629 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700630 updateItemArrays(item, itemId, stackTrace);
631 }
632 };
633 runOnWorkerThread(r);
634 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700635
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700636 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
637 final ArrayList<ItemInfo> items, final String callingFunction) {
638 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700639
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700640 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
641 Runnable r = new Runnable() {
642 public void run() {
643 ArrayList<ContentProviderOperation> ops =
644 new ArrayList<ContentProviderOperation>();
645 int count = items.size();
646 for (int i = 0; i < count; i++) {
647 ItemInfo item = items.get(i);
648 final long itemId = item.id;
649 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
650 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700651
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700652 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
653 updateItemArrays(item, itemId, stackTrace);
654
655 }
656 try {
657 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
658 } catch (Exception e) {
659 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700660 }
661 }
662 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700663 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700664 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700665
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700666 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
667 // Lock on mBgLock *after* the db operation
668 synchronized (sBgLock) {
669 checkItemInfoLocked(itemId, item, stackTrace);
670
671 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
672 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
673 // Item is in a folder, make sure this folder exists
674 if (!sBgFolders.containsKey(item.container)) {
675 // An items container is being set to a that of an item which is not in
676 // the list of Folders.
677 String msg = "item: " + item + " container being set to: " +
678 item.container + ", not in the list of folders";
679 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700680 }
681 }
682
683 // Items are added/removed from the corresponding FolderInfo elsewhere, such
684 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
685 // that are on the desktop, as appropriate
686 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800687 if (modelItem != null &&
688 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
689 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700690 switch (modelItem.itemType) {
691 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
692 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
693 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
694 if (!sBgWorkspaceItems.contains(modelItem)) {
695 sBgWorkspaceItems.add(modelItem);
696 }
697 break;
698 default:
699 break;
700 }
701 } else {
702 sBgWorkspaceItems.remove(modelItem);
703 }
704 }
705 }
706
Michael Jurkac7700af2013-05-14 20:17:58 +0200707 public void flushWorkerThread() {
708 mFlushingWorkerThread = true;
709 Runnable waiter = new Runnable() {
710 public void run() {
711 synchronized (this) {
712 notifyAll();
713 mFlushingWorkerThread = false;
714 }
715 }
716 };
717
718 synchronized(waiter) {
719 runOnWorkerThread(waiter);
720 if (mLoaderTask != null) {
721 synchronized(mLoaderTask) {
722 mLoaderTask.notify();
723 }
724 }
725 boolean success = false;
726 while (!success) {
727 try {
728 waiter.wait();
729 success = true;
730 } catch (InterruptedException e) {
731 }
732 }
733 }
734 }
735
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400737 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700738 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700739 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700740 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400741 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400742 item.cellX = cellX;
743 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700744
Winson Chung3d503fb2011-07-13 17:25:49 -0700745 // We store hotseat items in canonical form which is this orientation invariant position
746 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700747 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700748 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700749 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700750 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700752 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400753
754 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700756 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
757 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400759
Michael Jurkac9d95c52011-08-29 14:03:34 -0700760 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700761 }
762
763 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700764 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
765 * cellX, cellY have already been updated on the ItemInfos.
766 */
767 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
768 final long container, final int screen) {
769
770 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
771 int count = items.size();
772
773 for (int i = 0; i < count; i++) {
774 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700775 item.container = container;
776
777 // We store hotseat items in canonical form which is this orientation invariant position
778 // in the hotseat
779 if (context instanceof Launcher && screen < 0 &&
780 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700781 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700782 item.cellY);
783 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700784 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700785 }
786
787 final ContentValues values = new ContentValues();
788 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
789 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
790 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700791 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700792
793 contentValues.add(values);
794 }
795 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
796 }
797
798 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700799 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800800 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700801 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700802 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700803 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800804 item.cellX = cellX;
805 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700806 item.spanX = spanX;
807 item.spanY = spanY;
808
809 // We store hotseat items in canonical form which is this orientation invariant position
810 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700811 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700812 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700814 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700816 }
Adam Cohend4844c32011-02-18 19:25:06 -0800817
Adam Cohend4844c32011-02-18 19:25:06 -0800818 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800819 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700820 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
821 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
822 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
823 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800825
Michael Jurka816474f2012-06-25 14:49:02 -0700826 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700828
829 /**
830 * Update an item to the database in a specified container.
831 */
832 static void updateItemInDatabase(Context context, final ItemInfo item) {
833 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100834 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700835 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
836 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800837 }
838
839 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400840 * Returns true if the shortcuts already exists in the database.
841 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800842 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400843 static boolean shortcutExists(Context context, String title, Intent intent) {
844 final ContentResolver cr = context.getContentResolver();
845 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
846 new String[] { "title", "intent" }, "title=? and intent=?",
847 new String[] { title, intent.toUri(0) }, null);
848 boolean result = false;
849 try {
850 result = c.moveToFirst();
851 } finally {
852 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800853 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700855 }
856
Joe Onorato9c1289c2009-08-17 11:03:03 -0400857 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500858 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100859 * we identify a shortcut by the component name of the intent
860 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500861 */
Kenny Guyed131872014-04-30 03:02:21 +0100862 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500863 final ContentResolver cr = context.getContentResolver();
864 final ComponentName component = intent.getComponent();
865 if (component == null) {
866 return false;
867 }
868 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400869 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100870 long serialNumber = UserManagerCompat.getInstance(context)
871 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400872 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
873 "intent glob \"*component=" + shortName + "*\")" +
874 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500875 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100876 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500877 boolean result = false;
878 try {
879 result = c.moveToFirst();
880 } finally {
881 c.close();
882 }
883 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
884 return result;
885 }
886
887 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700888 * Returns an ItemInfo array containing all the items in the LauncherModel.
889 * The ItemInfo.id is not set through this function.
890 */
891 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
892 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
893 final ContentResolver cr = context.getContentResolver();
894 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
895 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100896 LauncherSettings.Favorites.SCREEN,
897 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
898 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
899 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700900
901 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
902 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
903 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
904 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
905 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
906 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
907 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100908 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
909 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700910 try {
911 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700912 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700913 item.cellX = c.getInt(cellXIndex);
914 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700915 item.spanX = Math.max(1, c.getInt(spanXIndex));
916 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700917 item.container = c.getInt(containerIndex);
918 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700919 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100920 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100921 item.user = userManager.getUserForSerialNumber(serialNumber);
922 // Skip if user has been deleted.
923 if (item.user != null) {
924 items.add(item);
925 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700926 }
927 } catch (Exception e) {
928 items.clear();
929 } finally {
930 c.close();
931 }
932
933 return items;
934 }
935
936 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400937 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
938 */
939 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
940 final ContentResolver cr = context.getContentResolver();
941 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
942 "_id=? and (itemType=? or itemType=?)",
943 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700944 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700945
Joe Onorato9c1289c2009-08-17 11:03:03 -0400946 try {
947 if (c.moveToFirst()) {
948 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
949 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
950 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
951 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
952 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
953 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800954
Joe Onorato9c1289c2009-08-17 11:03:03 -0400955 FolderInfo folderInfo = null;
956 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700957 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
958 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400959 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700960 }
961
Joe Onorato9c1289c2009-08-17 11:03:03 -0400962 folderInfo.title = c.getString(titleIndex);
963 folderInfo.id = id;
964 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700965 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700966 folderInfo.cellX = c.getInt(cellXIndex);
967 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968
969 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700970 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 } finally {
972 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700973 }
974
975 return null;
976 }
977
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978 /**
979 * Add an item to the database in a specified container. Sets the container, screen, cellX and
980 * cellY fields of the item. Also assigns an ID to the item.
981 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700982 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 item.cellX = cellX;
986 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700987 // We store hotseat items in canonical form which is this orientation invariant position
988 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700989 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700990 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700991 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700992 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700994 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995
996 final ContentValues values = new ContentValues();
997 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +0100998 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999
Michael Jurka414300a2013-08-27 15:42:35 +02001000 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001003
Jason Monk8e19cf22014-03-20 15:06:57 -04001004 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001005 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 public void run() {
1007 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1008 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001010 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001011 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001012 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001013 sBgItemsIdMap.put(item.id, item);
1014 switch (item.itemType) {
1015 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1016 sBgFolders.put(item.id, (FolderInfo) item);
1017 // Fall through
1018 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1019 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1020 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1021 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1022 sBgWorkspaceItems.add(item);
1023 } else {
1024 if (!sBgFolders.containsKey(item.container)) {
1025 // Adding an item to a folder that doesn't exist.
1026 String msg = "adding item: " + item + " to a folder that " +
1027 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001028 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001029 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001030 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001031 break;
1032 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1033 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1034 break;
1035 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036 }
1037 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001038 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001040 }
1041
Joe Onorato9c1289c2009-08-17 11:03:03 -04001042 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001043 * Creates a new unique child id, for a given cell span across all layouts.
1044 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001045 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001046 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001047 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001048 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001049 }
1050
Winson Chungaafa03c2010-06-11 17:34:16 -07001051 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001052 * Removes the specified item from the database
1053 * @param context
1054 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001055 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001056 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001057 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001058 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001059
Michael Jurka83df1882011-08-31 20:59:26 -07001060 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001061 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001062 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001063
1064 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001065 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001066 switch (item.itemType) {
1067 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1068 sBgFolders.remove(item.id);
1069 for (ItemInfo info: sBgItemsIdMap.values()) {
1070 if (info.container == item.id) {
1071 // We are deleting a folder which still contains items that
1072 // think they are contained by that folder.
1073 String msg = "deleting a folder (" + item + ") which still " +
1074 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001075 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001076 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001077 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001078 sBgWorkspaceItems.remove(item);
1079 break;
1080 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1081 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1082 sBgWorkspaceItems.remove(item);
1083 break;
1084 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1085 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1086 break;
1087 }
1088 sBgItemsIdMap.remove(item.id);
1089 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 }
1091 }
Michael Jurka83df1882011-08-31 20:59:26 -07001092 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001093 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001094 }
1095
1096 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001097 * Update the order of the workspace screens in the database. The array list contains
1098 * a list of screen ids in the order that they should appear.
1099 */
Winson Chungc9168342013-06-26 14:54:55 -07001100 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001101 // Log to disk
1102 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1103 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1104
Winson Chung64359a52013-07-08 17:17:08 -07001105 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001106 final ContentResolver cr = context.getContentResolver();
1107 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1108
1109 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001110 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001111 while (iter.hasNext()) {
1112 long id = iter.next();
1113 if (id < 0) {
1114 iter.remove();
1115 }
1116 }
1117
1118 Runnable r = new Runnable() {
1119 @Override
1120 public void run() {
Yura085c8532014-02-11 15:15:29 +00001121 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001122 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001123 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001124 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001125 for (int i = 0; i < count; i++) {
1126 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001127 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001128 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1129 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001130 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001131 }
Yura085c8532014-02-11 15:15:29 +00001132
1133 try {
1134 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1135 } catch (Exception ex) {
1136 throw new RuntimeException(ex);
1137 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001138
Winson Chungba9c37f2013-08-30 14:11:37 -07001139 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001140 sBgWorkspaceScreens.clear();
1141 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001142 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001143 }
1144 };
1145 runOnWorkerThread(r);
1146 }
1147
1148 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001149 * Remove the contents of the specified folder from the database
1150 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001151 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001152 final ContentResolver cr = context.getContentResolver();
1153
Michael Jurkac9d95c52011-08-29 14:03:34 -07001154 Runnable r = new Runnable() {
1155 public void run() {
1156 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001157 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001158 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001159 sBgItemsIdMap.remove(info.id);
1160 sBgFolders.remove(info.id);
1161 sBgDbIconCache.remove(info);
1162 sBgWorkspaceItems.remove(info);
1163 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001164
Michael Jurkac9d95c52011-08-29 14:03:34 -07001165 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1166 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001167 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001168 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001169 for (ItemInfo childInfo : info.contents) {
1170 sBgItemsIdMap.remove(childInfo.id);
1171 sBgDbIconCache.remove(childInfo);
1172 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001173 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001174 }
1175 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001176 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001177 }
1178
1179 /**
1180 * Set this as the current Launcher activity object for the loader.
1181 */
1182 public void initialize(Callbacks callbacks) {
1183 synchronized (mLock) {
1184 mCallbacks = new WeakReference<Callbacks>(callbacks);
1185 }
1186 }
1187
Kenny Guyed131872014-04-30 03:02:21 +01001188 @Override
1189 public void onPackageChanged(UserHandleCompat user, String packageName) {
1190 int op = PackageUpdatedTask.OP_UPDATE;
1191 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1192 user));
1193 }
1194
1195 @Override
1196 public void onPackageRemoved(UserHandleCompat user, String packageName) {
1197 int op = PackageUpdatedTask.OP_REMOVE;
1198 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1199 user));
1200 }
1201
1202 @Override
1203 public void onPackageAdded(UserHandleCompat user, String packageName) {
1204 int op = PackageUpdatedTask.OP_ADD;
1205 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1206 user));
1207 }
1208
1209 @Override
1210 public void onPackagesAvailable(UserHandleCompat user, String[] packageNames,
1211 boolean replacing) {
1212 if (!replacing) {
1213 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1214 user));
1215 if (mAppsCanBeOnRemoveableStorage) {
1216 // Only rebind if we support removable storage. It catches the
1217 // case where
1218 // apps on the external sd card need to be reloaded
1219 startLoaderFromBackground();
1220 }
1221 } else {
1222 // If we are replacing then just update the packages in the list
1223 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1224 packageNames, user));
1225 }
1226 }
1227
1228 @Override
1229 public void onPackagesUnavailable(UserHandleCompat user, String[] packageNames,
1230 boolean replacing) {
1231 if (!replacing) {
1232 enqueuePackageUpdated(new PackageUpdatedTask(
1233 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1234 user));
1235 }
1236
1237 }
1238
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001239 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001240 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1241 * ACTION_PACKAGE_CHANGED.
1242 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001243 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001244 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001245 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001246
Joe Onorato36115782010-06-17 13:28:48 -04001247 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001248 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001249 // If we have changed locale we need to clear out the labels in all apps/workspace.
1250 forceReload();
1251 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1252 // Check if configuration change was an mcc/mnc change which would affect app resources
1253 // and we would need to clear out the labels in all apps/workspace. Same handling as
1254 // above for ACTION_LOCALE_CHANGED
1255 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001256 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001257 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001258 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001259 forceReload();
1260 }
1261 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001262 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001263 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1264 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001265 if (mCallbacks != null) {
1266 Callbacks callbacks = mCallbacks.get();
1267 if (callbacks != null) {
1268 callbacks.bindSearchablesChanged();
1269 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001270 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001271 }
1272 }
1273
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001274 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001275 resetLoadedState(true, true);
1276
Reena Lee93f824a2011-09-23 17:20:28 -07001277 // Do this here because if the launcher activity is running it will be restarted.
1278 // If it's not running startLoaderFromBackground will merely tell it that it needs
1279 // to reload.
1280 startLoaderFromBackground();
1281 }
1282
Winson Chungf0c6ae02012-03-21 16:10:31 -07001283 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1284 synchronized (mLock) {
1285 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1286 // mWorkspaceLoaded to true later
1287 stopLoaderLocked();
1288 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1289 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1290 }
1291 }
1292
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001293 /**
1294 * When the launcher is in the background, it's possible for it to miss paired
1295 * configuration changes. So whenever we trigger the loader from the background
1296 * tell the launcher that it needs to re-run the loader when it comes back instead
1297 * of doing it now.
1298 */
1299 public void startLoaderFromBackground() {
1300 boolean runLoader = false;
1301 if (mCallbacks != null) {
1302 Callbacks callbacks = mCallbacks.get();
1303 if (callbacks != null) {
1304 // Only actually run the loader if they're not paused.
1305 if (!callbacks.setLoadOnResume()) {
1306 runLoader = true;
1307 }
1308 }
1309 }
1310 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001311 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001312 }
Joe Onorato36115782010-06-17 13:28:48 -04001313 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001314
Reena Lee93f824a2011-09-23 17:20:28 -07001315 // If there is already a loader task running, tell it to stop.
1316 // returns true if isLaunching() was true on the old task
1317 private boolean stopLoaderLocked() {
1318 boolean isLaunching = false;
1319 LoaderTask oldTask = mLoaderTask;
1320 if (oldTask != null) {
1321 if (oldTask.isLaunching()) {
1322 isLaunching = true;
1323 }
1324 oldTask.stopLocked();
1325 }
1326 return isLaunching;
1327 }
1328
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001329 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001330 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1331 }
1332
1333 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001334 synchronized (mLock) {
1335 if (DEBUG_LOADERS) {
1336 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1337 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001338
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001339 // Clear any deferred bind-runnables from the synchronized load process
1340 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001341 synchronized (mDeferredBindRunnables) {
1342 mDeferredBindRunnables.clear();
1343 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001344
Joe Onorato36115782010-06-17 13:28:48 -04001345 // Don't bother to start the thread if we know it's not going to do anything
1346 if (mCallbacks != null && mCallbacks.get() != null) {
1347 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001348 // also, don't downgrade isLaunching if we're already running
1349 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001350 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001351 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1352 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001353 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1354 } else {
1355 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1356 sWorker.post(mLoaderTask);
1357 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001358 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001359 }
1360 }
1361
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001362 void bindRemainingSynchronousPages() {
1363 // Post the remaining side pages to be loaded
1364 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001365 Runnable[] deferredBindRunnables = null;
1366 synchronized (mDeferredBindRunnables) {
1367 deferredBindRunnables = mDeferredBindRunnables.toArray(
1368 new Runnable[mDeferredBindRunnables.size()]);
1369 mDeferredBindRunnables.clear();
1370 }
1371 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001372 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001374 }
1375 }
1376
Joe Onorato36115782010-06-17 13:28:48 -04001377 public void stopLoader() {
1378 synchronized (mLock) {
1379 if (mLoaderTask != null) {
1380 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001381 }
1382 }
Joe Onorato36115782010-06-17 13:28:48 -04001383 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001384
Winson Chung76828c82013-08-19 15:43:29 -07001385 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1386 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1387 final ContentResolver contentResolver = context.getContentResolver();
1388 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1389 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1390 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1391
1392 try {
1393 final int idIndex = sc.getColumnIndexOrThrow(
1394 LauncherSettings.WorkspaceScreens._ID);
1395 final int rankIndex = sc.getColumnIndexOrThrow(
1396 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1397 while (sc.moveToNext()) {
1398 try {
1399 long screenId = sc.getLong(idIndex);
1400 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001401 orderedScreens.put(rank, screenId);
1402 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001403 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001404 }
1405 }
1406 } finally {
1407 sc.close();
1408 }
Winson Chunga90303b2013-11-15 13:05:06 -08001409
1410 // Log to disk
1411 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1412 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1413 for (Integer i : orderedScreens.keySet()) {
1414 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1415 }
1416 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1417 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001418 return orderedScreens;
1419 }
1420
Michael Jurkac57b7a82011-08-09 22:02:20 -07001421 public boolean isAllAppsLoaded() {
1422 return mAllAppsLoaded;
1423 }
1424
Winson Chung36a62fe2012-05-06 18:04:42 -07001425 boolean isLoadingWorkspace() {
1426 synchronized (mLock) {
1427 if (mLoaderTask != null) {
1428 return mLoaderTask.isLoadingWorkspace();
1429 }
1430 }
1431 return false;
1432 }
1433
Joe Onorato36115782010-06-17 13:28:48 -04001434 /**
1435 * Runnable for the thread that loads the contents of the launcher:
1436 * - workspace icons
1437 * - widgets
1438 * - all apps icons
1439 */
1440 private class LoaderTask implements Runnable {
1441 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001442 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001443 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001444 private boolean mStopped;
1445 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001446 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001447
Winson Chungc3eecff2011-07-11 17:44:15 -07001448 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001449
Dan Sandlerd5024042014-01-09 15:01:33 -05001450 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001451 mContext = context;
1452 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001453 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001454 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001455 }
1456
Joe Onorato36115782010-06-17 13:28:48 -04001457 boolean isLaunching() {
1458 return mIsLaunching;
1459 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001460
Winson Chung36a62fe2012-05-06 18:04:42 -07001461 boolean isLoadingWorkspace() {
1462 return mIsLoadingAndBindingWorkspace;
1463 }
1464
Winson Chungc763c4e2013-07-19 13:49:06 -07001465 /** Returns whether this is an upgrade path */
1466 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001467 mIsLoadingAndBindingWorkspace = true;
1468
Joe Onorato36115782010-06-17 13:28:48 -04001469 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001470 if (DEBUG_LOADERS) {
1471 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001472 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001473
Winson Chungc763c4e2013-07-19 13:49:06 -07001474 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001475 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001476 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001477 synchronized (LoaderTask.this) {
1478 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001479 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001480 }
1481 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001482 }
1483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001486 bindWorkspace(-1, isUpgradePath);
1487 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001488 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001489
Joe Onorato36115782010-06-17 13:28:48 -04001490 private void waitForIdle() {
1491 // Wait until the either we're stopped or the other threads are done.
1492 // This way we don't start loading all apps until the workspace has settled
1493 // down.
1494 synchronized (LoaderTask.this) {
1495 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001496
Joe Onorato36115782010-06-17 13:28:48 -04001497 mHandler.postIdle(new Runnable() {
1498 public void run() {
1499 synchronized (LoaderTask.this) {
1500 mLoadAndBindStepFinished = true;
1501 if (DEBUG_LOADERS) {
1502 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001503 }
Joe Onorato36115782010-06-17 13:28:48 -04001504 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001505 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001506 }
Joe Onorato36115782010-06-17 13:28:48 -04001507 });
1508
Michael Jurkac7700af2013-05-14 20:17:58 +02001509 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001510 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001511 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1512 // wait no longer than 1sec at a time
1513 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001514 } catch (InterruptedException ex) {
1515 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001516 }
1517 }
Joe Onorato36115782010-06-17 13:28:48 -04001518 if (DEBUG_LOADERS) {
1519 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001520 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001521 + "ms for previous step to finish binding");
1522 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001523 }
Joe Onorato36115782010-06-17 13:28:48 -04001524 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001525
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001526 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001527 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001528 // Ensure that we have a valid page index to load synchronously
1529 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1530 "valid page index");
1531 }
1532 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1533 // Ensure that we don't try and bind a specified page when the pages have not been
1534 // loaded already (we should load everything asynchronously in that case)
1535 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1536 }
1537 synchronized (mLock) {
1538 if (mIsLoaderTaskRunning) {
1539 // Ensure that we are never running the background loading at this point since
1540 // we also touch the background collections
1541 throw new RuntimeException("Error! Background loading is already running");
1542 }
1543 }
1544
1545 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1546 // data structures, we can't allow any other thread to touch that data, but because
1547 // this call is synchronous, we can get away with not locking).
1548
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001549 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001550 // operations from the previous activity. We need to ensure that all queued operations
1551 // are executed before any synchronous binding work is done.
1552 mHandler.flush();
1553
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 // Divide the set of loaded items into those that we are binding synchronously, and
1555 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001556 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001557 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1558 // arise from that.
1559 onlyBindAllApps();
1560 }
1561
Joe Onorato36115782010-06-17 13:28:48 -04001562 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001563 boolean isUpgrade = false;
1564
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001565 synchronized (mLock) {
1566 mIsLoaderTaskRunning = true;
1567 }
Joe Onorato36115782010-06-17 13:28:48 -04001568 // Optimize for end-user experience: if the Launcher is up and // running with the
1569 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1570 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001571 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001572 // Elevate priority when Home launches for the first time to avoid
1573 // starving at boot time. Staring at a blank home is not cool.
1574 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001575 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1576 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001577 android.os.Process.setThreadPriority(mIsLaunching
1578 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1579 }
Winson Chung64359a52013-07-08 17:17:08 -07001580 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001581 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001582
Joe Onorato36115782010-06-17 13:28:48 -04001583 if (mStopped) {
1584 break keep_running;
1585 }
1586
1587 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1588 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001589 synchronized (mLock) {
1590 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001591 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001592 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1593 }
1594 }
Joe Onorato36115782010-06-17 13:28:48 -04001595 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001596
1597 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001598 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1599 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001600
1601 // Restore the default thread priority after we are done loading items
1602 synchronized (mLock) {
1603 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1604 }
Joe Onorato36115782010-06-17 13:28:48 -04001605 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001606
Winson Chungaac01e12011-08-17 10:37:13 -07001607 // Update the saved icons if necessary
1608 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001609 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001610 for (Object key : sBgDbIconCache.keySet()) {
1611 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1612 }
1613 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001614 }
Winson Chungaac01e12011-08-17 10:37:13 -07001615
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001616 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001617 // Ensure that all the applications that are in the system are
1618 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001619 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001620 verifyApplications();
1621 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001622 }
1623
Joe Onorato36115782010-06-17 13:28:48 -04001624 // Clear out this reference, otherwise we end up holding it until all of the
1625 // callback runnables are done.
1626 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001627
Joe Onorato36115782010-06-17 13:28:48 -04001628 synchronized (mLock) {
1629 // If we are still the last one to be scheduled, remove ourselves.
1630 if (mLoaderTask == this) {
1631 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001632 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001633 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001634 }
Joe Onorato36115782010-06-17 13:28:48 -04001635 }
1636
1637 public void stopLocked() {
1638 synchronized (LoaderTask.this) {
1639 mStopped = true;
1640 this.notify();
1641 }
1642 }
1643
1644 /**
1645 * Gets the callbacks object. If we've been stopped, or if the launcher object
1646 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1647 * object that was around when the deferred message was scheduled, and if there's
1648 * a new Callbacks object around then also return null. This will save us from
1649 * calling onto it with data that will be ignored.
1650 */
1651 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1652 synchronized (mLock) {
1653 if (mStopped) {
1654 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001655 }
Joe Onorato36115782010-06-17 13:28:48 -04001656
1657 if (mCallbacks == null) {
1658 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001659 }
Joe Onorato36115782010-06-17 13:28:48 -04001660
1661 final Callbacks callbacks = mCallbacks.get();
1662 if (callbacks != oldCallbacks) {
1663 return null;
1664 }
1665 if (callbacks == null) {
1666 Log.w(TAG, "no mCallbacks");
1667 return null;
1668 }
1669
1670 return callbacks;
1671 }
1672 }
1673
Winson Chungc763c4e2013-07-19 13:49:06 -07001674 private void verifyApplications() {
1675 final Context context = mApp.getContext();
1676
1677 // Cross reference all the applications in our apps list with items in the workspace
1678 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001679 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001680 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001681 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001682 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001683 if (tmpInfos.isEmpty()) {
1684 // We are missing an application icon, so add this to the workspace
1685 added.add(app);
1686 // This is a rare event, so lets log it
1687 Log.e(TAG, "Missing Application on load: " + app);
1688 }
1689 }
1690 }
1691 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001692 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001693 }
1694 }
1695
Joe Onorato36115782010-06-17 13:28:48 -04001696 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001697 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001698 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001699 LauncherAppState app = LauncherAppState.getInstance();
1700 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001701 final int countX = (int) grid.numColumns;
1702 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001703
Adam Cohendcd297f2013-06-18 13:13:40 -07001704 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001705 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001706 // Return early if we detect that an item is under the hotseat button
1707 if (mCallbacks == null ||
1708 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001709 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001710 Log.e(TAG, "Error loading shortcut into hotseat " + item
1711 + " into position (" + item.screenId + ":" + item.cellX + ","
1712 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001713 return false;
1714 }
1715
Dan Sandler295ae182013-12-10 16:05:47 -05001716 final ItemInfo[][] hotseatItems =
1717 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1718
Adam Cohenae4409d2013-11-26 10:34:59 -08001719 if (item.screenId >= grid.numHotseatIcons) {
1720 Log.e(TAG, "Error loading shortcut " + item
1721 + " into hotseat position " + item.screenId
1722 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1723 + ")");
1724 return false;
1725 }
1726
Dan Sandler295ae182013-12-10 16:05:47 -05001727 if (hotseatItems != null) {
1728 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 Log.e(TAG, "Error loading shortcut into hotseat " + item
1730 + " into position (" + item.screenId + ":" + item.cellX + ","
1731 + item.cellY + ") occupied by "
1732 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1733 [(int) item.screenId][0]);
1734 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001735 } else {
1736 hotseatItems[(int) item.screenId][0] = item;
1737 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001738 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001739 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001740 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001741 items[(int) item.screenId][0] = item;
1742 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001743 return true;
1744 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001745 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1746 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001747 return true;
1748 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001749
Adam Cohendcd297f2013-06-18 13:13:40 -07001750 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001751 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001752 occupied.put(item.screenId, items);
1753 }
1754
Dan Sandler295ae182013-12-10 16:05:47 -05001755 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001756 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1757 item.cellX < 0 || item.cellY < 0 ||
1758 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1759 Log.e(TAG, "Error loading shortcut " + item
1760 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1761 + item.cellX + "," + item.cellY
1762 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1763 return false;
1764 }
1765
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001766 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001767 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1768 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001769 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001770 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001771 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001772 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001773 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001774 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001775 return false;
1776 }
1777 }
1778 }
1779 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1780 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001781 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001782 }
1783 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001784
Joe Onorato36115782010-06-17 13:28:48 -04001785 return true;
1786 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001787
Winson Chungba9c37f2013-08-30 14:11:37 -07001788 /** Clears all the sBg data structures */
1789 private void clearSBgDataStructures() {
1790 synchronized (sBgLock) {
1791 sBgWorkspaceItems.clear();
1792 sBgAppWidgets.clear();
1793 sBgFolders.clear();
1794 sBgItemsIdMap.clear();
1795 sBgDbIconCache.clear();
1796 sBgWorkspaceScreens.clear();
1797 }
1798 }
1799
Dan Sandlerd5024042014-01-09 15:01:33 -05001800 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001801 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001802 // Log to disk
1803 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1804
Joe Onorato36115782010-06-17 13:28:48 -04001805 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001806
Joe Onorato36115782010-06-17 13:28:48 -04001807 final Context context = mContext;
1808 final ContentResolver contentResolver = context.getContentResolver();
1809 final PackageManager manager = context.getPackageManager();
1810 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1811 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001812
Winson Chung892c74d2013-08-22 16:15:50 -07001813 LauncherAppState app = LauncherAppState.getInstance();
1814 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1815 int countX = (int) grid.numColumns;
1816 int countY = (int) grid.numRows;
1817
Dan Sandlerd5024042014-01-09 15:01:33 -05001818 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1819 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1820 LauncherAppState.getLauncherProvider().deleteDatabase();
1821 }
1822
1823 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1824 // append the user's Launcher2 shortcuts
1825 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1826 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1827 } else {
1828 // Make sure the default workspace is loaded
1829 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1830 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1831 }
Adam Cohene25af792013-06-06 23:08:25 -07001832
Adam Cohen71483f42014-05-15 14:04:01 -07001833 // This code path is for our old migration code and should no longer be exercised
1834 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001835
Winson Chung9f9f00b2013-11-15 13:27:00 -08001836 // Log to disk
1837 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001838
Winson Chung2abf94d2012-07-18 18:16:38 -07001839 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001840 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001841
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001842 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001843 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001844 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001845 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001846 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001847
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001848 // +1 for the hotseat (it can be larger than the workspace)
1849 // Load workspace in reverse order to ensure that latest items are loaded first (and
1850 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001851 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001852
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001853 try {
1854 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1855 final int intentIndex = c.getColumnIndexOrThrow
1856 (LauncherSettings.Favorites.INTENT);
1857 final int titleIndex = c.getColumnIndexOrThrow
1858 (LauncherSettings.Favorites.TITLE);
1859 final int iconTypeIndex = c.getColumnIndexOrThrow(
1860 LauncherSettings.Favorites.ICON_TYPE);
1861 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1862 final int iconPackageIndex = c.getColumnIndexOrThrow(
1863 LauncherSettings.Favorites.ICON_PACKAGE);
1864 final int iconResourceIndex = c.getColumnIndexOrThrow(
1865 LauncherSettings.Favorites.ICON_RESOURCE);
1866 final int containerIndex = c.getColumnIndexOrThrow(
1867 LauncherSettings.Favorites.CONTAINER);
1868 final int itemTypeIndex = c.getColumnIndexOrThrow(
1869 LauncherSettings.Favorites.ITEM_TYPE);
1870 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1871 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001872 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1873 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001874 final int screenIndex = c.getColumnIndexOrThrow(
1875 LauncherSettings.Favorites.SCREEN);
1876 final int cellXIndex = c.getColumnIndexOrThrow
1877 (LauncherSettings.Favorites.CELLX);
1878 final int cellYIndex = c.getColumnIndexOrThrow
1879 (LauncherSettings.Favorites.CELLY);
1880 final int spanXIndex = c.getColumnIndexOrThrow
1881 (LauncherSettings.Favorites.SPANX);
1882 final int spanYIndex = c.getColumnIndexOrThrow(
1883 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001884 final int restoredIndex = c.getColumnIndexOrThrow(
1885 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001886 final int profileIdIndex = c.getColumnIndexOrThrow(
1887 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001888 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1889 //final int displayModeIndex = c.getColumnIndexOrThrow(
1890 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001891
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001892 ShortcutInfo info;
1893 String intentDescription;
1894 LauncherAppWidgetInfo appWidgetInfo;
1895 int container;
1896 long id;
1897 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001898 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001899
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001900 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001901 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001902 try {
1903 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001904 boolean restored = 0 != c.getInt(restoredIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001905
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 switch (itemType) {
1907 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1908 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001909 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001910 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001911 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001912 user = mUserManager.getUserForSerialNumber(serialNumber);
1913 if (user == null) {
1914 // User has been deleted remove the item.
1915 itemsToRemove.add(id);
1916 continue;
1917 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001918 try {
1919 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001920 ComponentName cn = intent.getComponent();
Kenny Guyed131872014-04-30 03:02:21 +01001921 if (cn != null && !isValidPackageActivity(context, cn, user)) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001922 if (restored) {
1923 // might be installed later
1924 Launcher.addDumpLog(TAG,
1925 "package not yet restored: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001926 } else {
Chris Wrenf4d08112014-01-16 18:13:56 -05001927 if (!mAppsCanBeOnRemoveableStorage) {
1928 // Log the invalid package, and remove it
1929 Launcher.addDumpLog(TAG,
1930 "Invalid package removed: " + cn, true);
1931 itemsToRemove.add(id);
1932 } else {
1933 // If apps can be on external storage, then we just
1934 // leave them for the user to remove (maybe add
1935 // visual treatment to it)
1936 Launcher.addDumpLog(TAG,
1937 "Invalid package found: " + cn, true);
1938 }
1939 continue;
Winson Chungee055712013-07-30 14:46:24 -07001940 }
Chris Wrenf4d08112014-01-16 18:13:56 -05001941 } else if (restored) {
1942 // no special handling necessary for this restored item
1943 restoredRows.add(id);
1944 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07001945 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001946 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001947 Launcher.addDumpLog(TAG,
1948 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001949 continue;
1950 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001951
Chris Wrenf4d08112014-01-16 18:13:56 -05001952 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01001953 if (user.equals(UserHandleCompat.myUserHandle())) {
1954 Launcher.addDumpLog(TAG,
1955 "constructing info for partially restored package",
1956 true);
1957 info = getRestoredItemInfo(c, titleIndex, intent);
1958 intent = getRestoredItemIntent(c, context, intent);
1959 } else {
1960 // Don't restore items for other profiles.
1961 itemsToRemove.add(id);
1962 continue;
1963 }
Chris Wrenf4d08112014-01-16 18:13:56 -05001964 } else if (itemType ==
1965 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Kenny Guyed131872014-04-30 03:02:21 +01001966 info = getShortcutInfo(manager, intent, user, context, c, iconIndex,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001967 titleIndex, mLabelCache);
1968 } else {
1969 info = getShortcutInfo(c, context, iconTypeIndex,
1970 iconPackageIndex, iconResourceIndex, iconIndex,
1971 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001972
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001973 // App shortcuts that used to be automatically added to Launcher
1974 // didn't always have the correct intent flags set, so do that
1975 // here
1976 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001977 intent.getCategories() != null &&
1978 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001979 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001980 intent.addFlags(
1981 Intent.FLAG_ACTIVITY_NEW_TASK |
1982 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1983 }
Michael Jurka96879562012-03-22 05:54:33 -07001984 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001985
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001986 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001987 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001988 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001989 container = c.getInt(containerIndex);
1990 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001991 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001992 info.cellX = c.getInt(cellXIndex);
1993 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001994 info.spanX = 1;
1995 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01001996 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Adam Cohenae4409d2013-11-26 10:34:59 -08001997
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001998 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001999 deleteOnInvalidPlacement.set(false);
2000 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2001 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002002 itemsToRemove.add(id);
2003 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002004 break;
2005 }
2006
2007 switch (container) {
2008 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2009 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2010 sBgWorkspaceItems.add(info);
2011 break;
2012 default:
2013 // Item is in a user folder
2014 FolderInfo folderInfo =
2015 findOrMakeFolder(sBgFolders, container);
2016 folderInfo.add(info);
2017 break;
2018 }
2019 sBgItemsIdMap.put(info.id, info);
2020
2021 // now that we've loaded everthing re-save it with the
2022 // icon in case it disappears somehow.
2023 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002024 } else {
2025 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002026 }
2027 break;
2028
2029 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2030 id = c.getLong(idIndex);
2031 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2032
2033 folderInfo.title = c.getString(titleIndex);
2034 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002035 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002036 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002037 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002038 folderInfo.cellX = c.getInt(cellXIndex);
2039 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002040 folderInfo.spanX = 1;
2041 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002042
Daniel Sandler8802e962010-05-26 16:28:16 -04002043 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002044 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002045 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002046 deleteOnInvalidPlacement)) {
2047 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002048 itemsToRemove.add(id);
2049 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002050 break;
2051 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002052
Joe Onorato9c1289c2009-08-17 11:03:03 -04002053 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2055 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2056 sBgWorkspaceItems.add(folderInfo);
2057 break;
Joe Onorato36115782010-06-17 13:28:48 -04002058 }
Joe Onorato17a89222011-02-08 17:26:11 -08002059
Chris Wrenf4d08112014-01-16 18:13:56 -05002060 if (restored) {
2061 // no special handling required for restored folders
2062 restoredRows.add(id);
2063 }
2064
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2066 sBgFolders.put(folderInfo.id, folderInfo);
2067 break;
2068
2069 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2070 // Read all Launcher-specific widget details
2071 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002072 String savedProvider = c.getString(appWidgetProviderIndex);
2073
Joe Onorato36115782010-06-17 13:28:48 -04002074 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002075
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 final AppWidgetProviderInfo provider =
2077 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04002078
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 if (!isSafeMode && (provider == null || provider.provider == null ||
2080 provider.provider.getPackageName() == null)) {
2081 String log = "Deleting widget that isn't installed anymore: id="
2082 + id + " appWidgetId=" + appWidgetId;
2083 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002084 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 itemsToRemove.add(id);
2086 } else {
2087 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2088 provider.provider);
2089 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002090 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 appWidgetInfo.cellX = c.getInt(cellXIndex);
2092 appWidgetInfo.cellY = c.getInt(cellYIndex);
2093 appWidgetInfo.spanX = c.getInt(spanXIndex);
2094 appWidgetInfo.spanY = c.getInt(spanYIndex);
2095 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2096 appWidgetInfo.minSpanX = minSpan[0];
2097 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04002098
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 container = c.getInt(containerIndex);
2100 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2101 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2102 Log.e(TAG, "Widget found where container != " +
2103 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2104 continue;
2105 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002106
Adam Cohene25af792013-06-06 23:08:25 -07002107 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002108 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002109 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002110 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002111 deleteOnInvalidPlacement)) {
2112 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002113 itemsToRemove.add(id);
2114 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002115 break;
2116 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002117 String providerName = provider.provider.flattenToString();
2118 if (!providerName.equals(savedProvider)) {
2119 ContentValues values = new ContentValues();
2120 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2121 providerName);
2122 String where = BaseColumns._ID + "= ?";
2123 String[] args = {Integer.toString(c.getInt(idIndex))};
2124 contentResolver.update(contentUri, values, where, args);
2125 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2127 sBgAppWidgets.add(appWidgetInfo);
2128 }
Joe Onorato36115782010-06-17 13:28:48 -04002129 break;
2130 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002132 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002133 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002134 }
2135 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002136 if (c != null) {
2137 c.close();
2138 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002139 }
2140
Winson Chungba9c37f2013-08-30 14:11:37 -07002141 // Break early if we've stopped loading
2142 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002143 clearSBgDataStructures();
2144 return false;
2145 }
2146
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 if (itemsToRemove.size() > 0) {
2148 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002149 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002150 // Remove dead items
2151 for (long id : itemsToRemove) {
2152 if (DEBUG_LOADERS) {
2153 Log.d(TAG, "Removed id = " + id);
2154 }
2155 // Don't notify content observers
2156 try {
2157 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2158 null, null);
2159 } catch (RemoteException e) {
2160 Log.w(TAG, "Could not remove id = " + id);
2161 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002162 }
2163 }
2164
Chris Wrenf4d08112014-01-16 18:13:56 -05002165 if (restoredRows.size() > 0) {
2166 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2167 LauncherSettings.Favorites.CONTENT_URI);
2168 // Update restored items that no longer require special handling
2169 try {
2170 StringBuilder selectionBuilder = new StringBuilder();
2171 selectionBuilder.append(LauncherSettings.Favorites._ID);
2172 selectionBuilder.append(" IN (");
2173 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2174 selectionBuilder.append(")");
2175 ContentValues values = new ContentValues();
2176 values.put(LauncherSettings.Favorites.RESTORED, 0);
2177 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2178 values, selectionBuilder.toString(), null);
2179 } catch (RemoteException e) {
2180 Log.w(TAG, "Could not update restored rows");
2181 }
2182 }
2183
Winson Chungc763c4e2013-07-19 13:49:06 -07002184 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002185 long maxScreenId = 0;
2186 // If we're importing we use the old screen order.
2187 for (ItemInfo item: sBgItemsIdMap.values()) {
2188 long screenId = item.screenId;
2189 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2190 !sBgWorkspaceScreens.contains(screenId)) {
2191 sBgWorkspaceScreens.add(screenId);
2192 if (screenId > maxScreenId) {
2193 maxScreenId = screenId;
2194 }
2195 }
2196 }
2197 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002198 // Log to disk
2199 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2200 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2201 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002202
Michael Jurka414300a2013-08-27 15:42:35 +02002203 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002204 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002205
2206 // Update the max item id after we load an old db
2207 long maxItemId = 0;
2208 // If we're importing we use the old screen order.
2209 for (ItemInfo item: sBgItemsIdMap.values()) {
2210 maxItemId = Math.max(maxItemId, item.id);
2211 }
Michael Jurka414300a2013-08-27 15:42:35 +02002212 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002213 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002214 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2215 for (Integer i : orderedScreens.keySet()) {
2216 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002217 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002218 // Log to disk
2219 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2220 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002221
2222 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002223 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002224 for (ItemInfo item: sBgItemsIdMap.values()) {
2225 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002226 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2227 unusedScreens.contains(screenId)) {
2228 unusedScreens.remove(screenId);
2229 }
2230 }
2231
2232 // If there are any empty screens remove them, and update.
2233 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002234 // Log to disk
2235 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2236 TextUtils.join(", ", unusedScreens), true);
2237
Winson Chung933bae62013-08-29 11:42:30 -07002238 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002239 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2240 }
2241 }
2242
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002243 if (DEBUG_LOADERS) {
2244 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2245 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002246 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002247 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002248 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002249
Daniel Sandler566da102013-06-25 23:43:45 -04002250 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002251 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002252 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002253 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002254 line += " | ";
2255 }
Winson Chung892c74d2013-08-22 16:15:50 -07002256 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002257 ItemInfo[][] screen = occupied.get(screenId);
2258 if (x < screen.length && y < screen[x].length) {
2259 line += (screen[x][y] != null) ? "#" : ".";
2260 } else {
2261 line += "!";
2262 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 }
Joe Onorato36115782010-06-17 13:28:48 -04002264 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002265 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002266 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002267 }
Joe Onorato36115782010-06-17 13:28:48 -04002268 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002269 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002270 }
2271
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002272 /** Filters the set of items who are directly or indirectly (via another container) on the
2273 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002274 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 ArrayList<ItemInfo> allWorkspaceItems,
2276 ArrayList<ItemInfo> currentScreenItems,
2277 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002278 // Purge any null ItemInfos
2279 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2280 while (iter.hasNext()) {
2281 ItemInfo i = iter.next();
2282 if (i == null) {
2283 iter.remove();
2284 }
2285 }
2286
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 // Order the set of items by their containers first, this allows use to walk through the
2288 // list sequentially, build up a list of containers that are in the specified screen,
2289 // as well as all items in those containers.
2290 Set<Long> itemsOnScreen = new HashSet<Long>();
2291 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2292 @Override
2293 public int compare(ItemInfo lhs, ItemInfo rhs) {
2294 return (int) (lhs.container - rhs.container);
2295 }
2296 });
2297 for (ItemInfo info : allWorkspaceItems) {
2298 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002299 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002300 currentScreenItems.add(info);
2301 itemsOnScreen.add(info.id);
2302 } else {
2303 otherScreenItems.add(info);
2304 }
2305 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2306 currentScreenItems.add(info);
2307 itemsOnScreen.add(info.id);
2308 } else {
2309 if (itemsOnScreen.contains(info.container)) {
2310 currentScreenItems.add(info);
2311 itemsOnScreen.add(info.id);
2312 } else {
2313 otherScreenItems.add(info);
2314 }
2315 }
2316 }
2317 }
2318
2319 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002320 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002321 ArrayList<LauncherAppWidgetInfo> appWidgets,
2322 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2323 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002324
2325 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002326 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002327 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002328 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002329 currentScreenWidgets.add(widget);
2330 } else {
2331 otherScreenWidgets.add(widget);
2332 }
2333 }
2334 }
2335
2336 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002337 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002338 HashMap<Long, ItemInfo> itemsIdMap,
2339 HashMap<Long, FolderInfo> folders,
2340 HashMap<Long, FolderInfo> currentScreenFolders,
2341 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002342
2343 for (long id : folders.keySet()) {
2344 ItemInfo info = itemsIdMap.get(id);
2345 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002346 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002347 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002348 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002349 currentScreenFolders.put(id, folder);
2350 } else {
2351 otherScreenFolders.put(id, folder);
2352 }
2353 }
2354 }
2355
2356 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2357 * right) */
2358 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002359 final LauncherAppState app = LauncherAppState.getInstance();
2360 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002361 // XXX: review this
2362 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002363 @Override
2364 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002365 int cellCountX = (int) grid.numColumns;
2366 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002367 int screenOffset = cellCountX * cellCountY;
2368 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002369 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002370 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002371 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002372 rhs.cellY * cellCountX + rhs.cellX);
2373 return (int) (lr - rr);
2374 }
2375 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002376 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002377
Adam Cohendcd297f2013-06-18 13:13:40 -07002378 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2379 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002380 final Runnable r = new Runnable() {
2381 @Override
2382 public void run() {
2383 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2384 if (callbacks != null) {
2385 callbacks.bindScreens(orderedScreens);
2386 }
2387 }
2388 };
2389 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2390 }
2391
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002392 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2393 final ArrayList<ItemInfo> workspaceItems,
2394 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2395 final HashMap<Long, FolderInfo> folders,
2396 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002397
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002398 final boolean postOnMainThread = (deferredBindRunnables != null);
2399
2400 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002401 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002402 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002403 final int start = i;
2404 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002405 final Runnable r = new Runnable() {
2406 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002407 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002408 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002409 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002410 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2411 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002412 }
2413 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002414 };
2415 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002416 synchronized (deferredBindRunnables) {
2417 deferredBindRunnables.add(r);
2418 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002419 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002420 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002421 }
Joe Onorato36115782010-06-17 13:28:48 -04002422 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002423
2424 // Bind the folders
2425 if (!folders.isEmpty()) {
2426 final Runnable r = new Runnable() {
2427 public void run() {
2428 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2429 if (callbacks != null) {
2430 callbacks.bindFolders(folders);
2431 }
2432 }
2433 };
2434 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002435 synchronized (deferredBindRunnables) {
2436 deferredBindRunnables.add(r);
2437 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002438 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002439 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 }
2441 }
2442
2443 // Bind the widgets, one at a time
2444 N = appWidgets.size();
2445 for (int i = 0; i < N; i++) {
2446 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2447 final Runnable r = new Runnable() {
2448 public void run() {
2449 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2450 if (callbacks != null) {
2451 callbacks.bindAppWidget(widget);
2452 }
2453 }
2454 };
2455 if (postOnMainThread) {
2456 deferredBindRunnables.add(r);
2457 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002458 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 }
2460 }
2461 }
2462
2463 /**
2464 * Binds all loaded data to actual views on the main thread.
2465 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002466 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467 final long t = SystemClock.uptimeMillis();
2468 Runnable r;
2469
2470 // Don't use these two variables in any of the callback runnables.
2471 // Otherwise we hold a reference to them.
2472 final Callbacks oldCallbacks = mCallbacks.get();
2473 if (oldCallbacks == null) {
2474 // This launcher has exited and nobody bothered to tell us. Just bail.
2475 Log.w(TAG, "LoaderTask running with no launcher");
2476 return;
2477 }
2478
Winson Chung9b9fb962013-11-15 15:39:34 -08002479 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2481 ArrayList<LauncherAppWidgetInfo> appWidgets =
2482 new ArrayList<LauncherAppWidgetInfo>();
2483 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2484 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002485 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002486 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002487 workspaceItems.addAll(sBgWorkspaceItems);
2488 appWidgets.addAll(sBgAppWidgets);
2489 folders.putAll(sBgFolders);
2490 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002491 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 }
2493
Derek Prothro7aff3992013-12-10 14:00:37 -05002494 final boolean isLoadingSynchronously =
2495 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002496 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002497 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002498 if (currScreen >= orderedScreenIds.size()) {
2499 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002500 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002501 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002502 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002503 final long currentScreenId = currentScreen < 0
2504 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002505
2506 // Load all the items that are on the current page first (and in the process, unbind
2507 // all the existing workspace items before we call startBinding() below.
2508 unbindWorkspaceItemsOnMainThread();
2509
2510 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2512 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2513 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2514 new ArrayList<LauncherAppWidgetInfo>();
2515 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2516 new ArrayList<LauncherAppWidgetInfo>();
2517 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2518 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2519
Winson Chung9b9fb962013-11-15 15:39:34 -08002520 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002522 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002524 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002525 otherFolders);
2526 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2527 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2528
2529 // Tell the workspace that we're about to start binding items
2530 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002531 public void run() {
2532 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2533 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002535 }
2536 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002537 };
Winson Chung81b52252012-08-27 15:34:29 -07002538 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539
Adam Cohendcd297f2013-06-18 13:13:40 -07002540 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2541
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542 // Load items on the current page
2543 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2544 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002545 if (isLoadingSynchronously) {
2546 r = new Runnable() {
2547 public void run() {
2548 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002549 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002550 callbacks.onPageBoundSynchronously(currentScreen);
2551 }
2552 }
2553 };
Winson Chung81b52252012-08-27 15:34:29 -07002554 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002555 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002556
Winson Chung4a2afa32012-07-19 14:53:05 -07002557 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2558 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002559 synchronized (mDeferredBindRunnables) {
2560 mDeferredBindRunnables.clear();
2561 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002563 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002564
2565 // Tell the workspace that we're done binding items
2566 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002567 public void run() {
2568 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2569 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002570 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002571 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002572
Winson Chung98e030b2012-05-07 16:01:11 -07002573 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002574 if (DEBUG_LOADERS) {
2575 Log.d(TAG, "bound workspace in "
2576 + (SystemClock.uptimeMillis()-t) + "ms");
2577 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002578
2579 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002580 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002581 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002582 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002583 synchronized (mDeferredBindRunnables) {
2584 mDeferredBindRunnables.add(r);
2585 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002586 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002587 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002588 }
Joe Onorato36115782010-06-17 13:28:48 -04002589 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002590
Joe Onorato36115782010-06-17 13:28:48 -04002591 private void loadAndBindAllApps() {
2592 if (DEBUG_LOADERS) {
2593 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2594 }
2595 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002596 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002597 synchronized (LoaderTask.this) {
2598 if (mStopped) {
2599 return;
2600 }
2601 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002602 }
Joe Onorato36115782010-06-17 13:28:48 -04002603 } else {
2604 onlyBindAllApps();
2605 }
2606 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002607
Joe Onorato36115782010-06-17 13:28:48 -04002608 private void onlyBindAllApps() {
2609 final Callbacks oldCallbacks = mCallbacks.get();
2610 if (oldCallbacks == null) {
2611 // This launcher has exited and nobody bothered to tell us. Just bail.
2612 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2613 return;
2614 }
2615
2616 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002617 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002618 final ArrayList<AppInfo> list
2619 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002620 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002621 public void run() {
2622 final long t = SystemClock.uptimeMillis();
2623 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2624 if (callbacks != null) {
2625 callbacks.bindAllApplications(list);
2626 }
2627 if (DEBUG_LOADERS) {
2628 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2629 + (SystemClock.uptimeMillis()-t) + "ms");
2630 }
2631 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002632 };
2633 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002634 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002635 r.run();
2636 } else {
2637 mHandler.post(r);
2638 }
Joe Onorato36115782010-06-17 13:28:48 -04002639 }
2640
Winson Chung64359a52013-07-08 17:17:08 -07002641 private void loadAllApps() {
2642 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002643
Joe Onorato36115782010-06-17 13:28:48 -04002644 final Callbacks oldCallbacks = mCallbacks.get();
2645 if (oldCallbacks == null) {
2646 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002647 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002648 return;
2649 }
2650
2651 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2652 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2653
Kenny Guyed131872014-04-30 03:02:21 +01002654 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2655
Winson Chung64359a52013-07-08 17:17:08 -07002656 // Clear the list of apps
2657 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002658 for (UserHandleCompat user : profiles) {
2659 // Query for the set of apps
2660 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2661 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2662 if (DEBUG_LOADERS) {
2663 Log.d(TAG, "getActivityList took "
2664 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2665 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2666 }
2667 // Fail if we don't have any apps
2668 if (apps == null || apps.isEmpty()) {
2669 return;
2670 }
2671 // Sort the applications by name
2672 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2673 Collections.sort(apps,
2674 new LauncherModel.ShortcutNameComparator(mLabelCache));
2675 if (DEBUG_LOADERS) {
2676 Log.d(TAG, "sort took "
2677 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2678 }
Joe Onorato36115782010-06-17 13:28:48 -04002679
Kenny Guyed131872014-04-30 03:02:21 +01002680 // Create the ApplicationInfos
2681 for (int i = 0; i < apps.size(); i++) {
2682 LauncherActivityInfoCompat app = apps.get(i);
2683 // This builds the icon bitmaps.
2684 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2685 }
Winson Chung64359a52013-07-08 17:17:08 -07002686 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002687 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002688 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2689 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002690
2691 // Post callback on main thread
2692 mHandler.post(new Runnable() {
2693 public void run() {
2694 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002695 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002696 if (callbacks != null) {
2697 callbacks.bindAllApplications(added);
2698 if (DEBUG_LOADERS) {
2699 Log.d(TAG, "bound " + added.size() + " apps in "
2700 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2701 }
2702 } else {
2703 Log.i(TAG, "not binding apps: no Launcher activity");
2704 }
2705 }
2706 });
2707
Joe Onorato36115782010-06-17 13:28:48 -04002708 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002709 Log.d(TAG, "Icons processed in "
2710 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002711 }
2712 }
2713
2714 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002715 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002716 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2717 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2718 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2719 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2720 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2721 }
Joe Onorato36115782010-06-17 13:28:48 -04002722 }
2723 }
2724
2725 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002726 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002727 }
2728
2729 private class PackageUpdatedTask implements Runnable {
2730 int mOp;
2731 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002732 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002733
2734 public static final int OP_NONE = 0;
2735 public static final int OP_ADD = 1;
2736 public static final int OP_UPDATE = 2;
2737 public static final int OP_REMOVE = 3; // uninstlled
2738 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2739
2740
Kenny Guyed131872014-04-30 03:02:21 +01002741 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002742 mOp = op;
2743 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002744 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002745 }
2746
2747 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002748 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002749
2750 final String[] packages = mPackages;
2751 final int N = packages.length;
2752 switch (mOp) {
2753 case OP_ADD:
2754 for (int i=0; i<N; i++) {
2755 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002756 mIconCache.remove(packages[i], mUser);
2757 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002758 }
2759 break;
2760 case OP_UPDATE:
2761 for (int i=0; i<N; i++) {
2762 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002763 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002764 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002765 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002766 }
2767 break;
2768 case OP_REMOVE:
2769 case OP_UNAVAILABLE:
2770 for (int i=0; i<N; i++) {
2771 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002772 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002773 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002774 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002775 }
2776 break;
2777 }
2778
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002779 ArrayList<AppInfo> added = null;
2780 ArrayList<AppInfo> modified = null;
2781 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002782
Adam Cohen487f7dd2012-06-28 18:12:10 -07002783 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002784 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002785 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002786 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002787 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002788 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002789 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002790 }
Winson Chung5d55f332012-07-16 20:45:03 -07002791 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002792 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002793 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002794 }
2795
Joe Onorato36115782010-06-17 13:28:48 -04002796 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2797 if (callbacks == null) {
2798 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2799 return;
2800 }
2801
2802 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002803 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002804 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002805 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002806 addAndBindAddedWorkspaceApps(context, addedInfos);
2807 } else {
2808 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002809 }
Joe Onorato36115782010-06-17 13:28:48 -04002810 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002811
Joe Onorato36115782010-06-17 13:28:48 -04002812 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002813 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002814
2815 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002816 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002817 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002818 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002819 for (ItemInfo i : infos) {
2820 if (isShortcutInfoUpdateable(i)) {
2821 ShortcutInfo info = (ShortcutInfo) i;
2822 info.title = a.title.toString();
2823 updateItemInDatabase(context, info);
2824 }
2825 }
2826 }
2827
Joe Onorato36115782010-06-17 13:28:48 -04002828 mHandler.post(new Runnable() {
2829 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002830 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2831 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002832 callbacks.bindAppsUpdated(modifiedFinal);
2833 }
2834 }
2835 });
2836 }
Winson Chung83892cc2013-05-01 16:53:33 -07002837
Winson Chungdf95eb12013-10-16 14:57:07 -07002838 final ArrayList<String> removedPackageNames =
2839 new ArrayList<String>();
2840 if (mOp == OP_REMOVE) {
2841 // Mark all packages in the broadcast to be removed
2842 removedPackageNames.addAll(Arrays.asList(packages));
2843 } else if (mOp == OP_UPDATE) {
2844 // Mark disabled packages in the broadcast to be removed
2845 final PackageManager pm = context.getPackageManager();
2846 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002847 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002848 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002849 }
2850 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002851 }
2852 // Remove all the components associated with this package
2853 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002854 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002855 for (ItemInfo i : infos) {
2856 deleteItemFromDatabase(context, i);
2857 }
2858 }
2859 // Remove all the specific components
2860 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002861 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002862 for (ItemInfo i : infos) {
2863 deleteItemFromDatabase(context, i);
2864 }
2865 }
2866 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2867 // Remove any queued items from the install queue
2868 String spKey = LauncherAppState.getSharedPreferencesKey();
2869 SharedPreferences sp =
2870 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2871 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2872 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002873 mHandler.post(new Runnable() {
2874 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002875 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2876 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01002877 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002878 }
2879 }
2880 });
Joe Onoratobe386092009-11-17 17:32:16 -08002881 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002882
Michael Jurkac402cd92013-05-20 15:49:32 +02002883 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01002884 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002885 mHandler.post(new Runnable() {
2886 @Override
2887 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002888 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2889 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002890 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002891 }
2892 }
2893 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002894
2895 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002896 mHandler.post(new Runnable() {
2897 public void run() {
2898 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2899 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002900 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002901 }
2902 }
2903 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002904 }
2905 }
2906
Michael Jurkac402cd92013-05-20 15:49:32 +02002907 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2908 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2909 PackageManager packageManager = context.getPackageManager();
2910 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2911 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2912 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2913 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2914 Collections.sort(widgetsAndShortcuts,
2915 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2916 return widgetsAndShortcuts;
2917 }
2918
Kenny Guyed131872014-04-30 03:02:21 +01002919 private static boolean isPackageDisabled(Context context, String packageName,
2920 UserHandleCompat user) {
2921 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
2922 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07002923 }
Adam Cohen556f6132014-01-15 15:18:08 -08002924
Kenny Guyed131872014-04-30 03:02:21 +01002925 public static boolean isValidPackageActivity(Context context, ComponentName cn,
2926 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07002927 if (cn == null) {
2928 return false;
2929 }
Kenny Guyed131872014-04-30 03:02:21 +01002930 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
2931 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002932 return false;
2933 }
Kenny Guyed131872014-04-30 03:02:21 +01002934 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07002935 }
2936
Adam Cohena28b78e2014-05-20 17:03:04 -07002937 public static boolean isValidPackage(Context context, String packageName,
2938 UserHandleCompat user) {
2939 if (packageName == null) {
2940 return false;
2941 }
2942 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
2943 return launcherApps.isPackageEnabledForProfile(packageName, user);
2944 }
2945
Joe Onorato9c1289c2009-08-17 11:03:03 -04002946 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05002947 * Make an ShortcutInfo object for a restored application or shortcut item that points
2948 * to a package that is not yet installed on the system.
2949 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05002950 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002951 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05002952 if (cursor != null) {
2953 info.title = cursor.getString(titleIndex);
2954 } else {
2955 info.title = "";
2956 }
Kenny Guyed131872014-04-30 03:02:21 +01002957 info.user = UserHandleCompat.myUserHandle();
2958 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user));
Chris Wrenf4d08112014-01-16 18:13:56 -05002959 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05002960 info.restoredIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05002961 return info;
2962 }
2963
2964 /**
2965 * Make an Intent object for a restored application or shortcut item that points
2966 * to the market page for the item.
2967 */
2968 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05002969 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05002970 ComponentName componentName = intent.getComponent();
2971 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
2972 Uri marketUri = new Uri.Builder()
2973 .scheme("market")
2974 .authority("details")
2975 .appendQueryParameter("id", componentName.getPackageName())
2976 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05002977 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05002978 marketIntent.setData(marketUri);
2979 return marketIntent;
2980 }
2981
2982 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002983 * This is called from the code that adds shortcuts from the intent receiver. This
2984 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002985 */
Kenny Guyed131872014-04-30 03:02:21 +01002986 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
2987 UserHandleCompat user, Context context) {
2988 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002989 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002990
Joe Onorato56d82912010-03-07 14:32:10 -05002991 /**
2992 * Make an ShortcutInfo object for a shortcut that is an application.
2993 *
2994 * If c is not null, then it will be used to fill in missing data like the title and icon.
2995 */
Kenny Guyed131872014-04-30 03:02:21 +01002996 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
2997 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
2998 HashMap<Object, CharSequence> labelCache) {
2999 if (user == null) {
3000 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003001 return null;
3002 }
3003
Kenny Guyed131872014-04-30 03:02:21 +01003004 ComponentName componentName = intent.getComponent();
3005 if (componentName == null) {
3006 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3007 return null;
3008 }
3009
3010 Intent newIntent = new Intent(intent.getAction(), null);
3011 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3012 newIntent.setComponent(componentName);
3013 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
3014 if (lai == null) {
3015 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3016 return null;
3017 }
3018
3019 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003020
Joe Onorato56d82912010-03-07 14:32:10 -05003021 // the resource -- This may implicitly give us back the fallback icon,
3022 // but don't worry about that. All we're doing with usingFallbackIcon is
3023 // to avoid saving lots of copies of that in the database, and most apps
3024 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003025 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003026
Joe Onorato56d82912010-03-07 14:32:10 -05003027 // the db
3028 if (icon == null) {
3029 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003030 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003031 }
3032 }
3033 // the fallback icon
3034 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003035 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003036 info.usingFallbackIcon = true;
3037 }
3038 info.setIcon(icon);
3039
Kenny Guyed131872014-04-30 03:02:21 +01003040 // From the cache.
3041 if (labelCache != null) {
3042 info.title = labelCache.get(componentName);
3043 }
3044
Joe Onorato56d82912010-03-07 14:32:10 -05003045 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003046 if (info.title == null && lai != null) {
3047 info.title = lai.getLabel();
3048 if (labelCache != null) {
3049 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003050 }
Joe Onorato56d82912010-03-07 14:32:10 -05003051 }
3052 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003053 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003054 if (c != null) {
3055 info.title = c.getString(titleIndex);
3056 }
3057 }
3058 // fall back to the class name of the activity
3059 if (info.title == null) {
3060 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003061 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003062 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003063 info.user = user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003064 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003065 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003066
Winson Chung64359a52013-07-08 17:17:08 -07003067 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3068 ItemInfoFilter f) {
3069 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3070 for (ItemInfo i : infos) {
3071 if (i instanceof ShortcutInfo) {
3072 ShortcutInfo info = (ShortcutInfo) i;
3073 ComponentName cn = info.intent.getComponent();
3074 if (cn != null && f.filterItem(null, info, cn)) {
3075 filtered.add(info);
3076 }
3077 } else if (i instanceof FolderInfo) {
3078 FolderInfo info = (FolderInfo) i;
3079 for (ShortcutInfo s : info.contents) {
3080 ComponentName cn = s.intent.getComponent();
3081 if (cn != null && f.filterItem(info, s, cn)) {
3082 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003083 }
3084 }
Winson Chung64359a52013-07-08 17:17:08 -07003085 } else if (i instanceof LauncherAppWidgetInfo) {
3086 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3087 ComponentName cn = info.providerName;
3088 if (cn != null && f.filterItem(null, info, cn)) {
3089 filtered.add(info);
3090 }
Winson Chung8a435102012-08-30 17:16:53 -07003091 }
3092 }
Winson Chung64359a52013-07-08 17:17:08 -07003093 return new ArrayList<ItemInfo>(filtered);
3094 }
3095
Kenny Guyed131872014-04-30 03:02:21 +01003096 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3097 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003098 ItemInfoFilter filter = new ItemInfoFilter() {
3099 @Override
3100 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003101 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003102 }
3103 };
3104 return filterItemInfos(sBgItemsIdMap.values(), filter);
3105 }
3106
Kenny Guyed131872014-04-30 03:02:21 +01003107 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3108 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003109 ItemInfoFilter filter = new ItemInfoFilter() {
3110 @Override
3111 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003112 if (info.user == null) {
3113 return cn.equals(cname);
3114 } else {
3115 return cn.equals(cname) && info.user.equals(user);
3116 }
Winson Chung64359a52013-07-08 17:17:08 -07003117 }
3118 };
3119 return filterItemInfos(sBgItemsIdMap.values(), filter);
3120 }
3121
3122 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3123 if (i instanceof ShortcutInfo) {
3124 ShortcutInfo info = (ShortcutInfo) i;
3125 // We need to check for ACTION_MAIN otherwise getComponent() might
3126 // return null for some shortcuts (for instance, for shortcuts to
3127 // web pages.)
3128 Intent intent = info.intent;
3129 ComponentName name = intent.getComponent();
3130 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3131 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3132 return true;
3133 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003134 // placeholder shortcuts get special treatment, let them through too.
3135 if (info.getRestoredIntent() != null) {
3136 return true;
3137 }
Winson Chung64359a52013-07-08 17:17:08 -07003138 }
3139 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003140 }
3141
3142 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003143 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003144 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003145 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003146 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3147 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003148
Joe Onorato56d82912010-03-07 14:32:10 -05003149 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003150 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003151 // Non-app shortcuts are only supported for current user.
3152 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003153 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003154
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003155 // TODO: If there's an explicit component and we can't install that, delete it.
3156
Joe Onorato56d82912010-03-07 14:32:10 -05003157 info.title = c.getString(titleIndex);
3158
Joe Onorato9c1289c2009-08-17 11:03:03 -04003159 int iconType = c.getInt(iconTypeIndex);
3160 switch (iconType) {
3161 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3162 String packageName = c.getString(iconPackageIndex);
3163 String resourceName = c.getString(iconResourceIndex);
3164 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003165 info.customIcon = false;
3166 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003167 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003168 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003169 if (resources != null) {
3170 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003171 icon = Utilities.createIconBitmap(
3172 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003173 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003174 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003175 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003176 }
Joe Onorato56d82912010-03-07 14:32:10 -05003177 // the db
3178 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003179 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003180 }
3181 // the fallback icon
3182 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003183 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003184 info.usingFallbackIcon = true;
3185 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003186 break;
3187 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003188 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003189 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003190 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003191 info.customIcon = false;
3192 info.usingFallbackIcon = true;
3193 } else {
3194 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003195 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003196 break;
3197 default:
Kenny Guyed131872014-04-30 03:02:21 +01003198 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003199 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003200 info.customIcon = false;
3201 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003202 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003203 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003204 return info;
3205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003206
Michael Jurka931dc972011-08-05 15:08:15 -07003207 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003208 @SuppressWarnings("all") // suppress dead code warning
3209 final boolean debug = false;
3210 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003211 Log.d(TAG, "getIconFromCursor app="
3212 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3213 }
3214 byte[] data = c.getBlob(iconIndex);
3215 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003216 return Utilities.createIconBitmap(
3217 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003218 } catch (Exception e) {
3219 return null;
3220 }
3221 }
3222
Winson Chung3d503fb2011-07-13 17:25:49 -07003223 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3224 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003225 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003226 if (info == null) {
3227 return null;
3228 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003229 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003230
3231 return info;
3232 }
3233
Winson Chunga9abd0e2010-10-27 17:18:37 -07003234 /**
Winson Chung55cef262010-10-28 14:14:18 -07003235 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3236 */
3237 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3238 ComponentName component) {
3239 List<AppWidgetProviderInfo> widgets =
3240 AppWidgetManager.getInstance(context).getInstalledProviders();
3241 for (AppWidgetProviderInfo info : widgets) {
3242 if (info.provider.equals(component)) {
3243 return info;
3244 }
3245 }
3246 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003247 }
3248
Winson Chung68846fd2010-10-29 11:00:27 -07003249 /**
3250 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3251 */
3252 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3253 final PackageManager packageManager = context.getPackageManager();
3254 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3255 new ArrayList<WidgetMimeTypeHandlerData>();
3256
3257 final Intent supportsIntent =
3258 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3259 supportsIntent.setType(mimeType);
3260
3261 // Create a set of widget configuration components that we can test against
3262 final List<AppWidgetProviderInfo> widgets =
3263 AppWidgetManager.getInstance(context).getInstalledProviders();
3264 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3265 new HashMap<ComponentName, AppWidgetProviderInfo>();
3266 for (AppWidgetProviderInfo info : widgets) {
3267 configurationComponentToWidget.put(info.configure, info);
3268 }
3269
3270 // Run through each of the intents that can handle this type of clip data, and cross
3271 // reference them with the components that are actual configuration components
3272 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3273 PackageManager.MATCH_DEFAULT_ONLY);
3274 for (ResolveInfo info : activities) {
3275 final ActivityInfo activityInfo = info.activityInfo;
3276 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3277 activityInfo.name);
3278 if (configurationComponentToWidget.containsKey(infoComponent)) {
3279 supportedConfigurationActivities.add(
3280 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3281 configurationComponentToWidget.get(infoComponent)));
3282 }
3283 }
3284 return supportedConfigurationActivities;
3285 }
3286
Winson Chunga9abd0e2010-10-27 17:18:37 -07003287 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003288 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3289 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3290 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3291
Adam Cohend9198822011-11-22 16:42:47 -08003292 if (intent == null) {
3293 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3294 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3295 return null;
3296 }
3297
Joe Onorato0589f0f2010-02-08 13:44:00 -08003298 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003299 boolean customIcon = false;
3300 ShortcutIconResource iconResource = null;
3301
3302 if (bitmap != null && bitmap instanceof Bitmap) {
3303 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003304 customIcon = true;
3305 } else {
3306 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3307 if (extra != null && extra instanceof ShortcutIconResource) {
3308 try {
3309 iconResource = (ShortcutIconResource) extra;
3310 final PackageManager packageManager = context.getPackageManager();
3311 Resources resources = packageManager.getResourcesForApplication(
3312 iconResource.packageName);
3313 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003314 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003315 mIconCache.getFullResIcon(resources, id),
3316 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003317 } catch (Exception e) {
3318 Log.w(TAG, "Could not load shortcut icon: " + extra);
3319 }
3320 }
3321 }
3322
Michael Jurkac9d95c52011-08-29 14:03:34 -07003323 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003324
Kenny Guyed131872014-04-30 03:02:21 +01003325 // Only support intents for current user for now. Intents sent from other
3326 // users wouldn't get here without intent forwarding anyway.
3327 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003328 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003329 if (fallbackIcon != null) {
3330 icon = fallbackIcon;
3331 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003332 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003333 info.usingFallbackIcon = true;
3334 }
Joe Onorato56d82912010-03-07 14:32:10 -05003335 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003336 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003337
Joe Onorato0589f0f2010-02-08 13:44:00 -08003338 info.title = name;
3339 info.intent = intent;
3340 info.customIcon = customIcon;
3341 info.iconResource = iconResource;
3342
3343 return info;
3344 }
3345
Winson Chungaac01e12011-08-17 10:37:13 -07003346 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3347 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003348 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003349 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003350 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003351 }
Joe Onorato56d82912010-03-07 14:32:10 -05003352 // If this icon doesn't have a custom icon, check to see
3353 // what's stored in the DB, and if it doesn't match what
3354 // we're going to show, store what we are going to show back
3355 // into the DB. We do this so when we're loading, if the
3356 // package manager can't find an icon (for example because
3357 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003358 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003359 cache.put(info, c.getBlob(iconIndex));
3360 return true;
3361 }
3362 return false;
3363 }
3364 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3365 boolean needSave = false;
3366 try {
3367 if (data != null) {
3368 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3369 Bitmap loaded = info.getIcon(mIconCache);
3370 needSave = !saved.sameAs(loaded);
3371 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003372 needSave = true;
3373 }
Winson Chungaac01e12011-08-17 10:37:13 -07003374 } catch (Exception e) {
3375 needSave = true;
3376 }
3377 if (needSave) {
3378 Log.d(TAG, "going to save icon bitmap for info=" + info);
3379 // This is slower than is ideal, but this only happens once
3380 // or when the app is updated with a new icon.
3381 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003382 }
3383 }
3384
Joe Onorato9c1289c2009-08-17 11:03:03 -04003385 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003386 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003387 * or make a new one.
3388 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003389 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003390 // See if a placeholder was created for us already
3391 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003392 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003393 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003394 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003395 folders.put(id, folderInfo);
3396 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003397 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003398 }
3399
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003400 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003401 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003402 return new Comparator<AppInfo>() {
3403 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003404 if (a.user.equals(b.user)) {
3405 int result = collator.compare(a.title.toString().trim(),
3406 b.title.toString().trim());
3407 if (result == 0) {
3408 result = a.componentName.compareTo(b.componentName);
3409 }
3410 return result;
3411 } else {
3412 // TODO Need to figure out rules for sorting
3413 // profiles, this puts work second.
3414 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003415 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003416 }
Winson Chung11904872012-09-17 16:58:46 -07003417 };
3418 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003419 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3420 = new Comparator<AppInfo>() {
3421 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003422 if (a.firstInstallTime < b.firstInstallTime) return 1;
3423 if (a.firstInstallTime > b.firstInstallTime) return -1;
3424 return 0;
3425 }
3426 };
Winson Chung11904872012-09-17 16:58:46 -07003427 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3428 final Collator collator = Collator.getInstance();
3429 return new Comparator<AppWidgetProviderInfo>() {
3430 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003431 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003432 }
3433 };
3434 }
Winson Chung5308f242011-08-18 12:12:41 -07003435 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3436 if (info.activityInfo != null) {
3437 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3438 } else {
3439 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3440 }
3441 }
Kenny Guyed131872014-04-30 03:02:21 +01003442 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003443 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003444 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003445 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003446 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003447 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003448 }
Kenny Guyed131872014-04-30 03:02:21 +01003449 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003450 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003451 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003452 }
Kenny Guyed131872014-04-30 03:02:21 +01003453 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003454 CharSequence labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003455 ComponentName keyA = a.getComponentName();
3456 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003457 if (mLabelCache.containsKey(keyA)) {
3458 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003459 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003460 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003461
Winson Chung5308f242011-08-18 12:12:41 -07003462 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003463 }
Winson Chung5308f242011-08-18 12:12:41 -07003464 if (mLabelCache.containsKey(keyB)) {
3465 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003466 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003467 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003468
Winson Chung5308f242011-08-18 12:12:41 -07003469 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003470 }
Winson Chung11904872012-09-17 16:58:46 -07003471 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003472 }
3473 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003474 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003475 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003476 private PackageManager mPackageManager;
3477 private HashMap<Object, String> mLabelCache;
3478 WidgetAndShortcutNameComparator(PackageManager pm) {
3479 mPackageManager = pm;
3480 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003481 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003482 }
3483 public final int compare(Object a, Object b) {
3484 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003485 if (mLabelCache.containsKey(a)) {
3486 labelA = mLabelCache.get(a);
3487 } else {
3488 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003489 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003490 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003491 mLabelCache.put(a, labelA);
3492 }
3493 if (mLabelCache.containsKey(b)) {
3494 labelB = mLabelCache.get(b);
3495 } else {
3496 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003497 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003498 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003499 mLabelCache.put(b, labelB);
3500 }
Winson Chung11904872012-09-17 16:58:46 -07003501 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003502 }
3503 };
Joe Onoratobe386092009-11-17 17:32:16 -08003504
3505 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003506 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003507 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3508 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3509 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3510 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003511 if (mLoaderTask != null) {
3512 mLoaderTask.dumpState();
3513 } else {
3514 Log.d(TAG, "mLoaderTask=null");
3515 }
Joe Onoratobe386092009-11-17 17:32:16 -08003516 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003517}