blob: f1e73eb1d84f3b9a2873a9807d2f2c43f232c25a [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;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070022import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentProviderClient;
25import android.content.ContentProviderOperation;
26import android.content.ContentResolver;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080030import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070031import android.content.IntentFilter;
32import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.ActivityInfo;
34import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040035import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070037import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.content.res.Resources;
39import android.database.Cursor;
40import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
42import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080043import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040044import android.os.Handler;
45import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080046import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080047import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070048import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040049import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040050import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080051import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070052import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070053import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010054
Sunny Goyalf599ccf2014-07-08 13:01:29 -070055import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.LauncherActivityInfoCompat;
57import com.android.launcher3.compat.LauncherAppsCompat;
58import com.android.launcher3.compat.UserHandleCompat;
59import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080060
Michael Jurkac2f801e2011-07-12 14:19:46 -070061import java.lang.ref.WeakReference;
62import java.net.URISyntaxException;
63import java.text.Collator;
64import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070065import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070066import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070067import java.util.Collections;
68import java.util.Comparator;
69import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070070import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070071import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070072import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070073import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070074import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070075import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070076import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040086 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
87
Joe Onorato9c1289c2009-08-17 11:03:03 -040088 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070089
Daniel Sandler8707e0f2013-08-15 15:54:18 -070090 // true = use a "More Apps" folder for non-workspace apps on upgrade
91 // false = strew non-workspace apps across the workspace on upgrade
92 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050093 public static final int LOADER_FLAG_NONE = 0;
94 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
95 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
96
Joe Onorato36115782010-06-17 13:28:48 -040097 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050098 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080099
Winson Chungee055712013-07-30 14:46:24 -0700100 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800101 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400102
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400103 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private final Object mLock = new Object();
105 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400106 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700107 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200108 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Winson Chung81b52252012-08-27 15:34:29 -0700110 // Specific runnable types that are run on the main thread deferred handler, this allows us to
111 // clear all queued binding runnables when the Launcher activity is destroyed.
112 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
113 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
114
Jason Monkbbe1e242014-05-16 17:37:34 -0400115 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700116
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700117 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
118 static {
119 sWorkerThread.start();
120 }
121 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
122
Joe Onoratocc67f472010-06-08 10:54:30 -0700123 // We start off with everything not loaded. After that, we assume that
124 // our monitoring of the package manager provides all updates and we never
125 // need to do a requery. These are only ever touched from the loader thread.
126 private boolean mWorkspaceLoaded;
127 private boolean mAllAppsLoaded;
128
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700129 // When we are loading pages synchronously, we can't just post the binding of items on the side
130 // pages as this delays the rotation process. Instead, we wait for a callback from the first
131 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
132 // a normal load, we also clear this set of Runnables.
133 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
134
Joe Onorato9c1289c2009-08-17 11:03:03 -0400135 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700138 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800139
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700140 // The lock that must be acquired before referencing any static bg data structures. Unlike
141 // other locks, this one can generally be held long-term because we never expect any of these
142 // static data structures to be referenced outside of the worker thread except on the first
143 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700144 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
151 // created by LauncherModel that are directly on the home screen (however, no widgets or
152 // shortcuts within folders).
153 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
156 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 new ArrayList<LauncherAppWidgetInfo>();
158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
160 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
163 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700164
165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700168 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
169 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages = new HashMap<>();
170
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700171 // </ only access in worker thread >
172
173 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174
Reena Lee99a73f32011-10-24 17:27:37 -0700175 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700176
Kenny Guyed131872014-04-30 03:02:21 +0100177 private final LauncherAppsCompat mLauncherApps;
178 private final UserManagerCompat mUserManager;
179
Joe Onorato9c1289c2009-08-17 11:03:03 -0400180 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700181 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400182 public int getCurrentWorkspaceScreen();
183 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700184 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
185 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700186 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700187 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500188 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700189 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400190 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200191 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700192 public void bindAppsAdded(ArrayList<Long> newScreens,
193 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700194 ArrayList<ItemInfo> addAnimated,
195 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200196 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500197 public void updatePackageState(String pkgName, int state);
Winson Chung83892cc2013-05-01 16:53:33 -0700198 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100199 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200200 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100201 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700202 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700203 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700204 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206
Winson Chung64359a52013-07-08 17:17:08 -0700207 public interface ItemInfoFilter {
208 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
209 }
210
Bjorn Bringert1307f632013-10-03 22:31:03 +0100211 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800212 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400213
Winson Chungee055712013-07-30 14:46:24 -0700214 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700215 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400216 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
217 // resource string.
218 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
219 ProviderInfo providerInfo =
220 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
221 ProviderInfo redirectProvider =
222 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700223
224 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400225 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700226
227 if (mOldContentProviderExists) {
228 Log.d(TAG, "Old launcher provider exists.");
229 } else {
230 Log.d(TAG, "Old launcher provider does not exist.");
231 }
232
Daniel Sandlere4f98912013-06-25 15:13:26 -0400233 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100234 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800235 mIconCache = iconCache;
236
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400237 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700238 Configuration config = res.getConfiguration();
239 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100240 mLauncherApps = LauncherAppsCompat.getInstance(context);
241 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800242 }
243
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700244 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
245 * posted on the main thread handler. */
246 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700247 runOnMainThread(r, 0);
248 }
249 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700250 if (sWorkerThread.getThreadId() == Process.myTid()) {
251 // If we are on the worker thread, post onto the main handler
252 mHandler.post(r);
253 } else {
254 r.run();
255 }
256 }
257
258 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
259 * posted on the worker thread handler. */
260 private static void runOnWorkerThread(Runnable r) {
261 if (sWorkerThread.getThreadId() == Process.myTid()) {
262 r.run();
263 } else {
264 // If we are not on the worker thread, then post to the worker handler
265 sWorker.post(r);
266 }
267 }
268
Winson Chunge43a1e72014-01-15 10:33:02 -0800269 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
270 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800271 }
272
Winson Chungc9168342013-06-26 14:54:55 -0700273 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
274 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700275 LauncherAppState app = LauncherAppState.getInstance();
276 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
277 final int xCount = (int) grid.numColumns;
278 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700279 boolean[][] occupied = new boolean[xCount][yCount];
280
281 int cellX, cellY, spanX, spanY;
282 for (int i = 0; i < items.size(); ++i) {
283 final ItemInfo item = items.get(i);
284 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
285 if (item.screenId == screen) {
286 cellX = item.cellX;
287 cellY = item.cellY;
288 spanX = item.spanX;
289 spanY = item.spanY;
290 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
291 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
292 occupied[x][y] = true;
293 }
294 }
295 }
296 }
297 }
298
299 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
300 }
301 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700302 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700303 int firstScreenIndex,
304 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700305 // Lock on the app so that we don't try and get the items while apps are being added
306 LauncherAppState app = LauncherAppState.getInstance();
307 LauncherModel model = app.getModel();
308 boolean found = false;
309 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700310 if (sWorkerThread.getThreadId() != Process.myTid()) {
311 // Flush the LauncherModel worker thread, so that if we just did another
312 // processInstallShortcut, we give it time for its shortcut to get added to the
313 // database (getItemsInLocalCoordinates reads the database)
314 model.flushWorkerThread();
315 }
Winson Chungc9168342013-06-26 14:54:55 -0700316 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700317
318 // Try adding to the workspace screens incrementally, starting at the default or center
319 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700320 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
321 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700322 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700323 int[] tmpCoordinates = new int[2];
324 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700325 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700326 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700327 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700328 }
329 }
330 }
Winson Chungc9168342013-06-26 14:54:55 -0700331 return null;
332 }
333
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500334 public void setPackageState(final String pkgName, final int state) {
335 // Process the updated package state
336 Runnable r = new Runnable() {
337 public void run() {
338 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
339 if (callbacks != null) {
340 callbacks.updatePackageState(pkgName, state);
341 }
342 }
343 };
344 mHandler.post(r);
345 }
346
Adam Cohen76a47a12014-02-05 11:47:43 -0800347 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
348 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
349
350 if (allAppsApps == null) {
351 throw new RuntimeException("allAppsApps must not be null");
352 }
353 if (allAppsApps.isEmpty()) {
354 return;
355 }
356
Chris Wrenb6d4c282014-01-27 14:17:08 -0500357 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
358 Iterator<AppInfo> iter = allAppsApps.iterator();
359 while (iter.hasNext()) {
360 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100361 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500362 restoredAppsFinal.add((AppInfo) a);
363 }
364 }
365
Adam Cohen76a47a12014-02-05 11:47:43 -0800366 // Process the newly added applications and add them to the database first
367 Runnable r = new Runnable() {
368 public void run() {
369 runOnMainThread(new Runnable() {
370 public void run() {
371 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
372 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500373 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500374 for (AppInfo info : restoredAppsFinal) {
375 final Intent intent = info.getIntent();
376 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100377 mIconCache.deletePreloadedIcon(intent.getComponent(),
378 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500379 }
380 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500381 callbacks.bindAppsUpdated(restoredAppsFinal);
382 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500383 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800384 }
385 }
386 });
387 }
388 };
389 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700390 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800391
392 public void addAndBindAddedWorkspaceApps(final Context context,
393 final ArrayList<ItemInfo> workspaceApps) {
394 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
395
396 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800397 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
398 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800399 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700400 return;
Winson Chung997a9232013-07-24 15:33:46 -0700401 }
Winson Chung64359a52013-07-08 17:17:08 -0700402 // Process the newly added applications and add them to the database first
403 Runnable r = new Runnable() {
404 public void run() {
405 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
406 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500407 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700408
Winson Chung76828c82013-08-19 15:43:29 -0700409 // Get the list of workspace screens. We need to append to this list and
410 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
411 // called.
412 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
413 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
414 for (Integer i : orderedScreens.keySet()) {
415 long screenId = orderedScreens.get(i);
416 workspaceScreens.add(screenId);
417 }
418
Winson Chung64359a52013-07-08 17:17:08 -0700419 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700420 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700421 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700422 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700423 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700424 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700425
426 // Short-circuit this logic if the icon exists somewhere on the workspace
427 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500428 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
429 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100430 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500431 restoredAppsFinal.add((AppInfo) a);
432 }
Winson Chung64359a52013-07-08 17:17:08 -0700433 continue;
434 }
435
Winson Chung87412982013-10-03 18:34:14 -0700436 // Add this icon to the db, creating a new page if necessary. If there
437 // is only the empty page then we just add items to the first page.
438 // Otherwise, we add them to the next pages.
439 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700440 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700441 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700442 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200443 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700444
445 // If we can't find a valid position, then just add a new screen.
446 // This takes time so we need to re-queue the add until the new
447 // page is added. Create as many screens as necessary to satisfy
448 // the startSearchPageIndex.
449 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700450 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700451 while (numPagesToAdd > 0) {
452 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700453 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700454 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700455 addedWorkspaceScreensFinal.add(screenId);
456 numPagesToAdd--;
457 }
Winson Chung76828c82013-08-19 15:43:29 -0700458
Winson Chung64359a52013-07-08 17:17:08 -0700459 // Find the coordinate again
460 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700461 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700462 }
463 if (coords == null) {
464 throw new RuntimeException("Coordinates should not be null");
465 }
466
Winson Chung997a9232013-07-24 15:33:46 -0700467 ShortcutInfo shortcutInfo;
468 if (a instanceof ShortcutInfo) {
469 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200470 } else if (a instanceof AppInfo) {
471 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700472 } else {
473 throw new RuntimeException("Unexpected info type");
474 }
Winson Chung94d67682013-09-25 16:29:40 -0700475
Winson Chung64359a52013-07-08 17:17:08 -0700476 // Add the shortcut to the db
477 addItemToDatabase(context, shortcutInfo,
478 LauncherSettings.Favorites.CONTAINER_DESKTOP,
479 coords.first, coords.second[0], coords.second[1], false);
480 // Save the ShortcutInfo for binding in the workspace
481 addedShortcutsFinal.add(shortcutInfo);
482 }
483 }
484
Winson Chung76828c82013-08-19 15:43:29 -0700485 // Update the workspace screens
486 updateWorkspaceScreenOrder(context, workspaceScreens);
487
Adam Cohen76a47a12014-02-05 11:47:43 -0800488 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700489 runOnMainThread(new Runnable() {
490 public void run() {
491 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
492 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700493 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
494 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700495 if (!addedShortcutsFinal.isEmpty()) {
496 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
497 long lastScreenId = info.screenId;
498 for (ItemInfo i : addedShortcutsFinal) {
499 if (i.screenId == lastScreenId) {
500 addAnimated.add(i);
501 } else {
502 addNotAnimated.add(i);
503 }
Winson Chung997a9232013-07-24 15:33:46 -0700504 }
505 }
Winson Chungd64d1762013-08-20 14:37:16 -0700506 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800507 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500508 if (!restoredAppsFinal.isEmpty()) {
509 callbacks.bindAppsUpdated(restoredAppsFinal);
510 }
Winson Chung997a9232013-07-24 15:33:46 -0700511 }
Winson Chung64359a52013-07-08 17:17:08 -0700512 }
Winson Chung997a9232013-07-24 15:33:46 -0700513 });
514 }
Winson Chung64359a52013-07-08 17:17:08 -0700515 }
516 };
517 runOnWorkerThread(r);
518 }
519
Winson Chung81b52252012-08-27 15:34:29 -0700520 public void unbindItemInfosAndClearQueuedBindRunnables() {
521 if (sWorkerThread.getThreadId() == Process.myTid()) {
522 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
523 "main thread");
524 }
525
526 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400527 synchronized (mDeferredBindRunnables) {
528 mDeferredBindRunnables.clear();
529 }
Winson Chung81b52252012-08-27 15:34:29 -0700530 // Remove any queued bind runnables
531 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
532 // Unbind all the workspace items
533 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700534 }
535
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700536 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700537 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700538 // Ensure that we don't use the same workspace items data structure on the main thread
539 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700540 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
541 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700542 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700543 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
544 tmpAppWidgets.addAll(sBgAppWidgets);
545 }
546 Runnable r = new Runnable() {
547 @Override
548 public void run() {
549 for (ItemInfo item : tmpWorkspaceItems) {
550 item.unbind();
551 }
552 for (ItemInfo item : tmpAppWidgets) {
553 item.unbind();
554 }
555 }
556 };
557 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700558 }
559
Joe Onorato9c1289c2009-08-17 11:03:03 -0400560 /**
561 * Adds an item to the DB if it was not created previously, or move it to a new
562 * <container, screen, cellX, cellY>
563 */
564 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700565 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400566 if (item.container == ItemInfo.NO_ID) {
567 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700568 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400569 } else {
570 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 }
573 }
574
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700575 static void checkItemInfoLocked(
576 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
577 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
578 if (modelItem != null && item != modelItem) {
579 // check all the data is consistent
580 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
581 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
582 ShortcutInfo shortcut = (ShortcutInfo) item;
583 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
584 modelShortcut.intent.filterEquals(shortcut.intent) &&
585 modelShortcut.id == shortcut.id &&
586 modelShortcut.itemType == shortcut.itemType &&
587 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700588 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700589 modelShortcut.cellX == shortcut.cellX &&
590 modelShortcut.cellY == shortcut.cellY &&
591 modelShortcut.spanX == shortcut.spanX &&
592 modelShortcut.spanY == shortcut.spanY &&
593 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
594 (modelShortcut.dropPos != null &&
595 shortcut.dropPos != null &&
596 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
597 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
598 // For all intents and purposes, this is the same object
599 return;
600 }
601 }
602
603 // the modelItem needs to match up perfectly with item if our model is
604 // to be consistent with the database-- for now, just require
605 // modelItem == item or the equality check above
606 String msg = "item: " + ((item != null) ? item.toString() : "null") +
607 "modelItem: " +
608 ((modelItem != null) ? modelItem.toString() : "null") +
609 "Error: ItemInfo passed to checkItemInfo doesn't match original";
610 RuntimeException e = new RuntimeException(msg);
611 if (stackTrace != null) {
612 e.setStackTrace(stackTrace);
613 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800614 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700615 }
616 }
617
Michael Jurka816474f2012-06-25 14:49:02 -0700618 static void checkItemInfo(final ItemInfo item) {
619 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
620 final long itemId = item.id;
621 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700622 public void run() {
623 synchronized (sBgLock) {
624 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700625 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700626 }
627 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700628 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700629 }
630
Michael Jurkac9d95c52011-08-29 14:03:34 -0700631 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
632 final ItemInfo item, final String callingFunction) {
633 final long itemId = item.id;
634 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
635 final ContentResolver cr = context.getContentResolver();
636
Adam Cohen487f7dd2012-06-28 18:12:10 -0700637 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700638 Runnable r = new Runnable() {
639 public void run() {
640 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700641 updateItemArrays(item, itemId, stackTrace);
642 }
643 };
644 runOnWorkerThread(r);
645 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700646
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700647 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
648 final ArrayList<ItemInfo> items, final String callingFunction) {
649 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700650
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700651 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
652 Runnable r = new Runnable() {
653 public void run() {
654 ArrayList<ContentProviderOperation> ops =
655 new ArrayList<ContentProviderOperation>();
656 int count = items.size();
657 for (int i = 0; i < count; i++) {
658 ItemInfo item = items.get(i);
659 final long itemId = item.id;
660 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
661 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700662
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700663 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
664 updateItemArrays(item, itemId, stackTrace);
665
666 }
667 try {
668 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
669 } catch (Exception e) {
670 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700671 }
672 }
673 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700674 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700675 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700676
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700677 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
678 // Lock on mBgLock *after* the db operation
679 synchronized (sBgLock) {
680 checkItemInfoLocked(itemId, item, stackTrace);
681
682 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
683 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
684 // Item is in a folder, make sure this folder exists
685 if (!sBgFolders.containsKey(item.container)) {
686 // An items container is being set to a that of an item which is not in
687 // the list of Folders.
688 String msg = "item: " + item + " container being set to: " +
689 item.container + ", not in the list of folders";
690 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700691 }
692 }
693
694 // Items are added/removed from the corresponding FolderInfo elsewhere, such
695 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
696 // that are on the desktop, as appropriate
697 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800698 if (modelItem != null &&
699 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
700 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700701 switch (modelItem.itemType) {
702 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
703 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
704 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
705 if (!sBgWorkspaceItems.contains(modelItem)) {
706 sBgWorkspaceItems.add(modelItem);
707 }
708 break;
709 default:
710 break;
711 }
712 } else {
713 sBgWorkspaceItems.remove(modelItem);
714 }
715 }
716 }
717
Michael Jurkac7700af2013-05-14 20:17:58 +0200718 public void flushWorkerThread() {
719 mFlushingWorkerThread = true;
720 Runnable waiter = new Runnable() {
721 public void run() {
722 synchronized (this) {
723 notifyAll();
724 mFlushingWorkerThread = false;
725 }
726 }
727 };
728
729 synchronized(waiter) {
730 runOnWorkerThread(waiter);
731 if (mLoaderTask != null) {
732 synchronized(mLoaderTask) {
733 mLoaderTask.notify();
734 }
735 }
736 boolean success = false;
737 while (!success) {
738 try {
739 waiter.wait();
740 success = true;
741 } catch (InterruptedException e) {
742 }
743 }
744 }
745 }
746
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800747 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400748 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700749 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700750 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400752 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400753 item.cellX = cellX;
754 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700755
Winson Chung3d503fb2011-07-13 17:25:49 -0700756 // We store hotseat items in canonical form which is this orientation invariant position
757 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700759 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700763 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400764
765 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700767 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
768 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700769 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400770
Michael Jurkac9d95c52011-08-29 14:03:34 -0700771 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700772 }
773
774 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700775 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
776 * cellX, cellY have already been updated on the ItemInfos.
777 */
778 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
779 final long container, final int screen) {
780
781 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
782 int count = items.size();
783
784 for (int i = 0; i < count; i++) {
785 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700786 item.container = container;
787
788 // We store hotseat items in canonical form which is this orientation invariant position
789 // in the hotseat
790 if (context instanceof Launcher && screen < 0 &&
791 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700792 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700793 item.cellY);
794 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700796 }
797
798 final ContentValues values = new ContentValues();
799 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
800 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
801 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700802 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700803
804 contentValues.add(values);
805 }
806 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
807 }
808
809 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700810 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800811 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700812 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700814 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800815 item.cellX = cellX;
816 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700817 item.spanX = spanX;
818 item.spanY = spanY;
819
820 // We store hotseat items in canonical form which is this orientation invariant position
821 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700822 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700823 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700825 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 }
Adam Cohend4844c32011-02-18 19:25:06 -0800828
Adam Cohend4844c32011-02-18 19:25:06 -0800829 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800830 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700831 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
832 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
833 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
834 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700835 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800836
Michael Jurka816474f2012-06-25 14:49:02 -0700837 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700838 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700839
840 /**
841 * Update an item to the database in a specified container.
842 */
843 static void updateItemInDatabase(Context context, final ItemInfo item) {
844 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100845 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700846 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
847 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800848 }
849
850 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400851 * Returns true if the shortcuts already exists in the database.
852 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800853 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 static boolean shortcutExists(Context context, String title, Intent intent) {
855 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700856 final Intent intentWithPkg, intentWithoutPkg;
857
858 if (intent.getComponent() != null) {
859 // If component is not null, an intent with null package will produce
860 // the same result and should also be a match.
861 if (intent.getPackage() != null) {
862 intentWithPkg = intent;
863 intentWithoutPkg = new Intent(intent).setPackage(null);
864 } else {
865 intentWithPkg = new Intent(intent).setPackage(
866 intent.getComponent().getPackageName());
867 intentWithoutPkg = intent;
868 }
869 } else {
870 intentWithPkg = intent;
871 intentWithoutPkg = intent;
872 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400873 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700874 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
875 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400876 boolean result = false;
877 try {
878 result = c.moveToFirst();
879 } finally {
880 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800881 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400882 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700883 }
884
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500886 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100887 * we identify a shortcut by the component name of the intent
888 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500889 */
Kenny Guyed131872014-04-30 03:02:21 +0100890 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500891 final ContentResolver cr = context.getContentResolver();
892 final ComponentName component = intent.getComponent();
893 if (component == null) {
894 return false;
895 }
896 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400897 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100898 long serialNumber = UserManagerCompat.getInstance(context)
899 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400900 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
901 "intent glob \"*component=" + shortName + "*\")" +
902 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500903 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100904 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500905 boolean result = false;
906 try {
907 result = c.moveToFirst();
908 } finally {
909 c.close();
910 }
911 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
912 return result;
913 }
914
915 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 * Returns an ItemInfo array containing all the items in the LauncherModel.
917 * The ItemInfo.id is not set through this function.
918 */
919 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
920 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
921 final ContentResolver cr = context.getContentResolver();
922 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
923 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100924 LauncherSettings.Favorites.SCREEN,
925 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
926 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
927 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700928
929 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
930 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
931 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
932 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
933 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
934 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
935 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100936 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
937 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700938 try {
939 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700940 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700941 item.cellX = c.getInt(cellXIndex);
942 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700943 item.spanX = Math.max(1, c.getInt(spanXIndex));
944 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700945 item.container = c.getInt(containerIndex);
946 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100948 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100949 item.user = userManager.getUserForSerialNumber(serialNumber);
950 // Skip if user has been deleted.
951 if (item.user != null) {
952 items.add(item);
953 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700954 }
955 } catch (Exception e) {
956 items.clear();
957 } finally {
958 c.close();
959 }
960
961 return items;
962 }
963
964 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
966 */
967 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
968 final ContentResolver cr = context.getContentResolver();
969 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
970 "_id=? and (itemType=? or itemType=?)",
971 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700972 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700973
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 try {
975 if (c.moveToFirst()) {
976 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
977 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
978 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
979 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
980 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
981 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800982
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 FolderInfo folderInfo = null;
984 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700985 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
986 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400987 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700988 }
989
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 folderInfo.title = c.getString(titleIndex);
991 folderInfo.id = id;
992 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700994 folderInfo.cellX = c.getInt(cellXIndex);
995 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996
997 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700998 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999 } finally {
1000 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001001 }
1002
1003 return null;
1004 }
1005
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006 /**
1007 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1008 * cellY fields of the item. Also assigns an ID to the item.
1009 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001010 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013 item.cellX = cellX;
1014 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001015 // We store hotseat items in canonical form which is this orientation invariant position
1016 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001017 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001018 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001020 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001022 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001023
1024 final ContentValues values = new ContentValues();
1025 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001026 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001027
Michael Jurka414300a2013-08-27 15:42:35 +02001028 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001029 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001030 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001031
Jason Monk8e19cf22014-03-20 15:06:57 -04001032 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001033 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001034 public void run() {
1035 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1036 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001037
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001039 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001040 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 sBgItemsIdMap.put(item.id, item);
1042 switch (item.itemType) {
1043 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1044 sBgFolders.put(item.id, (FolderInfo) item);
1045 // Fall through
1046 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1047 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1048 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1049 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1050 sBgWorkspaceItems.add(item);
1051 } else {
1052 if (!sBgFolders.containsKey(item.container)) {
1053 // Adding an item to a folder that doesn't exist.
1054 String msg = "adding item: " + item + " to a folder that " +
1055 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001056 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001058 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001059 break;
1060 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1061 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1062 break;
1063 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001064 }
1065 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001066 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001067 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001068 }
1069
Joe Onorato9c1289c2009-08-17 11:03:03 -04001070 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001071 * Creates a new unique child id, for a given cell span across all layouts.
1072 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001073 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001075 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001077 }
1078
Winson Chungaafa03c2010-06-11 17:34:16 -07001079 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001080 * Removes the specified item from the database
1081 * @param context
1082 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001083 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001084 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001085 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001086 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001087
Michael Jurka83df1882011-08-31 20:59:26 -07001088 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001089 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001090 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001091
1092 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001093 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001094 switch (item.itemType) {
1095 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1096 sBgFolders.remove(item.id);
1097 for (ItemInfo info: sBgItemsIdMap.values()) {
1098 if (info.container == item.id) {
1099 // We are deleting a folder which still contains items that
1100 // think they are contained by that folder.
1101 String msg = "deleting a folder (" + item + ") which still " +
1102 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001103 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001104 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001105 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106 sBgWorkspaceItems.remove(item);
1107 break;
1108 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1109 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1110 sBgWorkspaceItems.remove(item);
1111 break;
1112 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1113 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1114 break;
1115 }
1116 sBgItemsIdMap.remove(item.id);
1117 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001118 }
1119 }
Michael Jurka83df1882011-08-31 20:59:26 -07001120 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001122 }
1123
1124 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001125 * Update the order of the workspace screens in the database. The array list contains
1126 * a list of screen ids in the order that they should appear.
1127 */
Winson Chungc9168342013-06-26 14:54:55 -07001128 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001129 // Log to disk
1130 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1131 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1132
Winson Chung64359a52013-07-08 17:17:08 -07001133 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001134 final ContentResolver cr = context.getContentResolver();
1135 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1136
1137 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001138 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001139 while (iter.hasNext()) {
1140 long id = iter.next();
1141 if (id < 0) {
1142 iter.remove();
1143 }
1144 }
1145
1146 Runnable r = new Runnable() {
1147 @Override
1148 public void run() {
Yura085c8532014-02-11 15:15:29 +00001149 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001151 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001152 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001153 for (int i = 0; i < count; i++) {
1154 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001155 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001156 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1157 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001158 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001159 }
Yura085c8532014-02-11 15:15:29 +00001160
1161 try {
1162 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1163 } catch (Exception ex) {
1164 throw new RuntimeException(ex);
1165 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001166
Winson Chungba9c37f2013-08-30 14:11:37 -07001167 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001168 sBgWorkspaceScreens.clear();
1169 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001170 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 }
1172 };
1173 runOnWorkerThread(r);
1174 }
1175
1176 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001177 * Remove the contents of the specified folder from the database
1178 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001179 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001180 final ContentResolver cr = context.getContentResolver();
1181
Michael Jurkac9d95c52011-08-29 14:03:34 -07001182 Runnable r = new Runnable() {
1183 public void run() {
1184 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001185 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001186 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001187 sBgItemsIdMap.remove(info.id);
1188 sBgFolders.remove(info.id);
1189 sBgDbIconCache.remove(info);
1190 sBgWorkspaceItems.remove(info);
1191 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001192
Michael Jurkac9d95c52011-08-29 14:03:34 -07001193 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1194 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001195 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001196 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 for (ItemInfo childInfo : info.contents) {
1198 sBgItemsIdMap.remove(childInfo.id);
1199 sBgDbIconCache.remove(childInfo);
1200 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001201 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001202 }
1203 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001205 }
1206
1207 /**
1208 * Set this as the current Launcher activity object for the loader.
1209 */
1210 public void initialize(Callbacks callbacks) {
1211 synchronized (mLock) {
1212 mCallbacks = new WeakReference<Callbacks>(callbacks);
1213 }
1214 }
1215
Kenny Guyed131872014-04-30 03:02:21 +01001216 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001217 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001218 int op = PackageUpdatedTask.OP_UPDATE;
1219 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1220 user));
1221 }
1222
1223 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001224 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001225 int op = PackageUpdatedTask.OP_REMOVE;
1226 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1227 user));
1228 }
1229
1230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_ADD;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001239 boolean replacing) {
1240 if (!replacing) {
1241 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1242 user));
1243 if (mAppsCanBeOnRemoveableStorage) {
1244 // Only rebind if we support removable storage. It catches the
1245 // case where
1246 // apps on the external sd card need to be reloaded
1247 startLoaderFromBackground();
1248 }
1249 } else {
1250 // If we are replacing then just update the packages in the list
1251 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1252 packageNames, user));
1253 }
1254 }
1255
1256 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001257 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001258 boolean replacing) {
1259 if (!replacing) {
1260 enqueuePackageUpdated(new PackageUpdatedTask(
1261 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1262 user));
1263 }
1264
1265 }
1266
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001267 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001268 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1269 * ACTION_PACKAGE_CHANGED.
1270 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001271 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001272 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001273 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001274
Joe Onorato36115782010-06-17 13:28:48 -04001275 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001276 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001277 // If we have changed locale we need to clear out the labels in all apps/workspace.
1278 forceReload();
1279 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1280 // Check if configuration change was an mcc/mnc change which would affect app resources
1281 // and we would need to clear out the labels in all apps/workspace. Same handling as
1282 // above for ACTION_LOCALE_CHANGED
1283 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001284 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001285 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001286 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001287 forceReload();
1288 }
1289 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001290 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001291 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1292 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001293 if (mCallbacks != null) {
1294 Callbacks callbacks = mCallbacks.get();
1295 if (callbacks != null) {
1296 callbacks.bindSearchablesChanged();
1297 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001298 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001299 }
1300 }
1301
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001302 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001303 resetLoadedState(true, true);
1304
Reena Lee93f824a2011-09-23 17:20:28 -07001305 // Do this here because if the launcher activity is running it will be restarted.
1306 // If it's not running startLoaderFromBackground will merely tell it that it needs
1307 // to reload.
1308 startLoaderFromBackground();
1309 }
1310
Winson Chungf0c6ae02012-03-21 16:10:31 -07001311 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1312 synchronized (mLock) {
1313 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1314 // mWorkspaceLoaded to true later
1315 stopLoaderLocked();
1316 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1317 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1318 }
1319 }
1320
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001321 /**
1322 * When the launcher is in the background, it's possible for it to miss paired
1323 * configuration changes. So whenever we trigger the loader from the background
1324 * tell the launcher that it needs to re-run the loader when it comes back instead
1325 * of doing it now.
1326 */
1327 public void startLoaderFromBackground() {
1328 boolean runLoader = false;
1329 if (mCallbacks != null) {
1330 Callbacks callbacks = mCallbacks.get();
1331 if (callbacks != null) {
1332 // Only actually run the loader if they're not paused.
1333 if (!callbacks.setLoadOnResume()) {
1334 runLoader = true;
1335 }
1336 }
1337 }
1338 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001339 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001340 }
Joe Onorato36115782010-06-17 13:28:48 -04001341 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001342
Reena Lee93f824a2011-09-23 17:20:28 -07001343 // If there is already a loader task running, tell it to stop.
1344 // returns true if isLaunching() was true on the old task
1345 private boolean stopLoaderLocked() {
1346 boolean isLaunching = false;
1347 LoaderTask oldTask = mLoaderTask;
1348 if (oldTask != null) {
1349 if (oldTask.isLaunching()) {
1350 isLaunching = true;
1351 }
1352 oldTask.stopLocked();
1353 }
1354 return isLaunching;
1355 }
1356
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001357 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001358 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1359 }
1360
1361 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001362 synchronized (mLock) {
1363 if (DEBUG_LOADERS) {
1364 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1365 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001366
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001367 // Clear any deferred bind-runnables from the synchronized load process
1368 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001369 synchronized (mDeferredBindRunnables) {
1370 mDeferredBindRunnables.clear();
1371 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001372
Joe Onorato36115782010-06-17 13:28:48 -04001373 // Don't bother to start the thread if we know it's not going to do anything
1374 if (mCallbacks != null && mCallbacks.get() != null) {
1375 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001376 // also, don't downgrade isLaunching if we're already running
1377 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001378 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001379 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1380 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1382 } else {
1383 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1384 sWorker.post(mLoaderTask);
1385 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001386 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001387 }
1388 }
1389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 void bindRemainingSynchronousPages() {
1391 // Post the remaining side pages to be loaded
1392 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001393 Runnable[] deferredBindRunnables = null;
1394 synchronized (mDeferredBindRunnables) {
1395 deferredBindRunnables = mDeferredBindRunnables.toArray(
1396 new Runnable[mDeferredBindRunnables.size()]);
1397 mDeferredBindRunnables.clear();
1398 }
1399 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001400 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 }
1403 }
1404
Joe Onorato36115782010-06-17 13:28:48 -04001405 public void stopLoader() {
1406 synchronized (mLock) {
1407 if (mLoaderTask != null) {
1408 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001409 }
1410 }
Joe Onorato36115782010-06-17 13:28:48 -04001411 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001412
Winson Chung76828c82013-08-19 15:43:29 -07001413 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1414 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1415 final ContentResolver contentResolver = context.getContentResolver();
1416 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1417 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1418 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1419
1420 try {
1421 final int idIndex = sc.getColumnIndexOrThrow(
1422 LauncherSettings.WorkspaceScreens._ID);
1423 final int rankIndex = sc.getColumnIndexOrThrow(
1424 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1425 while (sc.moveToNext()) {
1426 try {
1427 long screenId = sc.getLong(idIndex);
1428 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001429 orderedScreens.put(rank, screenId);
1430 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001431 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001432 }
1433 }
1434 } finally {
1435 sc.close();
1436 }
Winson Chunga90303b2013-11-15 13:05:06 -08001437
1438 // Log to disk
1439 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1440 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1441 for (Integer i : orderedScreens.keySet()) {
1442 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1443 }
1444 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1445 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001446 return orderedScreens;
1447 }
1448
Michael Jurkac57b7a82011-08-09 22:02:20 -07001449 public boolean isAllAppsLoaded() {
1450 return mAllAppsLoaded;
1451 }
1452
Winson Chung36a62fe2012-05-06 18:04:42 -07001453 boolean isLoadingWorkspace() {
1454 synchronized (mLock) {
1455 if (mLoaderTask != null) {
1456 return mLoaderTask.isLoadingWorkspace();
1457 }
1458 }
1459 return false;
1460 }
1461
Joe Onorato36115782010-06-17 13:28:48 -04001462 /**
1463 * Runnable for the thread that loads the contents of the launcher:
1464 * - workspace icons
1465 * - widgets
1466 * - all apps icons
1467 */
1468 private class LoaderTask implements Runnable {
1469 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001470 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001471 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001472 private boolean mStopped;
1473 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001474 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001475
Winson Chungc3eecff2011-07-11 17:44:15 -07001476 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001477
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001479 mContext = context;
1480 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001481 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001482 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 boolean isLaunching() {
1486 return mIsLaunching;
1487 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 boolean isLoadingWorkspace() {
1490 return mIsLoadingAndBindingWorkspace;
1491 }
1492
Winson Chungc763c4e2013-07-19 13:49:06 -07001493 /** Returns whether this is an upgrade path */
1494 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001495 mIsLoadingAndBindingWorkspace = true;
1496
Joe Onorato36115782010-06-17 13:28:48 -04001497 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001498 if (DEBUG_LOADERS) {
1499 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001500 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001501
Winson Chungc763c4e2013-07-19 13:49:06 -07001502 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001503 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001504 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001505 synchronized (LoaderTask.this) {
1506 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001507 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001508 }
1509 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001510 }
1511 }
1512
Joe Onorato36115782010-06-17 13:28:48 -04001513 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001514 bindWorkspace(-1, isUpgradePath);
1515 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001516 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001517
Joe Onorato36115782010-06-17 13:28:48 -04001518 private void waitForIdle() {
1519 // Wait until the either we're stopped or the other threads are done.
1520 // This way we don't start loading all apps until the workspace has settled
1521 // down.
1522 synchronized (LoaderTask.this) {
1523 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001524
Joe Onorato36115782010-06-17 13:28:48 -04001525 mHandler.postIdle(new Runnable() {
1526 public void run() {
1527 synchronized (LoaderTask.this) {
1528 mLoadAndBindStepFinished = true;
1529 if (DEBUG_LOADERS) {
1530 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Joe Onorato36115782010-06-17 13:28:48 -04001532 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001533 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001534 }
Joe Onorato36115782010-06-17 13:28:48 -04001535 });
1536
Michael Jurkac7700af2013-05-14 20:17:58 +02001537 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001538 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001539 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1540 // wait no longer than 1sec at a time
1541 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001542 } catch (InterruptedException ex) {
1543 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001544 }
1545 }
Joe Onorato36115782010-06-17 13:28:48 -04001546 if (DEBUG_LOADERS) {
1547 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001548 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001549 + "ms for previous step to finish binding");
1550 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001551 }
Joe Onorato36115782010-06-17 13:28:48 -04001552 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001553
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001555 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001556 // Ensure that we have a valid page index to load synchronously
1557 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1558 "valid page index");
1559 }
1560 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1561 // Ensure that we don't try and bind a specified page when the pages have not been
1562 // loaded already (we should load everything asynchronously in that case)
1563 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1564 }
1565 synchronized (mLock) {
1566 if (mIsLoaderTaskRunning) {
1567 // Ensure that we are never running the background loading at this point since
1568 // we also touch the background collections
1569 throw new RuntimeException("Error! Background loading is already running");
1570 }
1571 }
1572
1573 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1574 // data structures, we can't allow any other thread to touch that data, but because
1575 // this call is synchronous, we can get away with not locking).
1576
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001577 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001578 // operations from the previous activity. We need to ensure that all queued operations
1579 // are executed before any synchronous binding work is done.
1580 mHandler.flush();
1581
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 // Divide the set of loaded items into those that we are binding synchronously, and
1583 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001584 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1586 // arise from that.
1587 onlyBindAllApps();
1588 }
1589
Joe Onorato36115782010-06-17 13:28:48 -04001590 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001591 boolean isUpgrade = false;
1592
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001593 synchronized (mLock) {
1594 mIsLoaderTaskRunning = true;
1595 }
Joe Onorato36115782010-06-17 13:28:48 -04001596 // Optimize for end-user experience: if the Launcher is up and // running with the
1597 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1598 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001599 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001600 // Elevate priority when Home launches for the first time to avoid
1601 // starving at boot time. Staring at a blank home is not cool.
1602 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001603 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1604 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001605 android.os.Process.setThreadPriority(mIsLaunching
1606 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1607 }
Winson Chung64359a52013-07-08 17:17:08 -07001608 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001609 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001610
Joe Onorato36115782010-06-17 13:28:48 -04001611 if (mStopped) {
1612 break keep_running;
1613 }
1614
1615 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1616 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001617 synchronized (mLock) {
1618 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001619 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001620 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1621 }
1622 }
Joe Onorato36115782010-06-17 13:28:48 -04001623 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001624
1625 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001626 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1627 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001628
1629 // Restore the default thread priority after we are done loading items
1630 synchronized (mLock) {
1631 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632 }
Joe Onorato36115782010-06-17 13:28:48 -04001633 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001634
Winson Chungaac01e12011-08-17 10:37:13 -07001635 // Update the saved icons if necessary
1636 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001637 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001638 for (Object key : sBgDbIconCache.keySet()) {
1639 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1640 }
1641 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001642 }
Winson Chungaac01e12011-08-17 10:37:13 -07001643
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001644 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001645 // Ensure that all the applications that are in the system are
1646 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001647 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001648 verifyApplications();
1649 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001650 }
1651
Joe Onorato36115782010-06-17 13:28:48 -04001652 // Clear out this reference, otherwise we end up holding it until all of the
1653 // callback runnables are done.
1654 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001655
Joe Onorato36115782010-06-17 13:28:48 -04001656 synchronized (mLock) {
1657 // If we are still the last one to be scheduled, remove ourselves.
1658 if (mLoaderTask == this) {
1659 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001660 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001661 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663 }
1664
1665 public void stopLocked() {
1666 synchronized (LoaderTask.this) {
1667 mStopped = true;
1668 this.notify();
1669 }
1670 }
1671
1672 /**
1673 * Gets the callbacks object. If we've been stopped, or if the launcher object
1674 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1675 * object that was around when the deferred message was scheduled, and if there's
1676 * a new Callbacks object around then also return null. This will save us from
1677 * calling onto it with data that will be ignored.
1678 */
1679 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1680 synchronized (mLock) {
1681 if (mStopped) {
1682 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001683 }
Joe Onorato36115782010-06-17 13:28:48 -04001684
1685 if (mCallbacks == null) {
1686 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001687 }
Joe Onorato36115782010-06-17 13:28:48 -04001688
1689 final Callbacks callbacks = mCallbacks.get();
1690 if (callbacks != oldCallbacks) {
1691 return null;
1692 }
1693 if (callbacks == null) {
1694 Log.w(TAG, "no mCallbacks");
1695 return null;
1696 }
1697
1698 return callbacks;
1699 }
1700 }
1701
Winson Chungc763c4e2013-07-19 13:49:06 -07001702 private void verifyApplications() {
1703 final Context context = mApp.getContext();
1704
1705 // Cross reference all the applications in our apps list with items in the workspace
1706 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001707 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001708 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001709 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001710 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001711 if (tmpInfos.isEmpty()) {
1712 // We are missing an application icon, so add this to the workspace
1713 added.add(app);
1714 // This is a rare event, so lets log it
1715 Log.e(TAG, "Missing Application on load: " + app);
1716 }
1717 }
1718 }
1719 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001720 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001721 }
1722 }
1723
Joe Onorato36115782010-06-17 13:28:48 -04001724 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001725 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001726 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001727 LauncherAppState app = LauncherAppState.getInstance();
1728 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001729 final int countX = (int) grid.numColumns;
1730 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001731
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001733 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001734 // Return early if we detect that an item is under the hotseat button
1735 if (mCallbacks == null ||
1736 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001737 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001738 Log.e(TAG, "Error loading shortcut into hotseat " + item
1739 + " into position (" + item.screenId + ":" + item.cellX + ","
1740 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001741 return false;
1742 }
1743
Dan Sandler295ae182013-12-10 16:05:47 -05001744 final ItemInfo[][] hotseatItems =
1745 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1746
Adam Cohenae4409d2013-11-26 10:34:59 -08001747 if (item.screenId >= grid.numHotseatIcons) {
1748 Log.e(TAG, "Error loading shortcut " + item
1749 + " into hotseat position " + item.screenId
1750 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1751 + ")");
1752 return false;
1753 }
1754
Dan Sandler295ae182013-12-10 16:05:47 -05001755 if (hotseatItems != null) {
1756 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001757 Log.e(TAG, "Error loading shortcut into hotseat " + item
1758 + " into position (" + item.screenId + ":" + item.cellX + ","
1759 + item.cellY + ") occupied by "
1760 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1761 [(int) item.screenId][0]);
1762 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001763 } else {
1764 hotseatItems[(int) item.screenId][0] = item;
1765 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001767 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001768 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001769 items[(int) item.screenId][0] = item;
1770 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001771 return true;
1772 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001773 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1774 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001775 return true;
1776 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001777
Adam Cohendcd297f2013-06-18 13:13:40 -07001778 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001779 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001780 occupied.put(item.screenId, items);
1781 }
1782
Dan Sandler295ae182013-12-10 16:05:47 -05001783 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001784 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1785 item.cellX < 0 || item.cellY < 0 ||
1786 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1787 Log.e(TAG, "Error loading shortcut " + item
1788 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1789 + item.cellX + "," + item.cellY
1790 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1791 return false;
1792 }
1793
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001794 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001795 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1796 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001797 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001798 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001800 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001801 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001802 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001803 return false;
1804 }
1805 }
1806 }
1807 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1808 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001810 }
1811 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001812
Joe Onorato36115782010-06-17 13:28:48 -04001813 return true;
1814 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001815
Winson Chungba9c37f2013-08-30 14:11:37 -07001816 /** Clears all the sBg data structures */
1817 private void clearSBgDataStructures() {
1818 synchronized (sBgLock) {
1819 sBgWorkspaceItems.clear();
1820 sBgAppWidgets.clear();
1821 sBgFolders.clear();
1822 sBgItemsIdMap.clear();
1823 sBgDbIconCache.clear();
1824 sBgWorkspaceScreens.clear();
1825 }
1826 }
1827
Dan Sandlerd5024042014-01-09 15:01:33 -05001828 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001829 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001830 // Log to disk
1831 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1832
Joe Onorato36115782010-06-17 13:28:48 -04001833 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001834
Joe Onorato36115782010-06-17 13:28:48 -04001835 final Context context = mContext;
1836 final ContentResolver contentResolver = context.getContentResolver();
1837 final PackageManager manager = context.getPackageManager();
1838 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1839 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001840 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1841 final boolean isSdCardReady = context.registerReceiver(null,
1842 new IntentFilter(StartupReceiver.SYESTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001843
Winson Chung892c74d2013-08-22 16:15:50 -07001844 LauncherAppState app = LauncherAppState.getInstance();
1845 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1846 int countX = (int) grid.numColumns;
1847 int countY = (int) grid.numRows;
1848
Dan Sandlerd5024042014-01-09 15:01:33 -05001849 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1850 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1851 LauncherAppState.getLauncherProvider().deleteDatabase();
1852 }
1853
1854 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1855 // append the user's Launcher2 shortcuts
1856 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1857 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1858 } else {
1859 // Make sure the default workspace is loaded
1860 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1861 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1862 }
Adam Cohene25af792013-06-06 23:08:25 -07001863
Adam Cohen71483f42014-05-15 14:04:01 -07001864 // This code path is for our old migration code and should no longer be exercised
1865 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001866
Winson Chung9f9f00b2013-11-15 13:27:00 -08001867 // Log to disk
1868 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001869
Winson Chung2abf94d2012-07-18 18:16:38 -07001870 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001871 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001872
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001873 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001874 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001875 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001876 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001877 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001878
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001879 // +1 for the hotseat (it can be larger than the workspace)
1880 // Load workspace in reverse order to ensure that latest items are loaded first (and
1881 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001882 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 try {
1885 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1886 final int intentIndex = c.getColumnIndexOrThrow
1887 (LauncherSettings.Favorites.INTENT);
1888 final int titleIndex = c.getColumnIndexOrThrow
1889 (LauncherSettings.Favorites.TITLE);
1890 final int iconTypeIndex = c.getColumnIndexOrThrow(
1891 LauncherSettings.Favorites.ICON_TYPE);
1892 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1893 final int iconPackageIndex = c.getColumnIndexOrThrow(
1894 LauncherSettings.Favorites.ICON_PACKAGE);
1895 final int iconResourceIndex = c.getColumnIndexOrThrow(
1896 LauncherSettings.Favorites.ICON_RESOURCE);
1897 final int containerIndex = c.getColumnIndexOrThrow(
1898 LauncherSettings.Favorites.CONTAINER);
1899 final int itemTypeIndex = c.getColumnIndexOrThrow(
1900 LauncherSettings.Favorites.ITEM_TYPE);
1901 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1902 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001903 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 final int screenIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.SCREEN);
1907 final int cellXIndex = c.getColumnIndexOrThrow
1908 (LauncherSettings.Favorites.CELLX);
1909 final int cellYIndex = c.getColumnIndexOrThrow
1910 (LauncherSettings.Favorites.CELLY);
1911 final int spanXIndex = c.getColumnIndexOrThrow
1912 (LauncherSettings.Favorites.SPANX);
1913 final int spanYIndex = c.getColumnIndexOrThrow(
1914 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001915 final int restoredIndex = c.getColumnIndexOrThrow(
1916 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001917 final int profileIdIndex = c.getColumnIndexOrThrow(
1918 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001919 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1920 //final int displayModeIndex = c.getColumnIndexOrThrow(
1921 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001922
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001923 ShortcutInfo info;
1924 String intentDescription;
1925 LauncherAppWidgetInfo appWidgetInfo;
1926 int container;
1927 long id;
1928 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001929 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001930
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001931 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001932 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001933 try {
1934 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001935 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001936 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001937
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001938 switch (itemType) {
1939 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1940 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001941 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001942 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001943 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001944 user = mUserManager.getUserForSerialNumber(serialNumber);
1945 if (user == null) {
1946 // User has been deleted remove the item.
1947 itemsToRemove.add(id);
1948 continue;
1949 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 try {
1951 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001952 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001953 if (cn != null && cn.getPackageName() != null) {
1954 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1955 cn.getPackageName(), user);
1956 boolean validComponent = validPkg &&
1957 launcherApps.isActivityEnabledForProfile(cn, user);
1958
1959 if (validComponent) {
1960 if (restored) {
1961 // no special handling necessary for this item
1962 restoredRows.add(id);
1963 restored = false;
1964 }
1965 } else if (validPkg) {
1966 // The app is installed but the component is no
1967 // longer available.
1968 Launcher.addDumpLog(TAG,
1969 "Invalid component removed: " + cn, true);
1970 itemsToRemove.add(id);
1971 continue;
1972 } else if (restored) {
1973 // Package is not yet available but might be
1974 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001975 Launcher.addDumpLog(TAG,
1976 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001977 } else if (isSdCardReady) {
1978 // Do not wait for external media load anymore.
1979 // Log the invalid package, and remove it
1980 Launcher.addDumpLog(TAG,
1981 "Invalid package removed: " + cn, true);
1982 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05001983 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001984 } else {
1985 // SdCard is not ready yet. Package might get available,
1986 // once it is ready.
1987 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1988 + " (check again later)", true);
1989 HashSet<String> pkgs = sPendingPackages.get(user);
1990 if (pkgs == null) {
1991 pkgs = new HashSet<>();
1992 sPendingPackages.put(user, pkgs);
1993 }
1994 pkgs.add(cn.getPackageName());
1995 allowMissingTarget = true;
1996 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07001997 }
Winson Chungee055712013-07-30 14:46:24 -07001998 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001999 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002000 Launcher.addDumpLog(TAG,
2001 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002002 continue;
2003 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002004
Chris Wrenf4d08112014-01-16 18:13:56 -05002005 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002006 if (user.equals(UserHandleCompat.myUserHandle())) {
2007 Launcher.addDumpLog(TAG,
2008 "constructing info for partially restored package",
2009 true);
2010 info = getRestoredItemInfo(c, titleIndex, intent);
2011 intent = getRestoredItemIntent(c, context, intent);
2012 } else {
2013 // Don't restore items for other profiles.
2014 itemsToRemove.add(id);
2015 continue;
2016 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002017 } else if (itemType ==
2018 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002019 info = getShortcutInfo(manager, intent, user, context, c,
2020 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002021 } else {
2022 info = getShortcutInfo(c, context, iconTypeIndex,
2023 iconPackageIndex, iconResourceIndex, iconIndex,
2024 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002025
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002026 // App shortcuts that used to be automatically added to Launcher
2027 // didn't always have the correct intent flags set, so do that
2028 // here
2029 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002030 intent.getCategories() != null &&
2031 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002032 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002033 intent.addFlags(
2034 Intent.FLAG_ACTIVITY_NEW_TASK |
2035 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2036 }
Michael Jurka96879562012-03-22 05:54:33 -07002037 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002038
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002039 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002040 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002041 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 container = c.getInt(containerIndex);
2043 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002045 info.cellX = c.getInt(cellXIndex);
2046 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002047 info.spanX = 1;
2048 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002049 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Adam Cohenae4409d2013-11-26 10:34:59 -08002050
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002051 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002052 deleteOnInvalidPlacement.set(false);
2053 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2054 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002055 itemsToRemove.add(id);
2056 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 break;
2058 }
2059
2060 switch (container) {
2061 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2062 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2063 sBgWorkspaceItems.add(info);
2064 break;
2065 default:
2066 // Item is in a user folder
2067 FolderInfo folderInfo =
2068 findOrMakeFolder(sBgFolders, container);
2069 folderInfo.add(info);
2070 break;
2071 }
2072 sBgItemsIdMap.put(info.id, info);
2073
2074 // now that we've loaded everthing re-save it with the
2075 // icon in case it disappears somehow.
2076 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002077 } else {
2078 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 }
2080 break;
2081
2082 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2083 id = c.getLong(idIndex);
2084 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2085
2086 folderInfo.title = c.getString(titleIndex);
2087 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002088 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002090 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 folderInfo.cellX = c.getInt(cellXIndex);
2092 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002093 folderInfo.spanX = 1;
2094 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002095
Daniel Sandler8802e962010-05-26 16:28:16 -04002096 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002097 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002098 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002099 deleteOnInvalidPlacement)) {
2100 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002101 itemsToRemove.add(id);
2102 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002103 break;
2104 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002105
Joe Onorato9c1289c2009-08-17 11:03:03 -04002106 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002107 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2108 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2109 sBgWorkspaceItems.add(folderInfo);
2110 break;
Joe Onorato36115782010-06-17 13:28:48 -04002111 }
Joe Onorato17a89222011-02-08 17:26:11 -08002112
Chris Wrenf4d08112014-01-16 18:13:56 -05002113 if (restored) {
2114 // no special handling required for restored folders
2115 restoredRows.add(id);
2116 }
2117
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2119 sBgFolders.put(folderInfo.id, folderInfo);
2120 break;
2121
2122 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2123 // Read all Launcher-specific widget details
2124 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002125 String savedProvider = c.getString(appWidgetProviderIndex);
2126
Joe Onorato36115782010-06-17 13:28:48 -04002127 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002128
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 final AppWidgetProviderInfo provider =
2130 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04002131
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002132 if (!isSafeMode && (provider == null || provider.provider == null ||
2133 provider.provider.getPackageName() == null)) {
2134 String log = "Deleting widget that isn't installed anymore: id="
2135 + id + " appWidgetId=" + appWidgetId;
2136 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002137 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002138 itemsToRemove.add(id);
2139 } else {
2140 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2141 provider.provider);
2142 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002143 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 appWidgetInfo.cellX = c.getInt(cellXIndex);
2145 appWidgetInfo.cellY = c.getInt(cellYIndex);
2146 appWidgetInfo.spanX = c.getInt(spanXIndex);
2147 appWidgetInfo.spanY = c.getInt(spanYIndex);
2148 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2149 appWidgetInfo.minSpanX = minSpan[0];
2150 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04002151
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002152 container = c.getInt(containerIndex);
2153 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2154 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2155 Log.e(TAG, "Widget found where container != " +
2156 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2157 continue;
2158 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002159
Adam Cohene25af792013-06-06 23:08:25 -07002160 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002161 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002162 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002163 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002164 deleteOnInvalidPlacement)) {
2165 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002166 itemsToRemove.add(id);
2167 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002168 break;
2169 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002170 String providerName = provider.provider.flattenToString();
2171 if (!providerName.equals(savedProvider)) {
2172 ContentValues values = new ContentValues();
2173 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2174 providerName);
2175 String where = BaseColumns._ID + "= ?";
2176 String[] args = {Integer.toString(c.getInt(idIndex))};
2177 contentResolver.update(contentUri, values, where, args);
2178 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2180 sBgAppWidgets.add(appWidgetInfo);
2181 }
Joe Onorato36115782010-06-17 13:28:48 -04002182 break;
2183 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002185 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002186 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 }
2188 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002189 if (c != null) {
2190 c.close();
2191 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002192 }
2193
Winson Chungba9c37f2013-08-30 14:11:37 -07002194 // Break early if we've stopped loading
2195 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002196 clearSBgDataStructures();
2197 return false;
2198 }
2199
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002200 if (itemsToRemove.size() > 0) {
2201 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002202 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002203 // Remove dead items
2204 for (long id : itemsToRemove) {
2205 if (DEBUG_LOADERS) {
2206 Log.d(TAG, "Removed id = " + id);
2207 }
2208 // Don't notify content observers
2209 try {
2210 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2211 null, null);
2212 } catch (RemoteException e) {
2213 Log.w(TAG, "Could not remove id = " + id);
2214 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002215 }
2216 }
2217
Chris Wrenf4d08112014-01-16 18:13:56 -05002218 if (restoredRows.size() > 0) {
2219 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2220 LauncherSettings.Favorites.CONTENT_URI);
2221 // Update restored items that no longer require special handling
2222 try {
2223 StringBuilder selectionBuilder = new StringBuilder();
2224 selectionBuilder.append(LauncherSettings.Favorites._ID);
2225 selectionBuilder.append(" IN (");
2226 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2227 selectionBuilder.append(")");
2228 ContentValues values = new ContentValues();
2229 values.put(LauncherSettings.Favorites.RESTORED, 0);
2230 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2231 values, selectionBuilder.toString(), null);
2232 } catch (RemoteException e) {
2233 Log.w(TAG, "Could not update restored rows");
2234 }
2235 }
2236
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002237 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2238 context.registerReceiver(new AppsAvailabilityCheck(),
2239 new IntentFilter(StartupReceiver.SYESTEM_READY),
2240 null, sWorker);
2241 }
2242
Winson Chungc763c4e2013-07-19 13:49:06 -07002243 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002244 long maxScreenId = 0;
2245 // If we're importing we use the old screen order.
2246 for (ItemInfo item: sBgItemsIdMap.values()) {
2247 long screenId = item.screenId;
2248 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2249 !sBgWorkspaceScreens.contains(screenId)) {
2250 sBgWorkspaceScreens.add(screenId);
2251 if (screenId > maxScreenId) {
2252 maxScreenId = screenId;
2253 }
2254 }
2255 }
2256 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002257 // Log to disk
2258 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2259 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2260 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002261
Michael Jurka414300a2013-08-27 15:42:35 +02002262 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002263 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002264
2265 // Update the max item id after we load an old db
2266 long maxItemId = 0;
2267 // If we're importing we use the old screen order.
2268 for (ItemInfo item: sBgItemsIdMap.values()) {
2269 maxItemId = Math.max(maxItemId, item.id);
2270 }
Michael Jurka414300a2013-08-27 15:42:35 +02002271 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002272 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002273 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2274 for (Integer i : orderedScreens.keySet()) {
2275 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002276 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002277 // Log to disk
2278 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2279 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002280
2281 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002282 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002283 for (ItemInfo item: sBgItemsIdMap.values()) {
2284 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002285 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2286 unusedScreens.contains(screenId)) {
2287 unusedScreens.remove(screenId);
2288 }
2289 }
2290
2291 // If there are any empty screens remove them, and update.
2292 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002293 // Log to disk
2294 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2295 TextUtils.join(", ", unusedScreens), true);
2296
Winson Chung933bae62013-08-29 11:42:30 -07002297 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002298 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2299 }
2300 }
2301
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002302 if (DEBUG_LOADERS) {
2303 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2304 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002305 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002306 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002307 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002308
Daniel Sandler566da102013-06-25 23:43:45 -04002309 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002310 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002311 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002312 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002313 line += " | ";
2314 }
Winson Chung892c74d2013-08-22 16:15:50 -07002315 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002316 ItemInfo[][] screen = occupied.get(screenId);
2317 if (x < screen.length && y < screen[x].length) {
2318 line += (screen[x][y] != null) ? "#" : ".";
2319 } else {
2320 line += "!";
2321 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002322 }
Joe Onorato36115782010-06-17 13:28:48 -04002323 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002324 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002325 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002326 }
Joe Onorato36115782010-06-17 13:28:48 -04002327 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002328 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002329 }
2330
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002331 /** Filters the set of items who are directly or indirectly (via another container) on the
2332 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002333 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002334 ArrayList<ItemInfo> allWorkspaceItems,
2335 ArrayList<ItemInfo> currentScreenItems,
2336 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002337 // Purge any null ItemInfos
2338 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2339 while (iter.hasNext()) {
2340 ItemInfo i = iter.next();
2341 if (i == null) {
2342 iter.remove();
2343 }
2344 }
2345
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002346 // Order the set of items by their containers first, this allows use to walk through the
2347 // list sequentially, build up a list of containers that are in the specified screen,
2348 // as well as all items in those containers.
2349 Set<Long> itemsOnScreen = new HashSet<Long>();
2350 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2351 @Override
2352 public int compare(ItemInfo lhs, ItemInfo rhs) {
2353 return (int) (lhs.container - rhs.container);
2354 }
2355 });
2356 for (ItemInfo info : allWorkspaceItems) {
2357 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002358 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002359 currentScreenItems.add(info);
2360 itemsOnScreen.add(info.id);
2361 } else {
2362 otherScreenItems.add(info);
2363 }
2364 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2365 currentScreenItems.add(info);
2366 itemsOnScreen.add(info.id);
2367 } else {
2368 if (itemsOnScreen.contains(info.container)) {
2369 currentScreenItems.add(info);
2370 itemsOnScreen.add(info.id);
2371 } else {
2372 otherScreenItems.add(info);
2373 }
2374 }
2375 }
2376 }
2377
2378 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002379 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002380 ArrayList<LauncherAppWidgetInfo> appWidgets,
2381 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2382 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002383
2384 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002385 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002386 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002387 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002388 currentScreenWidgets.add(widget);
2389 } else {
2390 otherScreenWidgets.add(widget);
2391 }
2392 }
2393 }
2394
2395 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002396 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002397 HashMap<Long, ItemInfo> itemsIdMap,
2398 HashMap<Long, FolderInfo> folders,
2399 HashMap<Long, FolderInfo> currentScreenFolders,
2400 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002401
2402 for (long id : folders.keySet()) {
2403 ItemInfo info = itemsIdMap.get(id);
2404 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002405 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002406 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002407 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002408 currentScreenFolders.put(id, folder);
2409 } else {
2410 otherScreenFolders.put(id, folder);
2411 }
2412 }
2413 }
2414
2415 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2416 * right) */
2417 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002418 final LauncherAppState app = LauncherAppState.getInstance();
2419 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002420 // XXX: review this
2421 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002422 @Override
2423 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002424 int cellCountX = (int) grid.numColumns;
2425 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002426 int screenOffset = cellCountX * cellCountY;
2427 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002428 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002429 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002430 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002431 rhs.cellY * cellCountX + rhs.cellX);
2432 return (int) (lr - rr);
2433 }
2434 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002436
Adam Cohendcd297f2013-06-18 13:13:40 -07002437 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2438 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002439 final Runnable r = new Runnable() {
2440 @Override
2441 public void run() {
2442 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2443 if (callbacks != null) {
2444 callbacks.bindScreens(orderedScreens);
2445 }
2446 }
2447 };
2448 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2449 }
2450
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2452 final ArrayList<ItemInfo> workspaceItems,
2453 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2454 final HashMap<Long, FolderInfo> folders,
2455 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002456
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 final boolean postOnMainThread = (deferredBindRunnables != null);
2458
2459 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002460 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002462 final int start = i;
2463 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002464 final Runnable r = new Runnable() {
2465 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002466 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002467 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002468 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002469 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2470 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002471 }
2472 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473 };
2474 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002475 synchronized (deferredBindRunnables) {
2476 deferredBindRunnables.add(r);
2477 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002478 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002479 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 }
Joe Onorato36115782010-06-17 13:28:48 -04002481 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002482
2483 // Bind the folders
2484 if (!folders.isEmpty()) {
2485 final Runnable r = new Runnable() {
2486 public void run() {
2487 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2488 if (callbacks != null) {
2489 callbacks.bindFolders(folders);
2490 }
2491 }
2492 };
2493 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002494 synchronized (deferredBindRunnables) {
2495 deferredBindRunnables.add(r);
2496 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002497 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002498 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002499 }
2500 }
2501
2502 // Bind the widgets, one at a time
2503 N = appWidgets.size();
2504 for (int i = 0; i < N; i++) {
2505 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2506 final Runnable r = new Runnable() {
2507 public void run() {
2508 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2509 if (callbacks != null) {
2510 callbacks.bindAppWidget(widget);
2511 }
2512 }
2513 };
2514 if (postOnMainThread) {
2515 deferredBindRunnables.add(r);
2516 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002517 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002518 }
2519 }
2520 }
2521
2522 /**
2523 * Binds all loaded data to actual views on the main thread.
2524 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002525 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526 final long t = SystemClock.uptimeMillis();
2527 Runnable r;
2528
2529 // Don't use these two variables in any of the callback runnables.
2530 // Otherwise we hold a reference to them.
2531 final Callbacks oldCallbacks = mCallbacks.get();
2532 if (oldCallbacks == null) {
2533 // This launcher has exited and nobody bothered to tell us. Just bail.
2534 Log.w(TAG, "LoaderTask running with no launcher");
2535 return;
2536 }
2537
Winson Chung9b9fb962013-11-15 15:39:34 -08002538 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2540 ArrayList<LauncherAppWidgetInfo> appWidgets =
2541 new ArrayList<LauncherAppWidgetInfo>();
2542 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2543 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002544 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002545 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002546 workspaceItems.addAll(sBgWorkspaceItems);
2547 appWidgets.addAll(sBgAppWidgets);
2548 folders.putAll(sBgFolders);
2549 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002550 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002551 }
2552
Derek Prothro7aff3992013-12-10 14:00:37 -05002553 final boolean isLoadingSynchronously =
2554 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002555 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002556 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002557 if (currScreen >= orderedScreenIds.size()) {
2558 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002559 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002560 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002561 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002562 final long currentScreenId = currentScreen < 0
2563 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002564
2565 // Load all the items that are on the current page first (and in the process, unbind
2566 // all the existing workspace items before we call startBinding() below.
2567 unbindWorkspaceItemsOnMainThread();
2568
2569 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2571 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2572 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2573 new ArrayList<LauncherAppWidgetInfo>();
2574 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2575 new ArrayList<LauncherAppWidgetInfo>();
2576 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2577 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2578
Winson Chung9b9fb962013-11-15 15:39:34 -08002579 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002580 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002581 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002582 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002583 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584 otherFolders);
2585 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2586 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2587
2588 // Tell the workspace that we're about to start binding items
2589 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002590 public void run() {
2591 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2592 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002593 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002594 }
2595 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002596 };
Winson Chung81b52252012-08-27 15:34:29 -07002597 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598
Adam Cohendcd297f2013-06-18 13:13:40 -07002599 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2600
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 // Load items on the current page
2602 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2603 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002604 if (isLoadingSynchronously) {
2605 r = new Runnable() {
2606 public void run() {
2607 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002608 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002609 callbacks.onPageBoundSynchronously(currentScreen);
2610 }
2611 }
2612 };
Winson Chung81b52252012-08-27 15:34:29 -07002613 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002614 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615
Winson Chung4a2afa32012-07-19 14:53:05 -07002616 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2617 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002618 synchronized (mDeferredBindRunnables) {
2619 mDeferredBindRunnables.clear();
2620 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002621 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002622 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002623
2624 // Tell the workspace that we're done binding items
2625 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002626 public void run() {
2627 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2628 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002629 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002630 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002631
Winson Chung98e030b2012-05-07 16:01:11 -07002632 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002633 if (DEBUG_LOADERS) {
2634 Log.d(TAG, "bound workspace in "
2635 + (SystemClock.uptimeMillis()-t) + "ms");
2636 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002637
2638 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002639 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002641 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002642 synchronized (mDeferredBindRunnables) {
2643 mDeferredBindRunnables.add(r);
2644 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002645 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002646 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002647 }
Joe Onorato36115782010-06-17 13:28:48 -04002648 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002649
Joe Onorato36115782010-06-17 13:28:48 -04002650 private void loadAndBindAllApps() {
2651 if (DEBUG_LOADERS) {
2652 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2653 }
2654 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002655 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002656 synchronized (LoaderTask.this) {
2657 if (mStopped) {
2658 return;
2659 }
2660 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002661 }
Joe Onorato36115782010-06-17 13:28:48 -04002662 } else {
2663 onlyBindAllApps();
2664 }
2665 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002666
Joe Onorato36115782010-06-17 13:28:48 -04002667 private void onlyBindAllApps() {
2668 final Callbacks oldCallbacks = mCallbacks.get();
2669 if (oldCallbacks == null) {
2670 // This launcher has exited and nobody bothered to tell us. Just bail.
2671 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2672 return;
2673 }
2674
2675 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002676 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002677 final ArrayList<AppInfo> list
2678 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002679 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002680 public void run() {
2681 final long t = SystemClock.uptimeMillis();
2682 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2683 if (callbacks != null) {
2684 callbacks.bindAllApplications(list);
2685 }
2686 if (DEBUG_LOADERS) {
2687 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2688 + (SystemClock.uptimeMillis()-t) + "ms");
2689 }
2690 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002691 };
2692 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002693 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002694 r.run();
2695 } else {
2696 mHandler.post(r);
2697 }
Joe Onorato36115782010-06-17 13:28:48 -04002698 }
2699
Winson Chung64359a52013-07-08 17:17:08 -07002700 private void loadAllApps() {
2701 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002702
Joe Onorato36115782010-06-17 13:28:48 -04002703 final Callbacks oldCallbacks = mCallbacks.get();
2704 if (oldCallbacks == null) {
2705 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002706 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002707 return;
2708 }
2709
2710 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2711 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2712
Kenny Guyed131872014-04-30 03:02:21 +01002713 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2714
Winson Chung64359a52013-07-08 17:17:08 -07002715 // Clear the list of apps
2716 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002717 for (UserHandleCompat user : profiles) {
2718 // Query for the set of apps
2719 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2720 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2721 if (DEBUG_LOADERS) {
2722 Log.d(TAG, "getActivityList took "
2723 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2724 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2725 }
2726 // Fail if we don't have any apps
2727 if (apps == null || apps.isEmpty()) {
2728 return;
2729 }
2730 // Sort the applications by name
2731 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2732 Collections.sort(apps,
2733 new LauncherModel.ShortcutNameComparator(mLabelCache));
2734 if (DEBUG_LOADERS) {
2735 Log.d(TAG, "sort took "
2736 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2737 }
Joe Onorato36115782010-06-17 13:28:48 -04002738
Kenny Guyed131872014-04-30 03:02:21 +01002739 // Create the ApplicationInfos
2740 for (int i = 0; i < apps.size(); i++) {
2741 LauncherActivityInfoCompat app = apps.get(i);
2742 // This builds the icon bitmaps.
2743 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2744 }
Winson Chung64359a52013-07-08 17:17:08 -07002745 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002746 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002747 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2748 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002749
2750 // Post callback on main thread
2751 mHandler.post(new Runnable() {
2752 public void run() {
2753 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002754 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002755 if (callbacks != null) {
2756 callbacks.bindAllApplications(added);
2757 if (DEBUG_LOADERS) {
2758 Log.d(TAG, "bound " + added.size() + " apps in "
2759 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2760 }
2761 } else {
2762 Log.i(TAG, "not binding apps: no Launcher activity");
2763 }
2764 }
2765 });
2766
Joe Onorato36115782010-06-17 13:28:48 -04002767 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002768 Log.d(TAG, "Icons processed in "
2769 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002770 }
2771 }
2772
2773 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002774 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002775 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2776 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2777 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2778 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2779 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2780 }
Joe Onorato36115782010-06-17 13:28:48 -04002781 }
2782 }
2783
2784 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002785 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002786 }
2787
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002788 private class AppsAvailabilityCheck extends BroadcastReceiver {
2789
2790 @Override
2791 public void onReceive(Context context, Intent intent) {
2792 synchronized (sBgLock) {
2793 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2794 .getInstance(mApp.getContext());
2795 ArrayList<String> packagesRemoved;
2796 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2797 UserHandleCompat user = entry.getKey();
2798 packagesRemoved = new ArrayList<>();
2799 for (String pkg : entry.getValue()) {
2800 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2801 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2802 packagesRemoved.add(pkg);
2803 }
2804 }
2805 if (!packagesRemoved.isEmpty()) {
2806 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2807 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2808 }
2809 }
2810 sPendingPackages.clear();
2811 }
2812 }
2813 }
2814
Joe Onorato36115782010-06-17 13:28:48 -04002815 private class PackageUpdatedTask implements Runnable {
2816 int mOp;
2817 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002818 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002819
2820 public static final int OP_NONE = 0;
2821 public static final int OP_ADD = 1;
2822 public static final int OP_UPDATE = 2;
2823 public static final int OP_REMOVE = 3; // uninstlled
2824 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2825
2826
Kenny Guyed131872014-04-30 03:02:21 +01002827 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002828 mOp = op;
2829 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002830 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002831 }
2832
2833 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002834 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002835
2836 final String[] packages = mPackages;
2837 final int N = packages.length;
2838 switch (mOp) {
2839 case OP_ADD:
2840 for (int i=0; i<N; i++) {
2841 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002842 mIconCache.remove(packages[i], mUser);
2843 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002844 }
2845 break;
2846 case OP_UPDATE:
2847 for (int i=0; i<N; i++) {
2848 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002849 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002850 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002851 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002852 }
2853 break;
2854 case OP_REMOVE:
2855 case OP_UNAVAILABLE:
2856 for (int i=0; i<N; i++) {
2857 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002858 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002859 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002860 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002861 }
2862 break;
2863 }
2864
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002865 ArrayList<AppInfo> added = null;
2866 ArrayList<AppInfo> modified = null;
2867 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002868
Adam Cohen487f7dd2012-06-28 18:12:10 -07002869 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002870 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002871 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002872 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002873 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002874 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002875 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002876 }
Winson Chung5d55f332012-07-16 20:45:03 -07002877 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002878 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002879 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002880 }
2881
Joe Onorato36115782010-06-17 13:28:48 -04002882 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2883 if (callbacks == null) {
2884 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2885 return;
2886 }
2887
2888 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002889 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002890 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002891 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002892 addAndBindAddedWorkspaceApps(context, addedInfos);
2893 } else {
2894 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002895 }
Joe Onorato36115782010-06-17 13:28:48 -04002896 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002897
Joe Onorato36115782010-06-17 13:28:48 -04002898 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002899 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002900
2901 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002902 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002903 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002904 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002905 for (ItemInfo i : infos) {
2906 if (isShortcutInfoUpdateable(i)) {
2907 ShortcutInfo info = (ShortcutInfo) i;
2908 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002909 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002910 updateItemInDatabase(context, info);
2911 }
2912 }
2913 }
2914
Joe Onorato36115782010-06-17 13:28:48 -04002915 mHandler.post(new Runnable() {
2916 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002917 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2918 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002919 callbacks.bindAppsUpdated(modifiedFinal);
2920 }
2921 }
2922 });
2923 }
Winson Chung83892cc2013-05-01 16:53:33 -07002924
Winson Chungdf95eb12013-10-16 14:57:07 -07002925 final ArrayList<String> removedPackageNames =
2926 new ArrayList<String>();
2927 if (mOp == OP_REMOVE) {
2928 // Mark all packages in the broadcast to be removed
2929 removedPackageNames.addAll(Arrays.asList(packages));
2930 } else if (mOp == OP_UPDATE) {
2931 // Mark disabled packages in the broadcast to be removed
2932 final PackageManager pm = context.getPackageManager();
2933 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002934 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002935 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002936 }
2937 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002938 }
2939 // Remove all the components associated with this package
2940 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002941 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002942 for (ItemInfo i : infos) {
2943 deleteItemFromDatabase(context, i);
2944 }
2945 }
2946 // Remove all the specific components
2947 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002948 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002949 for (ItemInfo i : infos) {
2950 deleteItemFromDatabase(context, i);
2951 }
2952 }
2953 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2954 // Remove any queued items from the install queue
2955 String spKey = LauncherAppState.getSharedPreferencesKey();
2956 SharedPreferences sp =
2957 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2958 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2959 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002960 mHandler.post(new Runnable() {
2961 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002962 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2963 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01002964 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002965 }
2966 }
2967 });
Joe Onoratobe386092009-11-17 17:32:16 -08002968 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002969
Michael Jurkac402cd92013-05-20 15:49:32 +02002970 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01002971 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002972 mHandler.post(new Runnable() {
2973 @Override
2974 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002975 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2976 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002977 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002978 }
2979 }
2980 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002981
2982 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002983 mHandler.post(new Runnable() {
2984 public void run() {
2985 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2986 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002987 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002988 }
2989 }
2990 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002991 }
2992 }
2993
Michael Jurkac402cd92013-05-20 15:49:32 +02002994 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2995 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2996 PackageManager packageManager = context.getPackageManager();
2997 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2998 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2999 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3000 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
3001 Collections.sort(widgetsAndShortcuts,
3002 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
3003 return widgetsAndShortcuts;
3004 }
3005
Kenny Guyed131872014-04-30 03:02:21 +01003006 private static boolean isPackageDisabled(Context context, String packageName,
3007 UserHandleCompat user) {
3008 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3009 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003010 }
Adam Cohen556f6132014-01-15 15:18:08 -08003011
Kenny Guyed131872014-04-30 03:02:21 +01003012 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3013 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003014 if (cn == null) {
3015 return false;
3016 }
Kenny Guyed131872014-04-30 03:02:21 +01003017 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3018 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003019 return false;
3020 }
Kenny Guyed131872014-04-30 03:02:21 +01003021 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003022 }
3023
Adam Cohena28b78e2014-05-20 17:03:04 -07003024 public static boolean isValidPackage(Context context, String packageName,
3025 UserHandleCompat user) {
3026 if (packageName == null) {
3027 return false;
3028 }
3029 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3030 return launcherApps.isPackageEnabledForProfile(packageName, user);
3031 }
3032
Joe Onorato9c1289c2009-08-17 11:03:03 -04003033 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003034 * Make an ShortcutInfo object for a restored application or shortcut item that points
3035 * to a package that is not yet installed on the system.
3036 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003037 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003038 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003039 if (cursor != null) {
3040 info.title = cursor.getString(titleIndex);
3041 } else {
3042 info.title = "";
3043 }
Kenny Guyed131872014-04-30 03:02:21 +01003044 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003045 info.contentDescription = mUserManager.getBadgedLabelForUser(
3046 info.title.toString(), info.user);
Kenny Guyed131872014-04-30 03:02:21 +01003047 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user));
Chris Wrenf4d08112014-01-16 18:13:56 -05003048 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003049 info.restoredIntent = intent;
Chris Wren40c5ed32014-06-24 18:24:23 -04003050 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003051 return info;
3052 }
3053
3054 /**
3055 * Make an Intent object for a restored application or shortcut item that points
3056 * to the market page for the item.
3057 */
3058 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003059 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05003060 ComponentName componentName = intent.getComponent();
3061 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
3062 Uri marketUri = new Uri.Builder()
3063 .scheme("market")
3064 .authority("details")
3065 .appendQueryParameter("id", componentName.getPackageName())
3066 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05003067 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05003068 marketIntent.setData(marketUri);
3069 return marketIntent;
3070 }
3071
3072 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003073 * This is called from the code that adds shortcuts from the intent receiver. This
3074 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003075 */
Kenny Guyed131872014-04-30 03:02:21 +01003076 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3077 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003078 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003079 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003080
Joe Onorato56d82912010-03-07 14:32:10 -05003081 /**
3082 * Make an ShortcutInfo object for a shortcut that is an application.
3083 *
3084 * If c is not null, then it will be used to fill in missing data like the title and icon.
3085 */
Kenny Guyed131872014-04-30 03:02:21 +01003086 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3087 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003088 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003089 if (user == null) {
3090 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003091 return null;
3092 }
3093
Kenny Guyed131872014-04-30 03:02:21 +01003094 ComponentName componentName = intent.getComponent();
3095 if (componentName == null) {
3096 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3097 return null;
3098 }
3099
3100 Intent newIntent = new Intent(intent.getAction(), null);
3101 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3102 newIntent.setComponent(componentName);
3103 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003104 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003105 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3106 return null;
3107 }
3108
3109 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003110
Joe Onorato56d82912010-03-07 14:32:10 -05003111 // the resource -- This may implicitly give us back the fallback icon,
3112 // but don't worry about that. All we're doing with usingFallbackIcon is
3113 // to avoid saving lots of copies of that in the database, and most apps
3114 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003115 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003116
Joe Onorato56d82912010-03-07 14:32:10 -05003117 // the db
3118 if (icon == null) {
3119 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003120 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003121 }
3122 }
3123 // the fallback icon
3124 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003125 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003126 info.usingFallbackIcon = true;
3127 }
3128 info.setIcon(icon);
3129
Kenny Guyed131872014-04-30 03:02:21 +01003130 // From the cache.
3131 if (labelCache != null) {
3132 info.title = labelCache.get(componentName);
3133 }
3134
Joe Onorato56d82912010-03-07 14:32:10 -05003135 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003136 if (info.title == null && lai != null) {
3137 info.title = lai.getLabel();
3138 if (labelCache != null) {
3139 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003140 }
Joe Onorato56d82912010-03-07 14:32:10 -05003141 }
3142 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003143 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003144 if (c != null) {
3145 info.title = c.getString(titleIndex);
3146 }
3147 }
3148 // fall back to the class name of the activity
3149 if (info.title == null) {
3150 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003151 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003152 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003153 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003154 info.contentDescription = mUserManager.getBadgedLabelForUser(
3155 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003156 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003157 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003158
Winson Chung64359a52013-07-08 17:17:08 -07003159 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3160 ItemInfoFilter f) {
3161 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3162 for (ItemInfo i : infos) {
3163 if (i instanceof ShortcutInfo) {
3164 ShortcutInfo info = (ShortcutInfo) i;
3165 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003166 if (info.restoredIntent != null) {
3167 cn = info.restoredIntent.getComponent();
3168 }
Winson Chung64359a52013-07-08 17:17:08 -07003169 if (cn != null && f.filterItem(null, info, cn)) {
3170 filtered.add(info);
3171 }
3172 } else if (i instanceof FolderInfo) {
3173 FolderInfo info = (FolderInfo) i;
3174 for (ShortcutInfo s : info.contents) {
3175 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003176 if (s.restoredIntent != null) {
3177 cn = s.restoredIntent.getComponent();
3178 }
Winson Chung64359a52013-07-08 17:17:08 -07003179 if (cn != null && f.filterItem(info, s, cn)) {
3180 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003181 }
3182 }
Winson Chung64359a52013-07-08 17:17:08 -07003183 } else if (i instanceof LauncherAppWidgetInfo) {
3184 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3185 ComponentName cn = info.providerName;
3186 if (cn != null && f.filterItem(null, info, cn)) {
3187 filtered.add(info);
3188 }
Winson Chung8a435102012-08-30 17:16:53 -07003189 }
3190 }
Winson Chung64359a52013-07-08 17:17:08 -07003191 return new ArrayList<ItemInfo>(filtered);
3192 }
3193
Kenny Guyed131872014-04-30 03:02:21 +01003194 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3195 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003196 ItemInfoFilter filter = new ItemInfoFilter() {
3197 @Override
3198 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003199 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003200 }
3201 };
3202 return filterItemInfos(sBgItemsIdMap.values(), filter);
3203 }
3204
Kenny Guyed131872014-04-30 03:02:21 +01003205 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3206 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003207 ItemInfoFilter filter = new ItemInfoFilter() {
3208 @Override
3209 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003210 if (info.user == null) {
3211 return cn.equals(cname);
3212 } else {
3213 return cn.equals(cname) && info.user.equals(user);
3214 }
Winson Chung64359a52013-07-08 17:17:08 -07003215 }
3216 };
3217 return filterItemInfos(sBgItemsIdMap.values(), filter);
3218 }
3219
3220 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3221 if (i instanceof ShortcutInfo) {
3222 ShortcutInfo info = (ShortcutInfo) i;
3223 // We need to check for ACTION_MAIN otherwise getComponent() might
3224 // return null for some shortcuts (for instance, for shortcuts to
3225 // web pages.)
3226 Intent intent = info.intent;
3227 ComponentName name = intent.getComponent();
3228 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3229 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3230 return true;
3231 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003232 // placeholder shortcuts get special treatment, let them through too.
3233 if (info.getRestoredIntent() != null) {
3234 return true;
3235 }
Winson Chung64359a52013-07-08 17:17:08 -07003236 }
3237 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003238 }
3239
3240 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003241 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003242 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003243 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003244 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3245 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003246
Joe Onorato56d82912010-03-07 14:32:10 -05003247 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003248 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003249 // Non-app shortcuts are only supported for current user.
3250 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003251 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003252
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003253 // TODO: If there's an explicit component and we can't install that, delete it.
3254
Joe Onorato56d82912010-03-07 14:32:10 -05003255 info.title = c.getString(titleIndex);
3256
Joe Onorato9c1289c2009-08-17 11:03:03 -04003257 int iconType = c.getInt(iconTypeIndex);
3258 switch (iconType) {
3259 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3260 String packageName = c.getString(iconPackageIndex);
3261 String resourceName = c.getString(iconResourceIndex);
3262 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003263 info.customIcon = false;
3264 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003265 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003266 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003267 if (resources != null) {
3268 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003269 icon = Utilities.createIconBitmap(
3270 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003271 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003272 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003273 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003274 }
Joe Onorato56d82912010-03-07 14:32:10 -05003275 // the db
3276 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003277 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003278 }
3279 // the fallback icon
3280 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003281 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003282 info.usingFallbackIcon = true;
3283 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003284 break;
3285 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003286 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003287 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003288 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003289 info.customIcon = false;
3290 info.usingFallbackIcon = true;
3291 } else {
3292 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003293 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003294 break;
3295 default:
Kenny Guyed131872014-04-30 03:02:21 +01003296 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003297 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003298 info.customIcon = false;
3299 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003300 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003301 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003302 return info;
3303 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003304
Michael Jurka931dc972011-08-05 15:08:15 -07003305 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003306 @SuppressWarnings("all") // suppress dead code warning
3307 final boolean debug = false;
3308 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003309 Log.d(TAG, "getIconFromCursor app="
3310 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3311 }
3312 byte[] data = c.getBlob(iconIndex);
3313 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003314 return Utilities.createIconBitmap(
3315 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003316 } catch (Exception e) {
3317 return null;
3318 }
3319 }
3320
Winson Chung3d503fb2011-07-13 17:25:49 -07003321 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3322 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003323 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003324 if (info == null) {
3325 return null;
3326 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003327 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003328
3329 return info;
3330 }
3331
Winson Chunga9abd0e2010-10-27 17:18:37 -07003332 /**
Winson Chung55cef262010-10-28 14:14:18 -07003333 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3334 */
3335 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3336 ComponentName component) {
3337 List<AppWidgetProviderInfo> widgets =
3338 AppWidgetManager.getInstance(context).getInstalledProviders();
3339 for (AppWidgetProviderInfo info : widgets) {
3340 if (info.provider.equals(component)) {
3341 return info;
3342 }
3343 }
3344 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003345 }
3346
Winson Chung68846fd2010-10-29 11:00:27 -07003347 /**
3348 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3349 */
3350 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3351 final PackageManager packageManager = context.getPackageManager();
3352 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3353 new ArrayList<WidgetMimeTypeHandlerData>();
3354
3355 final Intent supportsIntent =
3356 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3357 supportsIntent.setType(mimeType);
3358
3359 // Create a set of widget configuration components that we can test against
3360 final List<AppWidgetProviderInfo> widgets =
3361 AppWidgetManager.getInstance(context).getInstalledProviders();
3362 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3363 new HashMap<ComponentName, AppWidgetProviderInfo>();
3364 for (AppWidgetProviderInfo info : widgets) {
3365 configurationComponentToWidget.put(info.configure, info);
3366 }
3367
3368 // Run through each of the intents that can handle this type of clip data, and cross
3369 // reference them with the components that are actual configuration components
3370 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3371 PackageManager.MATCH_DEFAULT_ONLY);
3372 for (ResolveInfo info : activities) {
3373 final ActivityInfo activityInfo = info.activityInfo;
3374 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3375 activityInfo.name);
3376 if (configurationComponentToWidget.containsKey(infoComponent)) {
3377 supportedConfigurationActivities.add(
3378 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3379 configurationComponentToWidget.get(infoComponent)));
3380 }
3381 }
3382 return supportedConfigurationActivities;
3383 }
3384
Winson Chunga9abd0e2010-10-27 17:18:37 -07003385 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003386 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3387 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3388 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3389
Adam Cohend9198822011-11-22 16:42:47 -08003390 if (intent == null) {
3391 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3392 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3393 return null;
3394 }
3395
Joe Onorato0589f0f2010-02-08 13:44:00 -08003396 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003397 boolean customIcon = false;
3398 ShortcutIconResource iconResource = null;
3399
3400 if (bitmap != null && bitmap instanceof Bitmap) {
3401 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003402 customIcon = true;
3403 } else {
3404 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3405 if (extra != null && extra instanceof ShortcutIconResource) {
3406 try {
3407 iconResource = (ShortcutIconResource) extra;
3408 final PackageManager packageManager = context.getPackageManager();
3409 Resources resources = packageManager.getResourcesForApplication(
3410 iconResource.packageName);
3411 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003412 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003413 mIconCache.getFullResIcon(resources, id),
3414 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003415 } catch (Exception e) {
3416 Log.w(TAG, "Could not load shortcut icon: " + extra);
3417 }
3418 }
3419 }
3420
Michael Jurkac9d95c52011-08-29 14:03:34 -07003421 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003422
Kenny Guyed131872014-04-30 03:02:21 +01003423 // Only support intents for current user for now. Intents sent from other
3424 // users wouldn't get here without intent forwarding anyway.
3425 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003426 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003427 if (fallbackIcon != null) {
3428 icon = fallbackIcon;
3429 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003430 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003431 info.usingFallbackIcon = true;
3432 }
Joe Onorato56d82912010-03-07 14:32:10 -05003433 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003434 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003435
Joe Onorato0589f0f2010-02-08 13:44:00 -08003436 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003437 info.contentDescription = mUserManager.getBadgedLabelForUser(
3438 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003439 info.intent = intent;
3440 info.customIcon = customIcon;
3441 info.iconResource = iconResource;
3442
3443 return info;
3444 }
3445
Winson Chungaac01e12011-08-17 10:37:13 -07003446 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3447 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003448 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003449 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003450 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003451 }
Joe Onorato56d82912010-03-07 14:32:10 -05003452 // If this icon doesn't have a custom icon, check to see
3453 // what's stored in the DB, and if it doesn't match what
3454 // we're going to show, store what we are going to show back
3455 // into the DB. We do this so when we're loading, if the
3456 // package manager can't find an icon (for example because
3457 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003458 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003459 cache.put(info, c.getBlob(iconIndex));
3460 return true;
3461 }
3462 return false;
3463 }
3464 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3465 boolean needSave = false;
3466 try {
3467 if (data != null) {
3468 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3469 Bitmap loaded = info.getIcon(mIconCache);
3470 needSave = !saved.sameAs(loaded);
3471 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003472 needSave = true;
3473 }
Winson Chungaac01e12011-08-17 10:37:13 -07003474 } catch (Exception e) {
3475 needSave = true;
3476 }
3477 if (needSave) {
3478 Log.d(TAG, "going to save icon bitmap for info=" + info);
3479 // This is slower than is ideal, but this only happens once
3480 // or when the app is updated with a new icon.
3481 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003482 }
3483 }
3484
Joe Onorato9c1289c2009-08-17 11:03:03 -04003485 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003486 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003487 * or make a new one.
3488 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003489 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003490 // See if a placeholder was created for us already
3491 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003492 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003493 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003494 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003495 folders.put(id, folderInfo);
3496 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003497 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003498 }
3499
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003500 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003501 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003502 return new Comparator<AppInfo>() {
3503 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003504 if (a.user.equals(b.user)) {
3505 int result = collator.compare(a.title.toString().trim(),
3506 b.title.toString().trim());
3507 if (result == 0) {
3508 result = a.componentName.compareTo(b.componentName);
3509 }
3510 return result;
3511 } else {
3512 // TODO Need to figure out rules for sorting
3513 // profiles, this puts work second.
3514 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003515 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003516 }
Winson Chung11904872012-09-17 16:58:46 -07003517 };
3518 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003519 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3520 = new Comparator<AppInfo>() {
3521 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003522 if (a.firstInstallTime < b.firstInstallTime) return 1;
3523 if (a.firstInstallTime > b.firstInstallTime) return -1;
3524 return 0;
3525 }
3526 };
Winson Chung11904872012-09-17 16:58:46 -07003527 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3528 final Collator collator = Collator.getInstance();
3529 return new Comparator<AppWidgetProviderInfo>() {
3530 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003531 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003532 }
3533 };
3534 }
Winson Chung5308f242011-08-18 12:12:41 -07003535 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3536 if (info.activityInfo != null) {
3537 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3538 } else {
3539 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3540 }
3541 }
Kenny Guyed131872014-04-30 03:02:21 +01003542 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003543 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003544 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003545 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003546 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003547 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003548 }
Kenny Guyed131872014-04-30 03:02:21 +01003549 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003550 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003551 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003552 }
Kenny Guyed131872014-04-30 03:02:21 +01003553 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003554 CharSequence labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003555 ComponentName keyA = a.getComponentName();
3556 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003557 if (mLabelCache.containsKey(keyA)) {
3558 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003559 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003560 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003561
Winson Chung5308f242011-08-18 12:12:41 -07003562 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003563 }
Winson Chung5308f242011-08-18 12:12:41 -07003564 if (mLabelCache.containsKey(keyB)) {
3565 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003566 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003567 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003568
Winson Chung5308f242011-08-18 12:12:41 -07003569 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003570 }
Winson Chung11904872012-09-17 16:58:46 -07003571 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003572 }
3573 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003574 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003575 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003576 private PackageManager mPackageManager;
3577 private HashMap<Object, String> mLabelCache;
3578 WidgetAndShortcutNameComparator(PackageManager pm) {
3579 mPackageManager = pm;
3580 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003581 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003582 }
3583 public final int compare(Object a, Object b) {
3584 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003585 if (mLabelCache.containsKey(a)) {
3586 labelA = mLabelCache.get(a);
3587 } else {
3588 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003589 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003590 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003591 mLabelCache.put(a, labelA);
3592 }
3593 if (mLabelCache.containsKey(b)) {
3594 labelB = mLabelCache.get(b);
3595 } else {
3596 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003597 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003598 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003599 mLabelCache.put(b, labelB);
3600 }
Winson Chung11904872012-09-17 16:58:46 -07003601 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003602 }
3603 };
Joe Onoratobe386092009-11-17 17:32:16 -08003604
3605 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003606 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003607 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3608 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3609 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3610 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003611 if (mLoaderTask != null) {
3612 mLoaderTask.dumpState();
3613 } else {
3614 Log.d(TAG, "mLoaderTask=null");
3615 }
Joe Onoratobe386092009-11-17 17:32:16 -08003616 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003617}