blob: b44433d8d957e8b2c2c6ece095da2f8175432a9e [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.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040034import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070036import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.content.res.Resources;
38import android.database.Cursor;
39import android.graphics.Bitmap;
40import android.graphics.BitmapFactory;
41import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040049import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080050import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070051import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070077import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070078import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080/**
81 * Maintains in-memory state of the Launcher. It is expected that there should be only one
82 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070083 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 */
Kenny Guyed131872014-04-30 03:02:21 +010085public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010086 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040088 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
89
Joe Onorato9c1289c2009-08-17 11:03:03 -040090 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070091
Daniel Sandler8707e0f2013-08-15 15:54:18 -070092 // true = use a "More Apps" folder for non-workspace apps on upgrade
93 // false = strew non-workspace apps across the workspace on upgrade
94 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050095 public static final int LOADER_FLAG_NONE = 0;
96 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
97 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
98
Joe Onorato36115782010-06-17 13:28:48 -040099 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500100 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800101
Winson Chungee055712013-07-30 14:46:24 -0700102 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800103 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400104
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400105 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400106 private final Object mLock = new Object();
107 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400108 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200110 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
Winson Chung81b52252012-08-27 15:34:29 -0700112 // Specific runnable types that are run on the main thread deferred handler, this allows us to
113 // clear all queued binding runnables when the Launcher activity is destroyed.
114 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
115 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
116
Jason Monkbbe1e242014-05-16 17:37:34 -0400117 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700118
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700119 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
120 static {
121 sWorkerThread.start();
122 }
123 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
124
Joe Onoratocc67f472010-06-08 10:54:30 -0700125 // We start off with everything not loaded. After that, we assume that
126 // our monitoring of the package manager provides all updates and we never
127 // need to do a requery. These are only ever touched from the loader thread.
128 private boolean mWorkspaceLoaded;
129 private boolean mAllAppsLoaded;
130
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700131 // When we are loading pages synchronously, we can't just post the binding of items on the side
132 // pages as this delays the rotation process. Instead, we wait for a callback from the first
133 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
134 // a normal load, we also clear this set of Runnables.
135 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
136
Joe Onorato9c1289c2009-08-17 11:03:03 -0400137 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800138
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700140 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800141
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700142 // The lock that must be acquired before referencing any static bg data structures. Unlike
143 // other locks, this one can generally be held long-term because we never expect any of these
144 // static data structures to be referenced outside of the worker thread except on the first
145 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700146 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700147
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151
Adam Cohen487f7dd2012-06-28 18:12:10 -0700152 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
153 // created by LauncherModel that are directly on the home screen (however, no widgets or
154 // shortcuts within folders).
155 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156
Adam Cohen487f7dd2012-06-28 18:12:10 -0700157 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
158 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159 new ArrayList<LauncherAppWidgetInfo>();
160
Adam Cohen487f7dd2012-06-28 18:12:10 -0700161 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
162 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700163
Adam Cohen487f7dd2012-06-28 18:12:10 -0700164 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
165 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700166
167 // sBgWorkspaceScreens is the ordered set of workspace screens.
168 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
169
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700170 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700171 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
172 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700173
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 // </ only access in worker thread >
175
176 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177
Reena Lee99a73f32011-10-24 17:27:37 -0700178 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700179
Kenny Guyed131872014-04-30 03:02:21 +0100180 private final LauncherAppsCompat mLauncherApps;
181 private final UserManagerCompat mUserManager;
182
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700184 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400185 public int getCurrentWorkspaceScreen();
186 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700187 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
188 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700189 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700190 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500191 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700192 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400193 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200194 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700195 public void bindAppsAdded(ArrayList<Long> newScreens,
196 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700197 ArrayList<ItemInfo> addAnimated,
198 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200199 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyale755d462014-07-22 13:48:29 -0700200 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Winson Chung83892cc2013-05-01 16:53:33 -0700201 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100202 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200203 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100204 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700205 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700206 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700207 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400208 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209
Winson Chung64359a52013-07-08 17:17:08 -0700210 public interface ItemInfoFilter {
211 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
212 }
213
Bjorn Bringert1307f632013-10-03 22:31:03 +0100214 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800215 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400216
Winson Chungee055712013-07-30 14:46:24 -0700217 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700218 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400219 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
220 // resource string.
221 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
222 ProviderInfo providerInfo =
223 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
224 ProviderInfo redirectProvider =
225 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700226
227 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400228 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700229
230 if (mOldContentProviderExists) {
231 Log.d(TAG, "Old launcher provider exists.");
232 } else {
233 Log.d(TAG, "Old launcher provider does not exist.");
234 }
235
Daniel Sandlere4f98912013-06-25 15:13:26 -0400236 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100237 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800238 mIconCache = iconCache;
239
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400240 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700241 Configuration config = res.getConfiguration();
242 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100243 mLauncherApps = LauncherAppsCompat.getInstance(context);
244 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800245 }
246
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700247 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
248 * posted on the main thread handler. */
249 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700250 runOnMainThread(r, 0);
251 }
252 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700253 if (sWorkerThread.getThreadId() == Process.myTid()) {
254 // If we are on the worker thread, post onto the main handler
255 mHandler.post(r);
256 } else {
257 r.run();
258 }
259 }
260
261 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
262 * posted on the worker thread handler. */
263 private static void runOnWorkerThread(Runnable r) {
264 if (sWorkerThread.getThreadId() == Process.myTid()) {
265 r.run();
266 } else {
267 // If we are not on the worker thread, then post to the worker handler
268 sWorker.post(r);
269 }
270 }
271
Winson Chunge43a1e72014-01-15 10:33:02 -0800272 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
273 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800274 }
275
Winson Chungc9168342013-06-26 14:54:55 -0700276 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
277 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700278 LauncherAppState app = LauncherAppState.getInstance();
279 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
280 final int xCount = (int) grid.numColumns;
281 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700282 boolean[][] occupied = new boolean[xCount][yCount];
283
284 int cellX, cellY, spanX, spanY;
285 for (int i = 0; i < items.size(); ++i) {
286 final ItemInfo item = items.get(i);
287 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
288 if (item.screenId == screen) {
289 cellX = item.cellX;
290 cellY = item.cellY;
291 spanX = item.spanX;
292 spanY = item.spanY;
293 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
294 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
295 occupied[x][y] = true;
296 }
297 }
298 }
299 }
300 }
301
302 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
303 }
304 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700305 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700306 int firstScreenIndex,
307 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700308 // Lock on the app so that we don't try and get the items while apps are being added
309 LauncherAppState app = LauncherAppState.getInstance();
310 LauncherModel model = app.getModel();
311 boolean found = false;
312 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700313 if (sWorkerThread.getThreadId() != Process.myTid()) {
314 // Flush the LauncherModel worker thread, so that if we just did another
315 // processInstallShortcut, we give it time for its shortcut to get added to the
316 // database (getItemsInLocalCoordinates reads the database)
317 model.flushWorkerThread();
318 }
Winson Chungc9168342013-06-26 14:54:55 -0700319 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700320
321 // Try adding to the workspace screens incrementally, starting at the default or center
322 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700323 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
324 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700325 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700326 int[] tmpCoordinates = new int[2];
327 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700328 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700329 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700330 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700331 }
332 }
333 }
Winson Chungc9168342013-06-26 14:54:55 -0700334 return null;
335 }
336
Sunny Goyale755d462014-07-22 13:48:29 -0700337 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500338 // Process the updated package state
339 Runnable r = new Runnable() {
340 public void run() {
341 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
342 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700343 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500344 }
345 }
346 };
347 mHandler.post(r);
348 }
349
Adam Cohen76a47a12014-02-05 11:47:43 -0800350 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
351 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
352
353 if (allAppsApps == null) {
354 throw new RuntimeException("allAppsApps must not be null");
355 }
356 if (allAppsApps.isEmpty()) {
357 return;
358 }
359
Chris Wrenb6d4c282014-01-27 14:17:08 -0500360 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
361 Iterator<AppInfo> iter = allAppsApps.iterator();
362 while (iter.hasNext()) {
363 ItemInfo a = iter.next();
Sunny Goyal34942622014-08-29 17:20:55 -0700364 if (LauncherModel.appWasPromise(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500365 restoredAppsFinal.add((AppInfo) a);
366 }
367 }
368
Adam Cohen76a47a12014-02-05 11:47:43 -0800369 // Process the newly added applications and add them to the database first
370 Runnable r = new Runnable() {
371 public void run() {
372 runOnMainThread(new Runnable() {
373 public void run() {
374 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
375 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500376 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500377 for (AppInfo info : restoredAppsFinal) {
378 final Intent intent = info.getIntent();
379 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100380 mIconCache.deletePreloadedIcon(intent.getComponent(),
381 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500382 }
383 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500384 callbacks.bindAppsUpdated(restoredAppsFinal);
385 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500386 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800387 }
388 }
389 });
390 }
391 };
392 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700393 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800394
395 public void addAndBindAddedWorkspaceApps(final Context context,
396 final ArrayList<ItemInfo> workspaceApps) {
397 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
398
399 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800400 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
401 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800402 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700403 return;
Winson Chung997a9232013-07-24 15:33:46 -0700404 }
Winson Chung64359a52013-07-08 17:17:08 -0700405 // Process the newly added applications and add them to the database first
406 Runnable r = new Runnable() {
407 public void run() {
408 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
409 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500410 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700411
Winson Chung76828c82013-08-19 15:43:29 -0700412 // Get the list of workspace screens. We need to append to this list and
413 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
414 // called.
415 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
416 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
417 for (Integer i : orderedScreens.keySet()) {
418 long screenId = orderedScreens.get(i);
419 workspaceScreens.add(screenId);
420 }
421
Winson Chung64359a52013-07-08 17:17:08 -0700422 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700423 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700424 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700425 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700426 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700427 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700428
429 // Short-circuit this logic if the icon exists somewhere on the workspace
430 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500431 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
432 if (a instanceof AppInfo &&
Sunny Goyal34942622014-08-29 17:20:55 -0700433 LauncherModel.appWasPromise(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500434 restoredAppsFinal.add((AppInfo) a);
435 }
Winson Chung64359a52013-07-08 17:17:08 -0700436 continue;
437 }
438
Winson Chung87412982013-10-03 18:34:14 -0700439 // Add this icon to the db, creating a new page if necessary. If there
440 // is only the empty page then we just add items to the first page.
441 // Otherwise, we add them to the next pages.
442 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700443 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700444 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700445 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200446 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700447
448 // If we can't find a valid position, then just add a new screen.
449 // This takes time so we need to re-queue the add until the new
450 // page is added. Create as many screens as necessary to satisfy
451 // the startSearchPageIndex.
452 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700453 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700454 while (numPagesToAdd > 0) {
455 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700457 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700458 addedWorkspaceScreensFinal.add(screenId);
459 numPagesToAdd--;
460 }
Winson Chung76828c82013-08-19 15:43:29 -0700461
Winson Chung64359a52013-07-08 17:17:08 -0700462 // Find the coordinate again
463 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700464 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700465 }
466 if (coords == null) {
467 throw new RuntimeException("Coordinates should not be null");
468 }
469
Winson Chung997a9232013-07-24 15:33:46 -0700470 ShortcutInfo shortcutInfo;
471 if (a instanceof ShortcutInfo) {
472 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200473 } else if (a instanceof AppInfo) {
474 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700475 } else {
476 throw new RuntimeException("Unexpected info type");
477 }
Winson Chung94d67682013-09-25 16:29:40 -0700478
Winson Chung64359a52013-07-08 17:17:08 -0700479 // Add the shortcut to the db
480 addItemToDatabase(context, shortcutInfo,
481 LauncherSettings.Favorites.CONTAINER_DESKTOP,
482 coords.first, coords.second[0], coords.second[1], false);
483 // Save the ShortcutInfo for binding in the workspace
484 addedShortcutsFinal.add(shortcutInfo);
485 }
486 }
487
Winson Chung76828c82013-08-19 15:43:29 -0700488 // Update the workspace screens
489 updateWorkspaceScreenOrder(context, workspaceScreens);
490
Adam Cohen76a47a12014-02-05 11:47:43 -0800491 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700492 runOnMainThread(new Runnable() {
493 public void run() {
494 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
495 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700496 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
497 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700498 if (!addedShortcutsFinal.isEmpty()) {
499 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
500 long lastScreenId = info.screenId;
501 for (ItemInfo i : addedShortcutsFinal) {
502 if (i.screenId == lastScreenId) {
503 addAnimated.add(i);
504 } else {
505 addNotAnimated.add(i);
506 }
Winson Chung997a9232013-07-24 15:33:46 -0700507 }
508 }
Winson Chungd64d1762013-08-20 14:37:16 -0700509 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800510 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500511 if (!restoredAppsFinal.isEmpty()) {
512 callbacks.bindAppsUpdated(restoredAppsFinal);
513 }
Winson Chung997a9232013-07-24 15:33:46 -0700514 }
Winson Chung64359a52013-07-08 17:17:08 -0700515 }
Winson Chung997a9232013-07-24 15:33:46 -0700516 });
517 }
Winson Chung64359a52013-07-08 17:17:08 -0700518 }
519 };
520 runOnWorkerThread(r);
521 }
522
Winson Chung81b52252012-08-27 15:34:29 -0700523 public void unbindItemInfosAndClearQueuedBindRunnables() {
524 if (sWorkerThread.getThreadId() == Process.myTid()) {
525 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
526 "main thread");
527 }
528
529 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400530 synchronized (mDeferredBindRunnables) {
531 mDeferredBindRunnables.clear();
532 }
Winson Chung81b52252012-08-27 15:34:29 -0700533 // Remove any queued bind runnables
534 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
535 // Unbind all the workspace items
536 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700537 }
538
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700539 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700540 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700541 // Ensure that we don't use the same workspace items data structure on the main thread
542 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700543 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
544 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700545 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700546 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
547 tmpAppWidgets.addAll(sBgAppWidgets);
548 }
549 Runnable r = new Runnable() {
550 @Override
551 public void run() {
552 for (ItemInfo item : tmpWorkspaceItems) {
553 item.unbind();
554 }
555 for (ItemInfo item : tmpAppWidgets) {
556 item.unbind();
557 }
558 }
559 };
560 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700561 }
562
Joe Onorato9c1289c2009-08-17 11:03:03 -0400563 /**
564 * Adds an item to the DB if it was not created previously, or move it to a new
565 * <container, screen, cellX, cellY>
566 */
567 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700568 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400569 if (item.container == ItemInfo.NO_ID) {
570 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400572 } else {
573 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700574 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 }
576 }
577
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700578 static void checkItemInfoLocked(
579 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
580 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
581 if (modelItem != null && item != modelItem) {
582 // check all the data is consistent
583 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
584 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
585 ShortcutInfo shortcut = (ShortcutInfo) item;
586 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
587 modelShortcut.intent.filterEquals(shortcut.intent) &&
588 modelShortcut.id == shortcut.id &&
589 modelShortcut.itemType == shortcut.itemType &&
590 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700592 modelShortcut.cellX == shortcut.cellX &&
593 modelShortcut.cellY == shortcut.cellY &&
594 modelShortcut.spanX == shortcut.spanX &&
595 modelShortcut.spanY == shortcut.spanY &&
596 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
597 (modelShortcut.dropPos != null &&
598 shortcut.dropPos != null &&
599 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
600 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
601 // For all intents and purposes, this is the same object
602 return;
603 }
604 }
605
606 // the modelItem needs to match up perfectly with item if our model is
607 // to be consistent with the database-- for now, just require
608 // modelItem == item or the equality check above
609 String msg = "item: " + ((item != null) ? item.toString() : "null") +
610 "modelItem: " +
611 ((modelItem != null) ? modelItem.toString() : "null") +
612 "Error: ItemInfo passed to checkItemInfo doesn't match original";
613 RuntimeException e = new RuntimeException(msg);
614 if (stackTrace != null) {
615 e.setStackTrace(stackTrace);
616 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800617 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700618 }
619 }
620
Michael Jurka816474f2012-06-25 14:49:02 -0700621 static void checkItemInfo(final ItemInfo item) {
622 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
623 final long itemId = item.id;
624 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700625 public void run() {
626 synchronized (sBgLock) {
627 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700628 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700629 }
630 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700631 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700632 }
633
Michael Jurkac9d95c52011-08-29 14:03:34 -0700634 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
635 final ItemInfo item, final String callingFunction) {
636 final long itemId = item.id;
637 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
638 final ContentResolver cr = context.getContentResolver();
639
Adam Cohen487f7dd2012-06-28 18:12:10 -0700640 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700641 Runnable r = new Runnable() {
642 public void run() {
643 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700644 updateItemArrays(item, itemId, stackTrace);
645 }
646 };
647 runOnWorkerThread(r);
648 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700649
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700650 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
651 final ArrayList<ItemInfo> items, final String callingFunction) {
652 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700653
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700654 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
655 Runnable r = new Runnable() {
656 public void run() {
657 ArrayList<ContentProviderOperation> ops =
658 new ArrayList<ContentProviderOperation>();
659 int count = items.size();
660 for (int i = 0; i < count; i++) {
661 ItemInfo item = items.get(i);
662 final long itemId = item.id;
663 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
664 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700665
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700666 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
667 updateItemArrays(item, itemId, stackTrace);
668
669 }
670 try {
671 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
672 } catch (Exception e) {
673 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700674 }
675 }
676 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700677 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700678 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700679
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700680 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
681 // Lock on mBgLock *after* the db operation
682 synchronized (sBgLock) {
683 checkItemInfoLocked(itemId, item, stackTrace);
684
685 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
686 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
687 // Item is in a folder, make sure this folder exists
688 if (!sBgFolders.containsKey(item.container)) {
689 // An items container is being set to a that of an item which is not in
690 // the list of Folders.
691 String msg = "item: " + item + " container being set to: " +
692 item.container + ", not in the list of folders";
693 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700694 }
695 }
696
697 // Items are added/removed from the corresponding FolderInfo elsewhere, such
698 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
699 // that are on the desktop, as appropriate
700 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800701 if (modelItem != null &&
702 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
703 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700704 switch (modelItem.itemType) {
705 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
706 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
707 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
708 if (!sBgWorkspaceItems.contains(modelItem)) {
709 sBgWorkspaceItems.add(modelItem);
710 }
711 break;
712 default:
713 break;
714 }
715 } else {
716 sBgWorkspaceItems.remove(modelItem);
717 }
718 }
719 }
720
Michael Jurkac7700af2013-05-14 20:17:58 +0200721 public void flushWorkerThread() {
722 mFlushingWorkerThread = true;
723 Runnable waiter = new Runnable() {
724 public void run() {
725 synchronized (this) {
726 notifyAll();
727 mFlushingWorkerThread = false;
728 }
729 }
730 };
731
732 synchronized(waiter) {
733 runOnWorkerThread(waiter);
734 if (mLoaderTask != null) {
735 synchronized(mLoaderTask) {
736 mLoaderTask.notify();
737 }
738 }
739 boolean success = false;
740 while (!success) {
741 try {
742 waiter.wait();
743 success = true;
744 } catch (InterruptedException e) {
745 }
746 }
747 }
748 }
749
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800750 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400751 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700752 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700753 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700754 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400756 item.cellX = cellX;
757 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700758
Winson Chung3d503fb2011-07-13 17:25:49 -0700759 // We store hotseat items in canonical form which is this orientation invariant position
760 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700761 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700762 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700763 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700764 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700765 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700766 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767
768 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400769 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700770 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
771 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700772 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400773
Michael Jurkac9d95c52011-08-29 14:03:34 -0700774 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700775 }
776
777 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700778 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
779 * cellX, cellY have already been updated on the ItemInfos.
780 */
781 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
782 final long container, final int screen) {
783
784 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
785 int count = items.size();
786
787 for (int i = 0; i < count; i++) {
788 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700789 item.container = container;
790
791 // We store hotseat items in canonical form which is this orientation invariant position
792 // in the hotseat
793 if (context instanceof Launcher && screen < 0 &&
794 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700796 item.cellY);
797 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700798 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700799 }
800
801 final ContentValues values = new ContentValues();
802 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
803 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
804 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700805 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700806
807 contentValues.add(values);
808 }
809 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
810 }
811
812 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700813 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800814 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700815 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700817 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800818 item.cellX = cellX;
819 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700820 item.spanX = spanX;
821 item.spanY = spanY;
822
823 // We store hotseat items in canonical form which is this orientation invariant position
824 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700825 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700826 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700828 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700829 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700830 }
Adam Cohend4844c32011-02-18 19:25:06 -0800831
Adam Cohend4844c32011-02-18 19:25:06 -0800832 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800833 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700834 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
835 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
836 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
837 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700838 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800839
Michael Jurka816474f2012-06-25 14:49:02 -0700840 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700841 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700842
843 /**
844 * Update an item to the database in a specified container.
845 */
846 static void updateItemInDatabase(Context context, final ItemInfo item) {
847 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100848 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700849 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
850 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800851 }
852
853 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 * Returns true if the shortcuts already exists in the database.
855 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800856 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400857 static boolean shortcutExists(Context context, String title, Intent intent) {
858 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700859 final Intent intentWithPkg, intentWithoutPkg;
860
861 if (intent.getComponent() != null) {
862 // If component is not null, an intent with null package will produce
863 // the same result and should also be a match.
864 if (intent.getPackage() != null) {
865 intentWithPkg = intent;
866 intentWithoutPkg = new Intent(intent).setPackage(null);
867 } else {
868 intentWithPkg = new Intent(intent).setPackage(
869 intent.getComponent().getPackageName());
870 intentWithoutPkg = intent;
871 }
872 } else {
873 intentWithPkg = intent;
874 intentWithoutPkg = intent;
875 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400876 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700877 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
878 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400879 boolean result = false;
880 try {
881 result = c.moveToFirst();
882 } finally {
883 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800884 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700886 }
887
Joe Onorato9c1289c2009-08-17 11:03:03 -0400888 /**
Sunny Goyal34942622014-08-29 17:20:55 -0700889 * Returns true if the promise shortcuts with the same package name exists on the workspace.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500890 */
Sunny Goyal34942622014-08-29 17:20:55 -0700891 static boolean appWasPromise(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500892 final ComponentName component = intent.getComponent();
893 if (component == null) {
894 return false;
895 }
Sunny Goyal34942622014-08-29 17:20:55 -0700896 return !getItemsByPackageName(component.getPackageName(), user).isEmpty();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500897 }
898
899 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700900 * Returns an ItemInfo array containing all the items in the LauncherModel.
901 * The ItemInfo.id is not set through this function.
902 */
903 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
904 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
905 final ContentResolver cr = context.getContentResolver();
906 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
907 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100908 LauncherSettings.Favorites.SCREEN,
909 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
910 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
911 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700912
913 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
914 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
915 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
916 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
917 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
918 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
919 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100920 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
921 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700922 try {
923 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700924 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700925 item.cellX = c.getInt(cellXIndex);
926 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700927 item.spanX = Math.max(1, c.getInt(spanXIndex));
928 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700929 item.container = c.getInt(containerIndex);
930 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700931 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100932 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100933 item.user = userManager.getUserForSerialNumber(serialNumber);
934 // Skip if user has been deleted.
935 if (item.user != null) {
936 items.add(item);
937 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700938 }
939 } catch (Exception e) {
940 items.clear();
941 } finally {
942 c.close();
943 }
944
945 return items;
946 }
947
948 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400949 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
950 */
951 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
952 final ContentResolver cr = context.getContentResolver();
953 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
954 "_id=? and (itemType=? or itemType=?)",
955 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700956 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700957
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 try {
959 if (c.moveToFirst()) {
960 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
961 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
962 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
963 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
964 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
965 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 FolderInfo folderInfo = null;
968 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700969 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
970 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700972 }
973
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 folderInfo.title = c.getString(titleIndex);
975 folderInfo.id = id;
976 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700977 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700978 folderInfo.cellX = c.getInt(cellXIndex);
979 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980
981 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700982 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 } finally {
984 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700985 }
986
987 return null;
988 }
989
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 /**
991 * Add an item to the database in a specified container. Sets the container, screen, cellX and
992 * cellY fields of the item. Also assigns an ID to the item.
993 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700994 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997 item.cellX = cellX;
998 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700999 // We store hotseat items in canonical form which is this orientation invariant position
1000 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001006 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001007
1008 final ContentValues values = new ContentValues();
1009 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001010 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001011
Michael Jurka414300a2013-08-27 15:42:35 +02001012 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001014 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001015
Jason Monk8e19cf22014-03-20 15:06:57 -04001016 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001017 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001018 public void run() {
1019 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1020 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001021
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001022 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001023 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001024 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001025 sBgItemsIdMap.put(item.id, item);
1026 switch (item.itemType) {
1027 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1028 sBgFolders.put(item.id, (FolderInfo) item);
1029 // Fall through
1030 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1031 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1032 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1033 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1034 sBgWorkspaceItems.add(item);
1035 } else {
1036 if (!sBgFolders.containsKey(item.container)) {
1037 // Adding an item to a folder that doesn't exist.
1038 String msg = "adding item: " + item + " to a folder that " +
1039 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001040 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001042 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001043 break;
1044 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1045 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1046 break;
1047 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001048 }
1049 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001050 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001051 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001052 }
1053
Joe Onorato9c1289c2009-08-17 11:03:03 -04001054 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001055 * Creates a new unique child id, for a given cell span across all layouts.
1056 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001057 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001058 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001059 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001060 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001061 }
1062
Sunny Goyal34942622014-08-29 17:20:55 -07001063 private static ArrayList<ItemInfo> getItemsByPackageName(
1064 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001065 ItemInfoFilter filter = new ItemInfoFilter() {
1066 @Override
1067 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1068 return cn.getPackageName().equals(pn) && info.user.equals(user);
1069 }
1070 };
Sunny Goyal34942622014-08-29 17:20:55 -07001071 return filterItemInfos(sBgItemsIdMap.values(), filter);
1072 }
1073
1074 /**
1075 * Removes all the items from the database corresponding to the specified package.
1076 */
1077 static void deletePackageFromDatabase(Context context, final String pn,
1078 final UserHandleCompat user) {
1079 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001080 }
1081
1082 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001083 * Removes the specified item from the database
1084 * @param context
1085 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001087 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001088 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1089 items.add(item);
1090 deleteItemsFromDatabase(context, items);
1091 }
1092
1093 /**
1094 * Removes the specified items from the database
1095 * @param context
1096 * @param item
1097 */
1098 static void deleteItemsFromDatabase(Context context, final ArrayList<ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001100
Michael Jurka83df1882011-08-31 20:59:26 -07001101 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001102 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001103 for (ItemInfo item : items) {
1104 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1105 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001107 // Lock on mBgLock *after* the db operation
1108 synchronized (sBgLock) {
1109 switch (item.itemType) {
1110 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1111 sBgFolders.remove(item.id);
1112 for (ItemInfo info: sBgItemsIdMap.values()) {
1113 if (info.container == item.id) {
1114 // We are deleting a folder which still contains items that
1115 // think they are contained by that folder.
1116 String msg = "deleting a folder (" + item + ") which still " +
1117 "contains items (" + info + ")";
1118 Log.e(TAG, msg);
1119 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001120 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001121 sBgWorkspaceItems.remove(item);
1122 break;
1123 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1124 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1125 sBgWorkspaceItems.remove(item);
1126 break;
1127 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1128 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1129 break;
1130 }
1131 sBgItemsIdMap.remove(item.id);
1132 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001133 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001134 }
1135 }
Michael Jurka83df1882011-08-31 20:59:26 -07001136 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001137 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001138 }
1139
1140 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001141 * Update the order of the workspace screens in the database. The array list contains
1142 * a list of screen ids in the order that they should appear.
1143 */
Winson Chungc9168342013-06-26 14:54:55 -07001144 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001145 // Log to disk
1146 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1147 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1148
Winson Chung64359a52013-07-08 17:17:08 -07001149 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 final ContentResolver cr = context.getContentResolver();
1151 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1152
1153 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001154 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 while (iter.hasNext()) {
1156 long id = iter.next();
1157 if (id < 0) {
1158 iter.remove();
1159 }
1160 }
1161
1162 Runnable r = new Runnable() {
1163 @Override
1164 public void run() {
Yura085c8532014-02-11 15:15:29 +00001165 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001167 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001168 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 for (int i = 0; i < count; i++) {
1170 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001171 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1173 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001174 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001175 }
Yura085c8532014-02-11 15:15:29 +00001176
1177 try {
1178 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1179 } catch (Exception ex) {
1180 throw new RuntimeException(ex);
1181 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001182
Winson Chungba9c37f2013-08-30 14:11:37 -07001183 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001184 sBgWorkspaceScreens.clear();
1185 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001186 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001187 }
1188 };
1189 runOnWorkerThread(r);
1190 }
1191
1192 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193 * Remove the contents of the specified folder from the database
1194 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001195 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196 final ContentResolver cr = context.getContentResolver();
1197
Michael Jurkac9d95c52011-08-29 14:03:34 -07001198 Runnable r = new Runnable() {
1199 public void run() {
1200 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001202 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 sBgItemsIdMap.remove(info.id);
1204 sBgFolders.remove(info.id);
1205 sBgDbIconCache.remove(info);
1206 sBgWorkspaceItems.remove(info);
1207 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001208
Michael Jurkac9d95c52011-08-29 14:03:34 -07001209 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1210 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001212 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001213 for (ItemInfo childInfo : info.contents) {
1214 sBgItemsIdMap.remove(childInfo.id);
1215 sBgDbIconCache.remove(childInfo);
1216 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001217 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001218 }
1219 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001220 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001221 }
1222
1223 /**
1224 * Set this as the current Launcher activity object for the loader.
1225 */
1226 public void initialize(Callbacks callbacks) {
1227 synchronized (mLock) {
1228 mCallbacks = new WeakReference<Callbacks>(callbacks);
1229 }
1230 }
1231
Kenny Guyed131872014-04-30 03:02:21 +01001232 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001233 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001234 int op = PackageUpdatedTask.OP_UPDATE;
1235 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1236 user));
1237 }
1238
1239 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001240 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001241 int op = PackageUpdatedTask.OP_REMOVE;
1242 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1243 user));
1244 }
1245
1246 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001247 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001248 int op = PackageUpdatedTask.OP_ADD;
1249 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1250 user));
1251 }
1252
1253 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001254 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001255 boolean replacing) {
1256 if (!replacing) {
1257 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1258 user));
1259 if (mAppsCanBeOnRemoveableStorage) {
1260 // Only rebind if we support removable storage. It catches the
1261 // case where
1262 // apps on the external sd card need to be reloaded
1263 startLoaderFromBackground();
1264 }
1265 } else {
1266 // If we are replacing then just update the packages in the list
1267 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1268 packageNames, user));
1269 }
1270 }
1271
1272 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001273 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001274 boolean replacing) {
1275 if (!replacing) {
1276 enqueuePackageUpdated(new PackageUpdatedTask(
1277 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1278 user));
1279 }
1280
1281 }
1282
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001283 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001284 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1285 * ACTION_PACKAGE_CHANGED.
1286 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001287 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001288 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001289 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001290
Joe Onorato36115782010-06-17 13:28:48 -04001291 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001292 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001293 // If we have changed locale we need to clear out the labels in all apps/workspace.
1294 forceReload();
1295 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1296 // Check if configuration change was an mcc/mnc change which would affect app resources
1297 // and we would need to clear out the labels in all apps/workspace. Same handling as
1298 // above for ACTION_LOCALE_CHANGED
1299 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001300 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001301 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001302 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001303 forceReload();
1304 }
1305 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001306 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001307 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1308 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001309 if (mCallbacks != null) {
1310 Callbacks callbacks = mCallbacks.get();
1311 if (callbacks != null) {
1312 callbacks.bindSearchablesChanged();
1313 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001314 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001315 }
1316 }
1317
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001318 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001319 resetLoadedState(true, true);
1320
Reena Lee93f824a2011-09-23 17:20:28 -07001321 // Do this here because if the launcher activity is running it will be restarted.
1322 // If it's not running startLoaderFromBackground will merely tell it that it needs
1323 // to reload.
1324 startLoaderFromBackground();
1325 }
1326
Winson Chungf0c6ae02012-03-21 16:10:31 -07001327 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1328 synchronized (mLock) {
1329 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1330 // mWorkspaceLoaded to true later
1331 stopLoaderLocked();
1332 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1333 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1334 }
1335 }
1336
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001337 /**
1338 * When the launcher is in the background, it's possible for it to miss paired
1339 * configuration changes. So whenever we trigger the loader from the background
1340 * tell the launcher that it needs to re-run the loader when it comes back instead
1341 * of doing it now.
1342 */
1343 public void startLoaderFromBackground() {
1344 boolean runLoader = false;
1345 if (mCallbacks != null) {
1346 Callbacks callbacks = mCallbacks.get();
1347 if (callbacks != null) {
1348 // Only actually run the loader if they're not paused.
1349 if (!callbacks.setLoadOnResume()) {
1350 runLoader = true;
1351 }
1352 }
1353 }
1354 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001355 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001356 }
Joe Onorato36115782010-06-17 13:28:48 -04001357 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001358
Reena Lee93f824a2011-09-23 17:20:28 -07001359 // If there is already a loader task running, tell it to stop.
1360 // returns true if isLaunching() was true on the old task
1361 private boolean stopLoaderLocked() {
1362 boolean isLaunching = false;
1363 LoaderTask oldTask = mLoaderTask;
1364 if (oldTask != null) {
1365 if (oldTask.isLaunching()) {
1366 isLaunching = true;
1367 }
1368 oldTask.stopLocked();
1369 }
1370 return isLaunching;
1371 }
1372
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001374 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1375 }
1376
1377 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001378 synchronized (mLock) {
1379 if (DEBUG_LOADERS) {
1380 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1381 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001382
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001383 // Clear any deferred bind-runnables from the synchronized load process
1384 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001385 synchronized (mDeferredBindRunnables) {
1386 mDeferredBindRunnables.clear();
1387 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001388
Joe Onorato36115782010-06-17 13:28:48 -04001389 // Don't bother to start the thread if we know it's not going to do anything
1390 if (mCallbacks != null && mCallbacks.get() != null) {
1391 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001392 // also, don't downgrade isLaunching if we're already running
1393 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001394 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001395 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1396 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001397 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1398 } else {
1399 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1400 sWorker.post(mLoaderTask);
1401 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001402 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001403 }
1404 }
1405
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001406 void bindRemainingSynchronousPages() {
1407 // Post the remaining side pages to be loaded
1408 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001409 Runnable[] deferredBindRunnables = null;
1410 synchronized (mDeferredBindRunnables) {
1411 deferredBindRunnables = mDeferredBindRunnables.toArray(
1412 new Runnable[mDeferredBindRunnables.size()]);
1413 mDeferredBindRunnables.clear();
1414 }
1415 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001416 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001417 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001418 }
1419 }
1420
Joe Onorato36115782010-06-17 13:28:48 -04001421 public void stopLoader() {
1422 synchronized (mLock) {
1423 if (mLoaderTask != null) {
1424 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001425 }
1426 }
Joe Onorato36115782010-06-17 13:28:48 -04001427 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001428
Winson Chung76828c82013-08-19 15:43:29 -07001429 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1430 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1431 final ContentResolver contentResolver = context.getContentResolver();
1432 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1433 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1434 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1435
1436 try {
1437 final int idIndex = sc.getColumnIndexOrThrow(
1438 LauncherSettings.WorkspaceScreens._ID);
1439 final int rankIndex = sc.getColumnIndexOrThrow(
1440 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1441 while (sc.moveToNext()) {
1442 try {
1443 long screenId = sc.getLong(idIndex);
1444 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001445 orderedScreens.put(rank, screenId);
1446 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001447 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001448 }
1449 }
1450 } finally {
1451 sc.close();
1452 }
Winson Chunga90303b2013-11-15 13:05:06 -08001453
1454 // Log to disk
1455 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1456 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1457 for (Integer i : orderedScreens.keySet()) {
1458 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1459 }
1460 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1461 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001462 return orderedScreens;
1463 }
1464
Michael Jurkac57b7a82011-08-09 22:02:20 -07001465 public boolean isAllAppsLoaded() {
1466 return mAllAppsLoaded;
1467 }
1468
Winson Chung36a62fe2012-05-06 18:04:42 -07001469 boolean isLoadingWorkspace() {
1470 synchronized (mLock) {
1471 if (mLoaderTask != null) {
1472 return mLoaderTask.isLoadingWorkspace();
1473 }
1474 }
1475 return false;
1476 }
1477
Joe Onorato36115782010-06-17 13:28:48 -04001478 /**
1479 * Runnable for the thread that loads the contents of the launcher:
1480 * - workspace icons
1481 * - widgets
1482 * - all apps icons
1483 */
1484 private class LoaderTask implements Runnable {
1485 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001486 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001487 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001488 private boolean mStopped;
1489 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001490 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001491
Winson Chungc3eecff2011-07-11 17:44:15 -07001492 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001493
Dan Sandlerd5024042014-01-09 15:01:33 -05001494 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001495 mContext = context;
1496 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001497 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001498 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001499 }
1500
Joe Onorato36115782010-06-17 13:28:48 -04001501 boolean isLaunching() {
1502 return mIsLaunching;
1503 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001504
Winson Chung36a62fe2012-05-06 18:04:42 -07001505 boolean isLoadingWorkspace() {
1506 return mIsLoadingAndBindingWorkspace;
1507 }
1508
Winson Chungc763c4e2013-07-19 13:49:06 -07001509 /** Returns whether this is an upgrade path */
1510 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001511 mIsLoadingAndBindingWorkspace = true;
1512
Joe Onorato36115782010-06-17 13:28:48 -04001513 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001514 if (DEBUG_LOADERS) {
1515 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001516 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001517
Winson Chungc763c4e2013-07-19 13:49:06 -07001518 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001519 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001520 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001521 synchronized (LoaderTask.this) {
1522 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001523 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001524 }
1525 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001526 }
1527 }
1528
Joe Onorato36115782010-06-17 13:28:48 -04001529 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001530 bindWorkspace(-1, isUpgradePath);
1531 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001532 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001533
Joe Onorato36115782010-06-17 13:28:48 -04001534 private void waitForIdle() {
1535 // Wait until the either we're stopped or the other threads are done.
1536 // This way we don't start loading all apps until the workspace has settled
1537 // down.
1538 synchronized (LoaderTask.this) {
1539 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001540
Joe Onorato36115782010-06-17 13:28:48 -04001541 mHandler.postIdle(new Runnable() {
1542 public void run() {
1543 synchronized (LoaderTask.this) {
1544 mLoadAndBindStepFinished = true;
1545 if (DEBUG_LOADERS) {
1546 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001547 }
Joe Onorato36115782010-06-17 13:28:48 -04001548 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001549 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001550 }
Joe Onorato36115782010-06-17 13:28:48 -04001551 });
1552
Michael Jurkac7700af2013-05-14 20:17:58 +02001553 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001554 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001555 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1556 // wait no longer than 1sec at a time
1557 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001558 } catch (InterruptedException ex) {
1559 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001560 }
1561 }
Joe Onorato36115782010-06-17 13:28:48 -04001562 if (DEBUG_LOADERS) {
1563 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001564 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001565 + "ms for previous step to finish binding");
1566 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001567 }
Joe Onorato36115782010-06-17 13:28:48 -04001568 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001569
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001570 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001571 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001572 // Ensure that we have a valid page index to load synchronously
1573 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1574 "valid page index");
1575 }
1576 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1577 // Ensure that we don't try and bind a specified page when the pages have not been
1578 // loaded already (we should load everything asynchronously in that case)
1579 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1580 }
1581 synchronized (mLock) {
1582 if (mIsLoaderTaskRunning) {
1583 // Ensure that we are never running the background loading at this point since
1584 // we also touch the background collections
1585 throw new RuntimeException("Error! Background loading is already running");
1586 }
1587 }
1588
1589 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1590 // data structures, we can't allow any other thread to touch that data, but because
1591 // this call is synchronous, we can get away with not locking).
1592
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001593 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001594 // operations from the previous activity. We need to ensure that all queued operations
1595 // are executed before any synchronous binding work is done.
1596 mHandler.flush();
1597
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001598 // Divide the set of loaded items into those that we are binding synchronously, and
1599 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001600 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001601 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1602 // arise from that.
1603 onlyBindAllApps();
1604 }
1605
Joe Onorato36115782010-06-17 13:28:48 -04001606 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001607 boolean isUpgrade = false;
1608
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001609 synchronized (mLock) {
1610 mIsLoaderTaskRunning = true;
1611 }
Joe Onorato36115782010-06-17 13:28:48 -04001612 // Optimize for end-user experience: if the Launcher is up and // running with the
1613 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1614 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001615 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001616 // Elevate priority when Home launches for the first time to avoid
1617 // starving at boot time. Staring at a blank home is not cool.
1618 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001619 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1620 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001621 android.os.Process.setThreadPriority(mIsLaunching
1622 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1623 }
Winson Chung64359a52013-07-08 17:17:08 -07001624 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001625 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001626
Joe Onorato36115782010-06-17 13:28:48 -04001627 if (mStopped) {
1628 break keep_running;
1629 }
1630
1631 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1632 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001633 synchronized (mLock) {
1634 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001635 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001636 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1637 }
1638 }
Joe Onorato36115782010-06-17 13:28:48 -04001639 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001640
1641 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001642 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1643 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001644
1645 // Restore the default thread priority after we are done loading items
1646 synchronized (mLock) {
1647 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1648 }
Joe Onorato36115782010-06-17 13:28:48 -04001649 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001650
Winson Chungaac01e12011-08-17 10:37:13 -07001651 // Update the saved icons if necessary
1652 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001653 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001654 for (Object key : sBgDbIconCache.keySet()) {
1655 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1656 }
1657 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001658 }
Winson Chungaac01e12011-08-17 10:37:13 -07001659
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001660 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001661 // Ensure that all the applications that are in the system are
1662 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001663 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001664 verifyApplications();
1665 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001666 }
1667
Joe Onorato36115782010-06-17 13:28:48 -04001668 // Clear out this reference, otherwise we end up holding it until all of the
1669 // callback runnables are done.
1670 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001671
Joe Onorato36115782010-06-17 13:28:48 -04001672 synchronized (mLock) {
1673 // If we are still the last one to be scheduled, remove ourselves.
1674 if (mLoaderTask == this) {
1675 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001676 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001677 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001678 }
Joe Onorato36115782010-06-17 13:28:48 -04001679 }
1680
1681 public void stopLocked() {
1682 synchronized (LoaderTask.this) {
1683 mStopped = true;
1684 this.notify();
1685 }
1686 }
1687
1688 /**
1689 * Gets the callbacks object. If we've been stopped, or if the launcher object
1690 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1691 * object that was around when the deferred message was scheduled, and if there's
1692 * a new Callbacks object around then also return null. This will save us from
1693 * calling onto it with data that will be ignored.
1694 */
1695 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1696 synchronized (mLock) {
1697 if (mStopped) {
1698 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001699 }
Joe Onorato36115782010-06-17 13:28:48 -04001700
1701 if (mCallbacks == null) {
1702 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001703 }
Joe Onorato36115782010-06-17 13:28:48 -04001704
1705 final Callbacks callbacks = mCallbacks.get();
1706 if (callbacks != oldCallbacks) {
1707 return null;
1708 }
1709 if (callbacks == null) {
1710 Log.w(TAG, "no mCallbacks");
1711 return null;
1712 }
1713
1714 return callbacks;
1715 }
1716 }
1717
Winson Chungc763c4e2013-07-19 13:49:06 -07001718 private void verifyApplications() {
1719 final Context context = mApp.getContext();
1720
1721 // Cross reference all the applications in our apps list with items in the workspace
1722 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001723 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001724 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001725 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001726 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001727 if (tmpInfos.isEmpty()) {
1728 // We are missing an application icon, so add this to the workspace
1729 added.add(app);
1730 // This is a rare event, so lets log it
1731 Log.e(TAG, "Missing Application on load: " + app);
1732 }
1733 }
1734 }
1735 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001736 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001737 }
1738 }
1739
Joe Onorato36115782010-06-17 13:28:48 -04001740 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001741 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001742 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001743 LauncherAppState app = LauncherAppState.getInstance();
1744 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001745 final int countX = (int) grid.numColumns;
1746 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001747
Adam Cohendcd297f2013-06-18 13:13:40 -07001748 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001749 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001750 // Return early if we detect that an item is under the hotseat button
1751 if (mCallbacks == null ||
1752 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001753 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001754 Log.e(TAG, "Error loading shortcut into hotseat " + item
1755 + " into position (" + item.screenId + ":" + item.cellX + ","
1756 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001757 return false;
1758 }
1759
Dan Sandler295ae182013-12-10 16:05:47 -05001760 final ItemInfo[][] hotseatItems =
1761 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1762
Adam Cohenae4409d2013-11-26 10:34:59 -08001763 if (item.screenId >= grid.numHotseatIcons) {
1764 Log.e(TAG, "Error loading shortcut " + item
1765 + " into hotseat position " + item.screenId
1766 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1767 + ")");
1768 return false;
1769 }
1770
Dan Sandler295ae182013-12-10 16:05:47 -05001771 if (hotseatItems != null) {
1772 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001773 Log.e(TAG, "Error loading shortcut into hotseat " + item
1774 + " into position (" + item.screenId + ":" + item.cellX + ","
1775 + item.cellY + ") occupied by "
1776 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1777 [(int) item.screenId][0]);
1778 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001779 } else {
1780 hotseatItems[(int) item.screenId][0] = item;
1781 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001782 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001783 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001784 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001785 items[(int) item.screenId][0] = item;
1786 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001787 return true;
1788 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001789 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1790 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001791 return true;
1792 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001793
Adam Cohendcd297f2013-06-18 13:13:40 -07001794 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001795 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001796 occupied.put(item.screenId, items);
1797 }
1798
Dan Sandler295ae182013-12-10 16:05:47 -05001799 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001800 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1801 item.cellX < 0 || item.cellY < 0 ||
1802 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1803 Log.e(TAG, "Error loading shortcut " + item
1804 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1805 + item.cellX + "," + item.cellY
1806 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1807 return false;
1808 }
1809
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001810 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001811 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1812 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001813 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001814 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001815 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001816 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001817 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001818 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001819 return false;
1820 }
1821 }
1822 }
1823 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1824 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001825 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001826 }
1827 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001828
Joe Onorato36115782010-06-17 13:28:48 -04001829 return true;
1830 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001831
Winson Chungba9c37f2013-08-30 14:11:37 -07001832 /** Clears all the sBg data structures */
1833 private void clearSBgDataStructures() {
1834 synchronized (sBgLock) {
1835 sBgWorkspaceItems.clear();
1836 sBgAppWidgets.clear();
1837 sBgFolders.clear();
1838 sBgItemsIdMap.clear();
1839 sBgDbIconCache.clear();
1840 sBgWorkspaceScreens.clear();
1841 }
1842 }
1843
Dan Sandlerd5024042014-01-09 15:01:33 -05001844 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001845 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001846 // Log to disk
1847 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1848
Joe Onorato36115782010-06-17 13:28:48 -04001849 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001850
Joe Onorato36115782010-06-17 13:28:48 -04001851 final Context context = mContext;
1852 final ContentResolver contentResolver = context.getContentResolver();
1853 final PackageManager manager = context.getPackageManager();
1854 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1855 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001856 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1857 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001858 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001859
Winson Chung892c74d2013-08-22 16:15:50 -07001860 LauncherAppState app = LauncherAppState.getInstance();
1861 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1862 int countX = (int) grid.numColumns;
1863 int countY = (int) grid.numRows;
1864
Dan Sandlerd5024042014-01-09 15:01:33 -05001865 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1866 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1867 LauncherAppState.getLauncherProvider().deleteDatabase();
1868 }
1869
1870 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1871 // append the user's Launcher2 shortcuts
1872 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1873 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1874 } else {
1875 // Make sure the default workspace is loaded
1876 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001877 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001878 }
Adam Cohene25af792013-06-06 23:08:25 -07001879
Adam Cohen71483f42014-05-15 14:04:01 -07001880 // This code path is for our old migration code and should no longer be exercised
1881 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001882
Winson Chung9f9f00b2013-11-15 13:27:00 -08001883 // Log to disk
1884 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001885
Winson Chung2abf94d2012-07-18 18:16:38 -07001886 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001887 clearSBgDataStructures();
Sunny Goyal34942622014-08-29 17:20:55 -07001888 PackageInstallerCompat.getInstance(mContext).updateActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001889
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001890 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001891 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001892 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001893 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001894 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001895
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001896 // +1 for the hotseat (it can be larger than the workspace)
1897 // Load workspace in reverse order to ensure that latest items are loaded first (and
1898 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001899 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001900
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001901 try {
1902 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1903 final int intentIndex = c.getColumnIndexOrThrow
1904 (LauncherSettings.Favorites.INTENT);
1905 final int titleIndex = c.getColumnIndexOrThrow
1906 (LauncherSettings.Favorites.TITLE);
1907 final int iconTypeIndex = c.getColumnIndexOrThrow(
1908 LauncherSettings.Favorites.ICON_TYPE);
1909 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1910 final int iconPackageIndex = c.getColumnIndexOrThrow(
1911 LauncherSettings.Favorites.ICON_PACKAGE);
1912 final int iconResourceIndex = c.getColumnIndexOrThrow(
1913 LauncherSettings.Favorites.ICON_RESOURCE);
1914 final int containerIndex = c.getColumnIndexOrThrow(
1915 LauncherSettings.Favorites.CONTAINER);
1916 final int itemTypeIndex = c.getColumnIndexOrThrow(
1917 LauncherSettings.Favorites.ITEM_TYPE);
1918 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1919 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001920 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1921 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001922 final int screenIndex = c.getColumnIndexOrThrow(
1923 LauncherSettings.Favorites.SCREEN);
1924 final int cellXIndex = c.getColumnIndexOrThrow
1925 (LauncherSettings.Favorites.CELLX);
1926 final int cellYIndex = c.getColumnIndexOrThrow
1927 (LauncherSettings.Favorites.CELLY);
1928 final int spanXIndex = c.getColumnIndexOrThrow
1929 (LauncherSettings.Favorites.SPANX);
1930 final int spanYIndex = c.getColumnIndexOrThrow(
1931 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001932 final int restoredIndex = c.getColumnIndexOrThrow(
1933 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001934 final int profileIdIndex = c.getColumnIndexOrThrow(
1935 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001936 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1937 //final int displayModeIndex = c.getColumnIndexOrThrow(
1938 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001939
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001940 ShortcutInfo info;
1941 String intentDescription;
1942 LauncherAppWidgetInfo appWidgetInfo;
1943 int container;
1944 long id;
1945 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001946 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001947
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001948 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001949 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 try {
1951 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001952 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001953 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001954
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001955 switch (itemType) {
1956 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1957 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001958 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001959 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001960 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001961 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001962 int promiseType = c.getInt(restoredIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001963 if (user == null) {
1964 // User has been deleted remove the item.
1965 itemsToRemove.add(id);
1966 continue;
1967 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001968 try {
1969 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001970 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001971 if (cn != null && cn.getPackageName() != null) {
1972 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1973 cn.getPackageName(), user);
1974 boolean validComponent = validPkg &&
1975 launcherApps.isActivityEnabledForProfile(cn, user);
1976
1977 if (validComponent) {
1978 if (restored) {
1979 // no special handling necessary for this item
1980 restoredRows.add(id);
1981 restored = false;
1982 }
1983 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001984 intent = null;
1985 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1986 // We allow auto install apps to have their intent
1987 // updated after an install.
1988 intent = manager.getLaunchIntentForPackage(
1989 cn.getPackageName());
1990 if (intent != null) {
1991 ContentValues values = new ContentValues();
1992 values.put(LauncherSettings.Favorites.INTENT,
1993 intent.toUri(0));
1994 String where = BaseColumns._ID + "= ?";
1995 String[] args = {Long.toString(id)};
1996 contentResolver.update(contentUri, values, where, args);
1997 }
1998 }
1999
2000 if (intent == null) {
2001 // The app is installed but the component is no
2002 // longer available.
2003 Launcher.addDumpLog(TAG,
2004 "Invalid component removed: " + cn, true);
2005 itemsToRemove.add(id);
2006 continue;
2007 } else {
2008 // no special handling necessary for this item
2009 restoredRows.add(id);
2010 restored = false;
2011 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002012 } else if (restored) {
2013 // Package is not yet available but might be
2014 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002015 Launcher.addDumpLog(TAG,
2016 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002017 } else if (isSdCardReady) {
2018 // Do not wait for external media load anymore.
2019 // Log the invalid package, and remove it
2020 Launcher.addDumpLog(TAG,
2021 "Invalid package removed: " + cn, true);
2022 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002023 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002024 } else {
2025 // SdCard is not ready yet. Package might get available,
2026 // once it is ready.
2027 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2028 + " (check again later)", true);
2029 HashSet<String> pkgs = sPendingPackages.get(user);
2030 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002031 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002032 sPendingPackages.put(user, pkgs);
2033 }
2034 pkgs.add(cn.getPackageName());
2035 allowMissingTarget = true;
2036 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002037 }
Winson Chungee055712013-07-30 14:46:24 -07002038 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002039 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002040 Launcher.addDumpLog(TAG,
2041 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 continue;
2043 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002044
Chris Wrenf4d08112014-01-16 18:13:56 -05002045 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002046 if (user.equals(UserHandleCompat.myUserHandle())) {
2047 Launcher.addDumpLog(TAG,
2048 "constructing info for partially restored package",
2049 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002050 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002051 intent = getRestoredItemIntent(c, context, intent);
2052 } else {
2053 // Don't restore items for other profiles.
2054 itemsToRemove.add(id);
2055 continue;
2056 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002057 } else if (itemType ==
2058 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002059 info = getShortcutInfo(manager, intent, user, context, c,
2060 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002061 } else {
2062 info = getShortcutInfo(c, context, iconTypeIndex,
2063 iconPackageIndex, iconResourceIndex, iconIndex,
2064 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002065
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 // App shortcuts that used to be automatically added to Launcher
2067 // didn't always have the correct intent flags set, so do that
2068 // here
2069 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002070 intent.getCategories() != null &&
2071 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002072 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002073 intent.addFlags(
2074 Intent.FLAG_ACTIVITY_NEW_TASK |
2075 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2076 }
Michael Jurka96879562012-03-22 05:54:33 -07002077 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002078
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002080 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002081 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 container = c.getInt(containerIndex);
2083 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002084 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 info.cellX = c.getInt(cellXIndex);
2086 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002087 info.spanX = 1;
2088 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002089 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002090 info.isDisabled = isSafeMode
2091 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002092
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002094 deleteOnInvalidPlacement.set(false);
2095 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2096 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002097 itemsToRemove.add(id);
2098 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 break;
2100 }
2101
2102 switch (container) {
2103 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2104 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2105 sBgWorkspaceItems.add(info);
2106 break;
2107 default:
2108 // Item is in a user folder
2109 FolderInfo folderInfo =
2110 findOrMakeFolder(sBgFolders, container);
2111 folderInfo.add(info);
2112 break;
2113 }
2114 sBgItemsIdMap.put(info.id, info);
2115
2116 // now that we've loaded everthing re-save it with the
2117 // icon in case it disappears somehow.
2118 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002119 } else {
2120 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 }
2122 break;
2123
2124 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2125 id = c.getLong(idIndex);
2126 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2127
2128 folderInfo.title = c.getString(titleIndex);
2129 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002130 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002132 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002133 folderInfo.cellX = c.getInt(cellXIndex);
2134 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002135 folderInfo.spanX = 1;
2136 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002137
Daniel Sandler8802e962010-05-26 16:28:16 -04002138 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002139 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002140 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002141 deleteOnInvalidPlacement)) {
2142 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002143 itemsToRemove.add(id);
2144 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002145 break;
2146 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002147
Joe Onorato9c1289c2009-08-17 11:03:03 -04002148 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2150 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2151 sBgWorkspaceItems.add(folderInfo);
2152 break;
Joe Onorato36115782010-06-17 13:28:48 -04002153 }
Joe Onorato17a89222011-02-08 17:26:11 -08002154
Chris Wrenf4d08112014-01-16 18:13:56 -05002155 if (restored) {
2156 // no special handling required for restored folders
2157 restoredRows.add(id);
2158 }
2159
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002160 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2161 sBgFolders.put(folderInfo.id, folderInfo);
2162 break;
2163
2164 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2165 // Read all Launcher-specific widget details
2166 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002167 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002168 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002169 final ComponentName component =
2170 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002171
Sunny Goyal651077b2014-06-30 14:15:31 -07002172 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002173 final boolean isIdValid = (restoreStatus &
2174 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002175
Sunny Goyalff572272014-07-23 13:58:07 -07002176 final boolean wasProviderReady = (restoreStatus &
2177 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002178
Sunny Goyalff572272014-07-23 13:58:07 -07002179 final AppWidgetProviderInfo provider = isIdValid
2180 ? widgets.getAppWidgetInfo(appWidgetId)
2181 : findAppWidgetProviderInfoWithComponent(context, component);
2182
2183 final boolean isProviderReady = isValidProvider(provider);
2184 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002185 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002186 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002188 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002189 itemsToRemove.add(id);
2190 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002191 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002192 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2193 provider.provider);
2194 int[] minSpan =
2195 Launcher.getMinSpanForWidget(context, provider);
2196 appWidgetInfo.minSpanX = minSpan[0];
2197 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002198
2199 int status = restoreStatus;
2200 if (!wasProviderReady) {
2201 // If provider was not previously ready, update the
2202 // status and UI flag.
2203
2204 // Id would be valid only if the widget restore broadcast was received.
2205 if (isIdValid) {
2206 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2207 } else {
2208 status &= ~LauncherAppWidgetInfo
2209 .FLAG_PROVIDER_NOT_READY;
2210 }
2211 }
2212 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002213 } else {
2214 Log.v(TAG, "Widget restore pending id=" + id
2215 + " appWidgetId=" + appWidgetId
2216 + " status =" + restoreStatus);
2217 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002218 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002219 appWidgetInfo.restoreStatus = restoreStatus;
2220 }
Sunny Goyalff572272014-07-23 13:58:07 -07002221
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002222 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002223 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002224 appWidgetInfo.cellX = c.getInt(cellXIndex);
2225 appWidgetInfo.cellY = c.getInt(cellYIndex);
2226 appWidgetInfo.spanX = c.getInt(spanXIndex);
2227 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002228
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002229 container = c.getInt(containerIndex);
2230 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2231 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2232 Log.e(TAG, "Widget found where container != " +
2233 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2234 continue;
2235 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002236
Adam Cohene25af792013-06-06 23:08:25 -07002237 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002238 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002239 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002240 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002241 deleteOnInvalidPlacement)) {
2242 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002243 itemsToRemove.add(id);
2244 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 break;
2246 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002247
Sunny Goyalff572272014-07-23 13:58:07 -07002248 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002249 String providerName = provider.provider.flattenToString();
Sunny Goyalff572272014-07-23 13:58:07 -07002250 if (!providerName.equals(savedProvider) ||
2251 (appWidgetInfo.restoreStatus != restoreStatus)) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002252 ContentValues values = new ContentValues();
2253 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2254 providerName);
2255 values.put(LauncherSettings.Favorites.RESTORED,
Sunny Goyalff572272014-07-23 13:58:07 -07002256 appWidgetInfo.restoreStatus);
Sunny Goyal651077b2014-06-30 14:15:31 -07002257 String where = BaseColumns._ID + "= ?";
2258 String[] args = {Long.toString(id)};
2259 contentResolver.update(contentUri, values, where, args);
2260 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002261 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2263 sBgAppWidgets.add(appWidgetInfo);
2264 }
Joe Onorato36115782010-06-17 13:28:48 -04002265 break;
2266 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002267 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002268 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002269 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002270 }
2271 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002272 if (c != null) {
2273 c.close();
2274 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 }
2276
Winson Chungba9c37f2013-08-30 14:11:37 -07002277 // Break early if we've stopped loading
2278 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002279 clearSBgDataStructures();
2280 return false;
2281 }
2282
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002283 if (itemsToRemove.size() > 0) {
2284 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002285 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002286 // Remove dead items
2287 for (long id : itemsToRemove) {
2288 if (DEBUG_LOADERS) {
2289 Log.d(TAG, "Removed id = " + id);
2290 }
2291 // Don't notify content observers
2292 try {
2293 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2294 null, null);
2295 } catch (RemoteException e) {
2296 Log.w(TAG, "Could not remove id = " + id);
2297 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002298 }
2299 }
2300
Chris Wrenf4d08112014-01-16 18:13:56 -05002301 if (restoredRows.size() > 0) {
2302 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2303 LauncherSettings.Favorites.CONTENT_URI);
2304 // Update restored items that no longer require special handling
2305 try {
2306 StringBuilder selectionBuilder = new StringBuilder();
2307 selectionBuilder.append(LauncherSettings.Favorites._ID);
2308 selectionBuilder.append(" IN (");
2309 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2310 selectionBuilder.append(")");
2311 ContentValues values = new ContentValues();
2312 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002313 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002314 values, selectionBuilder.toString(), null);
2315 } catch (RemoteException e) {
2316 Log.w(TAG, "Could not update restored rows");
2317 }
2318 }
2319
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002320 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2321 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002322 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002323 null, sWorker);
2324 }
2325
Winson Chungc763c4e2013-07-19 13:49:06 -07002326 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002327 long maxScreenId = 0;
2328 // If we're importing we use the old screen order.
2329 for (ItemInfo item: sBgItemsIdMap.values()) {
2330 long screenId = item.screenId;
2331 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2332 !sBgWorkspaceScreens.contains(screenId)) {
2333 sBgWorkspaceScreens.add(screenId);
2334 if (screenId > maxScreenId) {
2335 maxScreenId = screenId;
2336 }
2337 }
2338 }
2339 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002340 // Log to disk
2341 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2342 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2343 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002344
Michael Jurka414300a2013-08-27 15:42:35 +02002345 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002346 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002347
2348 // Update the max item id after we load an old db
2349 long maxItemId = 0;
2350 // If we're importing we use the old screen order.
2351 for (ItemInfo item: sBgItemsIdMap.values()) {
2352 maxItemId = Math.max(maxItemId, item.id);
2353 }
Michael Jurka414300a2013-08-27 15:42:35 +02002354 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002356 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2357 for (Integer i : orderedScreens.keySet()) {
2358 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002359 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002360 // Log to disk
2361 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2362 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002363
2364 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002365 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 for (ItemInfo item: sBgItemsIdMap.values()) {
2367 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002368 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2369 unusedScreens.contains(screenId)) {
2370 unusedScreens.remove(screenId);
2371 }
2372 }
2373
2374 // If there are any empty screens remove them, and update.
2375 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002376 // Log to disk
2377 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2378 TextUtils.join(", ", unusedScreens), true);
2379
Winson Chung933bae62013-08-29 11:42:30 -07002380 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002381 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2382 }
2383 }
2384
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002385 if (DEBUG_LOADERS) {
2386 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2387 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002388 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002389 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002390 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002391
Daniel Sandler566da102013-06-25 23:43:45 -04002392 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002393 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002394 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002395 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002396 line += " | ";
2397 }
Winson Chung892c74d2013-08-22 16:15:50 -07002398 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002399 ItemInfo[][] screen = occupied.get(screenId);
2400 if (x < screen.length && y < screen[x].length) {
2401 line += (screen[x][y] != null) ? "#" : ".";
2402 } else {
2403 line += "!";
2404 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002405 }
Joe Onorato36115782010-06-17 13:28:48 -04002406 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002407 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002408 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002409 }
Joe Onorato36115782010-06-17 13:28:48 -04002410 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002411 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002412 }
2413
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002414 /** Filters the set of items who are directly or indirectly (via another container) on the
2415 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002416 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002417 ArrayList<ItemInfo> allWorkspaceItems,
2418 ArrayList<ItemInfo> currentScreenItems,
2419 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002420 // Purge any null ItemInfos
2421 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2422 while (iter.hasNext()) {
2423 ItemInfo i = iter.next();
2424 if (i == null) {
2425 iter.remove();
2426 }
2427 }
2428
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 // Order the set of items by their containers first, this allows use to walk through the
2430 // list sequentially, build up a list of containers that are in the specified screen,
2431 // as well as all items in those containers.
2432 Set<Long> itemsOnScreen = new HashSet<Long>();
2433 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2434 @Override
2435 public int compare(ItemInfo lhs, ItemInfo rhs) {
2436 return (int) (lhs.container - rhs.container);
2437 }
2438 });
2439 for (ItemInfo info : allWorkspaceItems) {
2440 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002441 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002442 currentScreenItems.add(info);
2443 itemsOnScreen.add(info.id);
2444 } else {
2445 otherScreenItems.add(info);
2446 }
2447 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2448 currentScreenItems.add(info);
2449 itemsOnScreen.add(info.id);
2450 } else {
2451 if (itemsOnScreen.contains(info.container)) {
2452 currentScreenItems.add(info);
2453 itemsOnScreen.add(info.id);
2454 } else {
2455 otherScreenItems.add(info);
2456 }
2457 }
2458 }
2459 }
2460
2461 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002462 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002463 ArrayList<LauncherAppWidgetInfo> appWidgets,
2464 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2465 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466
2467 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002468 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002469 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002470 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471 currentScreenWidgets.add(widget);
2472 } else {
2473 otherScreenWidgets.add(widget);
2474 }
2475 }
2476 }
2477
2478 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002479 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 HashMap<Long, ItemInfo> itemsIdMap,
2481 HashMap<Long, FolderInfo> folders,
2482 HashMap<Long, FolderInfo> currentScreenFolders,
2483 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484
2485 for (long id : folders.keySet()) {
2486 ItemInfo info = itemsIdMap.get(id);
2487 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002488 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002490 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002491 currentScreenFolders.put(id, folder);
2492 } else {
2493 otherScreenFolders.put(id, folder);
2494 }
2495 }
2496 }
2497
2498 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2499 * right) */
2500 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002501 final LauncherAppState app = LauncherAppState.getInstance();
2502 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002503 // XXX: review this
2504 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002505 @Override
2506 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002507 int cellCountX = (int) grid.numColumns;
2508 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002509 int screenOffset = cellCountX * cellCountY;
2510 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002511 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002512 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002513 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002514 rhs.cellY * cellCountX + rhs.cellX);
2515 return (int) (lr - rr);
2516 }
2517 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002518 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002519
Adam Cohendcd297f2013-06-18 13:13:40 -07002520 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2521 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002522 final Runnable r = new Runnable() {
2523 @Override
2524 public void run() {
2525 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2526 if (callbacks != null) {
2527 callbacks.bindScreens(orderedScreens);
2528 }
2529 }
2530 };
2531 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2532 }
2533
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2535 final ArrayList<ItemInfo> workspaceItems,
2536 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2537 final HashMap<Long, FolderInfo> folders,
2538 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002539
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002540 final boolean postOnMainThread = (deferredBindRunnables != null);
2541
2542 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002543 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002545 final int start = i;
2546 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547 final Runnable r = new Runnable() {
2548 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002549 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002550 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002551 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002552 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2553 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002554 }
2555 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002556 };
2557 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002558 synchronized (deferredBindRunnables) {
2559 deferredBindRunnables.add(r);
2560 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002561 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002562 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002563 }
Joe Onorato36115782010-06-17 13:28:48 -04002564 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002565
2566 // Bind the folders
2567 if (!folders.isEmpty()) {
2568 final Runnable r = new Runnable() {
2569 public void run() {
2570 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2571 if (callbacks != null) {
2572 callbacks.bindFolders(folders);
2573 }
2574 }
2575 };
2576 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002577 synchronized (deferredBindRunnables) {
2578 deferredBindRunnables.add(r);
2579 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002580 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002581 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002582 }
2583 }
2584
2585 // Bind the widgets, one at a time
2586 N = appWidgets.size();
2587 for (int i = 0; i < N; i++) {
2588 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2589 final Runnable r = new Runnable() {
2590 public void run() {
2591 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2592 if (callbacks != null) {
2593 callbacks.bindAppWidget(widget);
2594 }
2595 }
2596 };
2597 if (postOnMainThread) {
2598 deferredBindRunnables.add(r);
2599 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002600 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 }
2602 }
2603 }
2604
2605 /**
2606 * Binds all loaded data to actual views on the main thread.
2607 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002608 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002609 final long t = SystemClock.uptimeMillis();
2610 Runnable r;
2611
2612 // Don't use these two variables in any of the callback runnables.
2613 // Otherwise we hold a reference to them.
2614 final Callbacks oldCallbacks = mCallbacks.get();
2615 if (oldCallbacks == null) {
2616 // This launcher has exited and nobody bothered to tell us. Just bail.
2617 Log.w(TAG, "LoaderTask running with no launcher");
2618 return;
2619 }
2620
Winson Chung9b9fb962013-11-15 15:39:34 -08002621 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002622 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2623 ArrayList<LauncherAppWidgetInfo> appWidgets =
2624 new ArrayList<LauncherAppWidgetInfo>();
2625 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2626 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002627 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002628 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002629 workspaceItems.addAll(sBgWorkspaceItems);
2630 appWidgets.addAll(sBgAppWidgets);
2631 folders.putAll(sBgFolders);
2632 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002633 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002634 }
2635
Derek Prothro7aff3992013-12-10 14:00:37 -05002636 final boolean isLoadingSynchronously =
2637 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002638 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002639 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002640 if (currScreen >= orderedScreenIds.size()) {
2641 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002642 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002643 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002644 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002645 final long currentScreenId = currentScreen < 0
2646 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002647
2648 // Load all the items that are on the current page first (and in the process, unbind
2649 // all the existing workspace items before we call startBinding() below.
2650 unbindWorkspaceItemsOnMainThread();
2651
2652 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2654 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2655 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2656 new ArrayList<LauncherAppWidgetInfo>();
2657 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2658 new ArrayList<LauncherAppWidgetInfo>();
2659 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2660 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2661
Winson Chung9b9fb962013-11-15 15:39:34 -08002662 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002664 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002665 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002666 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667 otherFolders);
2668 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2669 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2670
2671 // Tell the workspace that we're about to start binding items
2672 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002673 public void run() {
2674 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2675 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002676 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002677 }
2678 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002679 };
Winson Chung81b52252012-08-27 15:34:29 -07002680 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681
Adam Cohendcd297f2013-06-18 13:13:40 -07002682 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2683
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 // Load items on the current page
2685 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2686 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002687 if (isLoadingSynchronously) {
2688 r = new Runnable() {
2689 public void run() {
2690 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002691 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002692 callbacks.onPageBoundSynchronously(currentScreen);
2693 }
2694 }
2695 };
Winson Chung81b52252012-08-27 15:34:29 -07002696 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002697 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002698
Winson Chung4a2afa32012-07-19 14:53:05 -07002699 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2700 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002701 synchronized (mDeferredBindRunnables) {
2702 mDeferredBindRunnables.clear();
2703 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002704 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002705 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002706
2707 // Tell the workspace that we're done binding items
2708 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002709 public void run() {
2710 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2711 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002712 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002713 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002714
Winson Chung98e030b2012-05-07 16:01:11 -07002715 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002716 if (DEBUG_LOADERS) {
2717 Log.d(TAG, "bound workspace in "
2718 + (SystemClock.uptimeMillis()-t) + "ms");
2719 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002720
2721 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002722 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002723 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002724 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002725 synchronized (mDeferredBindRunnables) {
2726 mDeferredBindRunnables.add(r);
2727 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002728 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002729 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002730 }
Joe Onorato36115782010-06-17 13:28:48 -04002731 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002732
Joe Onorato36115782010-06-17 13:28:48 -04002733 private void loadAndBindAllApps() {
2734 if (DEBUG_LOADERS) {
2735 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2736 }
2737 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002738 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002739 synchronized (LoaderTask.this) {
2740 if (mStopped) {
2741 return;
2742 }
2743 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002744 }
Joe Onorato36115782010-06-17 13:28:48 -04002745 } else {
2746 onlyBindAllApps();
2747 }
2748 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002749
Joe Onorato36115782010-06-17 13:28:48 -04002750 private void onlyBindAllApps() {
2751 final Callbacks oldCallbacks = mCallbacks.get();
2752 if (oldCallbacks == null) {
2753 // This launcher has exited and nobody bothered to tell us. Just bail.
2754 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2755 return;
2756 }
2757
2758 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002759 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002760 final ArrayList<AppInfo> list
2761 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002762 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002763 public void run() {
2764 final long t = SystemClock.uptimeMillis();
2765 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2766 if (callbacks != null) {
2767 callbacks.bindAllApplications(list);
2768 }
2769 if (DEBUG_LOADERS) {
2770 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2771 + (SystemClock.uptimeMillis()-t) + "ms");
2772 }
2773 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002774 };
2775 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002776 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002777 r.run();
2778 } else {
2779 mHandler.post(r);
2780 }
Joe Onorato36115782010-06-17 13:28:48 -04002781 }
2782
Winson Chung64359a52013-07-08 17:17:08 -07002783 private void loadAllApps() {
2784 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002785
Joe Onorato36115782010-06-17 13:28:48 -04002786 final Callbacks oldCallbacks = mCallbacks.get();
2787 if (oldCallbacks == null) {
2788 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002789 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002790 return;
2791 }
2792
2793 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2794 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2795
Kenny Guyed131872014-04-30 03:02:21 +01002796 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2797
Winson Chung64359a52013-07-08 17:17:08 -07002798 // Clear the list of apps
2799 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002800 for (UserHandleCompat user : profiles) {
2801 // Query for the set of apps
2802 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2803 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2804 if (DEBUG_LOADERS) {
2805 Log.d(TAG, "getActivityList took "
2806 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2807 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2808 }
2809 // Fail if we don't have any apps
2810 if (apps == null || apps.isEmpty()) {
2811 return;
2812 }
2813 // Sort the applications by name
2814 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2815 Collections.sort(apps,
2816 new LauncherModel.ShortcutNameComparator(mLabelCache));
2817 if (DEBUG_LOADERS) {
2818 Log.d(TAG, "sort took "
2819 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2820 }
Joe Onorato36115782010-06-17 13:28:48 -04002821
Kenny Guyed131872014-04-30 03:02:21 +01002822 // Create the ApplicationInfos
2823 for (int i = 0; i < apps.size(); i++) {
2824 LauncherActivityInfoCompat app = apps.get(i);
2825 // This builds the icon bitmaps.
2826 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2827 }
Winson Chung64359a52013-07-08 17:17:08 -07002828 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002829 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002830 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2831 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002832
2833 // Post callback on main thread
2834 mHandler.post(new Runnable() {
2835 public void run() {
2836 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002837 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002838 if (callbacks != null) {
2839 callbacks.bindAllApplications(added);
2840 if (DEBUG_LOADERS) {
2841 Log.d(TAG, "bound " + added.size() + " apps in "
2842 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2843 }
2844 } else {
2845 Log.i(TAG, "not binding apps: no Launcher activity");
2846 }
2847 }
2848 });
2849
Joe Onorato36115782010-06-17 13:28:48 -04002850 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002851 Log.d(TAG, "Icons processed in "
2852 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002853 }
2854 }
2855
2856 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002857 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002858 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2859 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2860 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2861 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2862 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2863 }
Joe Onorato36115782010-06-17 13:28:48 -04002864 }
2865 }
2866
2867 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002868 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002869 }
2870
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002871 private class AppsAvailabilityCheck extends BroadcastReceiver {
2872
2873 @Override
2874 public void onReceive(Context context, Intent intent) {
2875 synchronized (sBgLock) {
2876 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2877 .getInstance(mApp.getContext());
2878 ArrayList<String> packagesRemoved;
2879 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2880 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002881 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002882 for (String pkg : entry.getValue()) {
2883 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2884 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2885 packagesRemoved.add(pkg);
2886 }
2887 }
2888 if (!packagesRemoved.isEmpty()) {
2889 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2890 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2891 }
2892 }
Sunny Goyal34942622014-08-29 17:20:55 -07002893 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002894 }
2895 }
2896 }
2897
Joe Onorato36115782010-06-17 13:28:48 -04002898 private class PackageUpdatedTask implements Runnable {
2899 int mOp;
2900 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002901 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002902
2903 public static final int OP_NONE = 0;
2904 public static final int OP_ADD = 1;
2905 public static final int OP_UPDATE = 2;
2906 public static final int OP_REMOVE = 3; // uninstlled
2907 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2908
2909
Kenny Guyed131872014-04-30 03:02:21 +01002910 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002911 mOp = op;
2912 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002913 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002914 }
2915
2916 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002917 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002918
2919 final String[] packages = mPackages;
2920 final int N = packages.length;
2921 switch (mOp) {
2922 case OP_ADD:
2923 for (int i=0; i<N; i++) {
2924 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002925 mIconCache.remove(packages[i], mUser);
2926 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002927 }
2928 break;
2929 case OP_UPDATE:
2930 for (int i=0; i<N; i++) {
2931 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002932 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002933 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002934 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002935 }
2936 break;
2937 case OP_REMOVE:
2938 case OP_UNAVAILABLE:
2939 for (int i=0; i<N; i++) {
2940 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002941 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002942 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002943 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002944 }
2945 break;
2946 }
2947
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002948 ArrayList<AppInfo> added = null;
2949 ArrayList<AppInfo> modified = null;
2950 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002951
Adam Cohen487f7dd2012-06-28 18:12:10 -07002952 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002953 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002954 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002955 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002956 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002957 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002958 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002959 }
Winson Chung5d55f332012-07-16 20:45:03 -07002960 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002961 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002962 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002963 }
2964
Joe Onorato36115782010-06-17 13:28:48 -04002965 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2966 if (callbacks == null) {
2967 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2968 return;
2969 }
2970
2971 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002972 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002973 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002974 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002975 addAndBindAddedWorkspaceApps(context, addedInfos);
2976 } else {
2977 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002978 }
Joe Onorato36115782010-06-17 13:28:48 -04002979 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002980
Joe Onorato36115782010-06-17 13:28:48 -04002981 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002982 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002983
2984 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002985 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002986 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002987 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002988 for (ItemInfo i : infos) {
2989 if (isShortcutInfoUpdateable(i)) {
2990 ShortcutInfo info = (ShortcutInfo) i;
2991 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002992 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002993 updateItemInDatabase(context, info);
2994 }
2995 }
2996 }
2997
Joe Onorato36115782010-06-17 13:28:48 -04002998 mHandler.post(new Runnable() {
2999 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003000 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3001 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003002 callbacks.bindAppsUpdated(modifiedFinal);
3003 }
3004 }
3005 });
3006 }
Winson Chung83892cc2013-05-01 16:53:33 -07003007
Winson Chungdf95eb12013-10-16 14:57:07 -07003008 final ArrayList<String> removedPackageNames =
3009 new ArrayList<String>();
3010 if (mOp == OP_REMOVE) {
3011 // Mark all packages in the broadcast to be removed
3012 removedPackageNames.addAll(Arrays.asList(packages));
3013 } else if (mOp == OP_UPDATE) {
3014 // Mark disabled packages in the broadcast to be removed
3015 final PackageManager pm = context.getPackageManager();
3016 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003017 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003018 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003019 }
3020 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003021 }
3022 // Remove all the components associated with this package
3023 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003024 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003025 }
3026 // Remove all the specific components
3027 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003028 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003029 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003030 }
3031 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3032 // Remove any queued items from the install queue
3033 String spKey = LauncherAppState.getSharedPreferencesKey();
3034 SharedPreferences sp =
3035 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3036 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3037 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003038 mHandler.post(new Runnable() {
3039 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003040 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3041 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003042 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003043 }
3044 }
3045 });
Joe Onoratobe386092009-11-17 17:32:16 -08003046 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003047
Michael Jurkac402cd92013-05-20 15:49:32 +02003048 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003049 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003050 mHandler.post(new Runnable() {
3051 @Override
3052 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003053 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3054 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003055 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003056 }
3057 }
3058 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003059
3060 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003061 mHandler.post(new Runnable() {
3062 public void run() {
3063 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3064 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003065 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003066 }
3067 }
3068 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003069 }
3070 }
3071
Michael Jurkac402cd92013-05-20 15:49:32 +02003072 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3073 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3074 PackageManager packageManager = context.getPackageManager();
3075 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003076 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3077
Michael Jurkac402cd92013-05-20 15:49:32 +02003078 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3079 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003080 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003081 return widgetsAndShortcuts;
3082 }
3083
Kenny Guyed131872014-04-30 03:02:21 +01003084 private static boolean isPackageDisabled(Context context, String packageName,
3085 UserHandleCompat user) {
3086 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3087 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003088 }
Adam Cohen556f6132014-01-15 15:18:08 -08003089
Kenny Guyed131872014-04-30 03:02:21 +01003090 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3091 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003092 if (cn == null) {
3093 return false;
3094 }
Kenny Guyed131872014-04-30 03:02:21 +01003095 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3096 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003097 return false;
3098 }
Kenny Guyed131872014-04-30 03:02:21 +01003099 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003100 }
3101
Adam Cohena28b78e2014-05-20 17:03:04 -07003102 public static boolean isValidPackage(Context context, String packageName,
3103 UserHandleCompat user) {
3104 if (packageName == null) {
3105 return false;
3106 }
3107 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3108 return launcherApps.isPackageEnabledForProfile(packageName, user);
3109 }
3110
Joe Onorato9c1289c2009-08-17 11:03:03 -04003111 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003112 * Make an ShortcutInfo object for a restored application or shortcut item that points
3113 * to a package that is not yet installed on the system.
3114 */
Sunny Goyal34942622014-08-29 17:20:55 -07003115 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3116 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003117 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003118 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003119 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3120
3121 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3122 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3123 if (!TextUtils.isEmpty(title)) {
3124 info.title = title;
3125 }
3126 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3127 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3128 if (TextUtils.isEmpty(info.title)) {
3129 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3130 }
3131 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3132 } else {
3133 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3134 }
3135
Kenny Guyc2bd8102014-06-30 12:30:31 +01003136 info.contentDescription = mUserManager.getBadgedLabelForUser(
3137 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003138 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003139 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003140 return info;
3141 }
3142
3143 /**
3144 * Make an Intent object for a restored application or shortcut item that points
3145 * to the market page for the item.
3146 */
3147 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3148 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003149 return getMarketIntent(componentName.getPackageName());
3150 }
3151
3152 static Intent getMarketIntent(String packageName) {
3153 return new Intent(Intent.ACTION_VIEW)
3154 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003155 .scheme("market")
3156 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003157 .appendQueryParameter("id", packageName)
3158 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003159 }
3160
3161 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003162 * This is called from the code that adds shortcuts from the intent receiver. This
3163 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003164 */
Kenny Guyed131872014-04-30 03:02:21 +01003165 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3166 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003167 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003168 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003169
Joe Onorato56d82912010-03-07 14:32:10 -05003170 /**
3171 * Make an ShortcutInfo object for a shortcut that is an application.
3172 *
3173 * If c is not null, then it will be used to fill in missing data like the title and icon.
3174 */
Kenny Guyed131872014-04-30 03:02:21 +01003175 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3176 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003177 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003178 if (user == null) {
3179 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003180 return null;
3181 }
3182
Kenny Guyed131872014-04-30 03:02:21 +01003183 ComponentName componentName = intent.getComponent();
3184 if (componentName == null) {
3185 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3186 return null;
3187 }
3188
3189 Intent newIntent = new Intent(intent.getAction(), null);
3190 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3191 newIntent.setComponent(componentName);
3192 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003193 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003194 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3195 return null;
3196 }
3197
3198 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003199
Joe Onorato56d82912010-03-07 14:32:10 -05003200 // the resource -- This may implicitly give us back the fallback icon,
3201 // but don't worry about that. All we're doing with usingFallbackIcon is
3202 // to avoid saving lots of copies of that in the database, and most apps
3203 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003204 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003205
Joe Onorato56d82912010-03-07 14:32:10 -05003206 // the db
3207 if (icon == null) {
3208 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003209 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003210 }
3211 }
3212 // the fallback icon
3213 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003214 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003215 info.usingFallbackIcon = true;
3216 }
3217 info.setIcon(icon);
3218
Kenny Guyed131872014-04-30 03:02:21 +01003219 // From the cache.
3220 if (labelCache != null) {
3221 info.title = labelCache.get(componentName);
3222 }
3223
Joe Onorato56d82912010-03-07 14:32:10 -05003224 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003225 if (info.title == null && lai != null) {
3226 info.title = lai.getLabel();
3227 if (labelCache != null) {
3228 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003229 }
Joe Onorato56d82912010-03-07 14:32:10 -05003230 }
3231 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003232 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003233 if (c != null) {
3234 info.title = c.getString(titleIndex);
3235 }
3236 }
3237 // fall back to the class name of the activity
3238 if (info.title == null) {
3239 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003240 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003241 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003242 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003243 info.contentDescription = mUserManager.getBadgedLabelForUser(
3244 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003245 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003246 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003247
Winson Chung64359a52013-07-08 17:17:08 -07003248 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3249 ItemInfoFilter f) {
3250 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3251 for (ItemInfo i : infos) {
3252 if (i instanceof ShortcutInfo) {
3253 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003254 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003255 if (cn != null && f.filterItem(null, info, cn)) {
3256 filtered.add(info);
3257 }
3258 } else if (i instanceof FolderInfo) {
3259 FolderInfo info = (FolderInfo) i;
3260 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003261 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003262 if (cn != null && f.filterItem(info, s, cn)) {
3263 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003264 }
3265 }
Winson Chung64359a52013-07-08 17:17:08 -07003266 } else if (i instanceof LauncherAppWidgetInfo) {
3267 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3268 ComponentName cn = info.providerName;
3269 if (cn != null && f.filterItem(null, info, cn)) {
3270 filtered.add(info);
3271 }
Winson Chung8a435102012-08-30 17:16:53 -07003272 }
3273 }
Winson Chung64359a52013-07-08 17:17:08 -07003274 return new ArrayList<ItemInfo>(filtered);
3275 }
3276
Kenny Guyed131872014-04-30 03:02:21 +01003277 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3278 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003279 ItemInfoFilter filter = new ItemInfoFilter() {
3280 @Override
3281 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003282 if (info.user == null) {
3283 return cn.equals(cname);
3284 } else {
3285 return cn.equals(cname) && info.user.equals(user);
3286 }
Winson Chung64359a52013-07-08 17:17:08 -07003287 }
3288 };
3289 return filterItemInfos(sBgItemsIdMap.values(), filter);
3290 }
3291
3292 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3293 if (i instanceof ShortcutInfo) {
3294 ShortcutInfo info = (ShortcutInfo) i;
3295 // We need to check for ACTION_MAIN otherwise getComponent() might
3296 // return null for some shortcuts (for instance, for shortcuts to
3297 // web pages.)
3298 Intent intent = info.intent;
3299 ComponentName name = intent.getComponent();
3300 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3301 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3302 return true;
3303 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003304 // placeholder shortcuts get special treatment, let them through too.
Sunny Goyal34942622014-08-29 17:20:55 -07003305 if (info.isPromise()) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003306 return true;
3307 }
Winson Chung64359a52013-07-08 17:17:08 -07003308 }
3309 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003310 }
3311
3312 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003313 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003314 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003315 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003316 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3317 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003318
Joe Onorato56d82912010-03-07 14:32:10 -05003319 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003320 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003321 // Non-app shortcuts are only supported for current user.
3322 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003323 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003324
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003325 // TODO: If there's an explicit component and we can't install that, delete it.
3326
Joe Onorato56d82912010-03-07 14:32:10 -05003327 info.title = c.getString(titleIndex);
3328
Joe Onorato9c1289c2009-08-17 11:03:03 -04003329 int iconType = c.getInt(iconTypeIndex);
3330 switch (iconType) {
3331 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3332 String packageName = c.getString(iconPackageIndex);
3333 String resourceName = c.getString(iconResourceIndex);
3334 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003335 info.customIcon = false;
3336 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003337 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003338 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003339 if (resources != null) {
3340 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003341 icon = Utilities.createIconBitmap(
3342 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003343 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003344 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003345 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003346 }
Joe Onorato56d82912010-03-07 14:32:10 -05003347 // the db
3348 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003349 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003350 }
3351 // the fallback icon
3352 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003353 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003354 info.usingFallbackIcon = true;
3355 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003356 break;
3357 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003358 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003359 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003360 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003361 info.customIcon = false;
3362 info.usingFallbackIcon = true;
3363 } else {
3364 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003365 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003366 break;
3367 default:
Kenny Guyed131872014-04-30 03:02:21 +01003368 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003369 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003370 info.customIcon = false;
3371 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003372 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003373 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003374 return info;
3375 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003376
Michael Jurka931dc972011-08-05 15:08:15 -07003377 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003378 @SuppressWarnings("all") // suppress dead code warning
3379 final boolean debug = false;
3380 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003381 Log.d(TAG, "getIconFromCursor app="
3382 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3383 }
3384 byte[] data = c.getBlob(iconIndex);
3385 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003386 return Utilities.createIconBitmap(
3387 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003388 } catch (Exception e) {
3389 return null;
3390 }
3391 }
3392
Winson Chung3d503fb2011-07-13 17:25:49 -07003393 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3394 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003395 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003396 if (info == null) {
3397 return null;
3398 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003399 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003400
3401 return info;
3402 }
3403
Winson Chunga9abd0e2010-10-27 17:18:37 -07003404 /**
Winson Chung55cef262010-10-28 14:14:18 -07003405 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3406 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003407 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003408 ComponentName component) {
3409 List<AppWidgetProviderInfo> widgets =
3410 AppWidgetManager.getInstance(context).getInstalledProviders();
3411 for (AppWidgetProviderInfo info : widgets) {
3412 if (info.provider.equals(component)) {
3413 return info;
3414 }
3415 }
3416 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003417 }
3418
3419 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003420 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3421 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3422 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3423
Adam Cohend9198822011-11-22 16:42:47 -08003424 if (intent == null) {
3425 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3426 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3427 return null;
3428 }
3429
Joe Onorato0589f0f2010-02-08 13:44:00 -08003430 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003431 boolean customIcon = false;
3432 ShortcutIconResource iconResource = null;
3433
3434 if (bitmap != null && bitmap instanceof Bitmap) {
3435 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003436 customIcon = true;
3437 } else {
3438 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3439 if (extra != null && extra instanceof ShortcutIconResource) {
3440 try {
3441 iconResource = (ShortcutIconResource) extra;
3442 final PackageManager packageManager = context.getPackageManager();
3443 Resources resources = packageManager.getResourcesForApplication(
3444 iconResource.packageName);
3445 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003446 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003447 mIconCache.getFullResIcon(resources, id),
3448 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003449 } catch (Exception e) {
3450 Log.w(TAG, "Could not load shortcut icon: " + extra);
3451 }
3452 }
3453 }
3454
Michael Jurkac9d95c52011-08-29 14:03:34 -07003455 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003456
Kenny Guyed131872014-04-30 03:02:21 +01003457 // Only support intents for current user for now. Intents sent from other
3458 // users wouldn't get here without intent forwarding anyway.
3459 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003460 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003461 if (fallbackIcon != null) {
3462 icon = fallbackIcon;
3463 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003464 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003465 info.usingFallbackIcon = true;
3466 }
Joe Onorato56d82912010-03-07 14:32:10 -05003467 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003468 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003469
Joe Onorato0589f0f2010-02-08 13:44:00 -08003470 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003471 info.contentDescription = mUserManager.getBadgedLabelForUser(
3472 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003473 info.intent = intent;
3474 info.customIcon = customIcon;
3475 info.iconResource = iconResource;
3476
3477 return info;
3478 }
3479
Winson Chungaac01e12011-08-17 10:37:13 -07003480 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3481 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003482 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003483 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003484 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003485 }
Joe Onorato56d82912010-03-07 14:32:10 -05003486 // If this icon doesn't have a custom icon, check to see
3487 // what's stored in the DB, and if it doesn't match what
3488 // we're going to show, store what we are going to show back
3489 // into the DB. We do this so when we're loading, if the
3490 // package manager can't find an icon (for example because
3491 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003492 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003493 cache.put(info, c.getBlob(iconIndex));
3494 return true;
3495 }
3496 return false;
3497 }
3498 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3499 boolean needSave = false;
3500 try {
3501 if (data != null) {
3502 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3503 Bitmap loaded = info.getIcon(mIconCache);
3504 needSave = !saved.sameAs(loaded);
3505 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003506 needSave = true;
3507 }
Winson Chungaac01e12011-08-17 10:37:13 -07003508 } catch (Exception e) {
3509 needSave = true;
3510 }
3511 if (needSave) {
3512 Log.d(TAG, "going to save icon bitmap for info=" + info);
3513 // This is slower than is ideal, but this only happens once
3514 // or when the app is updated with a new icon.
3515 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003516 }
3517 }
3518
Joe Onorato9c1289c2009-08-17 11:03:03 -04003519 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003520 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003521 * or make a new one.
3522 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003523 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003524 // See if a placeholder was created for us already
3525 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003526 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003527 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003528 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003529 folders.put(id, folderInfo);
3530 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003531 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003532 }
3533
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003534 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003535 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003536 return new Comparator<AppInfo>() {
3537 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003538 if (a.user.equals(b.user)) {
3539 int result = collator.compare(a.title.toString().trim(),
3540 b.title.toString().trim());
3541 if (result == 0) {
3542 result = a.componentName.compareTo(b.componentName);
3543 }
3544 return result;
3545 } else {
3546 // TODO Need to figure out rules for sorting
3547 // profiles, this puts work second.
3548 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003549 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003550 }
Winson Chung11904872012-09-17 16:58:46 -07003551 };
3552 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003553 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3554 = new Comparator<AppInfo>() {
3555 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003556 if (a.firstInstallTime < b.firstInstallTime) return 1;
3557 if (a.firstInstallTime > b.firstInstallTime) return -1;
3558 return 0;
3559 }
3560 };
Winson Chung5308f242011-08-18 12:12:41 -07003561 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3562 if (info.activityInfo != null) {
3563 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3564 } else {
3565 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3566 }
3567 }
Kenny Guyed131872014-04-30 03:02:21 +01003568 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003569 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003570 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003571 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003572 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003573 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003574 }
Kenny Guyed131872014-04-30 03:02:21 +01003575 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003576 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003577 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003578 }
Kenny Guyed131872014-04-30 03:02:21 +01003579 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003580 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003581 ComponentName keyA = a.getComponentName();
3582 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003583 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003584 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003585 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003586 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003587
Winson Chung5308f242011-08-18 12:12:41 -07003588 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003589 }
Winson Chung5308f242011-08-18 12:12:41 -07003590 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003591 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003592 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003593 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003594
Winson Chung5308f242011-08-18 12:12:41 -07003595 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003596 }
Winson Chung11904872012-09-17 16:58:46 -07003597 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003598 }
3599 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003600 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003601 private final AppWidgetManagerCompat mManager;
3602 private final PackageManager mPackageManager;
3603 private final HashMap<Object, String> mLabelCache;
3604 private final Collator mCollator;
3605
3606 WidgetAndShortcutNameComparator(Context context) {
3607 mManager = AppWidgetManagerCompat.getInstance(context);
3608 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003609 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003610 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003611 }
3612 public final int compare(Object a, Object b) {
3613 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003614 if (mLabelCache.containsKey(a)) {
3615 labelA = mLabelCache.get(a);
3616 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003617 labelA = (a instanceof AppWidgetProviderInfo)
3618 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3619 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003620 mLabelCache.put(a, labelA);
3621 }
3622 if (mLabelCache.containsKey(b)) {
3623 labelB = mLabelCache.get(b);
3624 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003625 labelB = (b instanceof AppWidgetProviderInfo)
3626 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3627 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003628 mLabelCache.put(b, labelB);
3629 }
Winson Chung11904872012-09-17 16:58:46 -07003630 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003631 }
3632 };
Joe Onoratobe386092009-11-17 17:32:16 -08003633
Sunny Goyal651077b2014-06-30 14:15:31 -07003634 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3635 return (provider != null) && (provider.provider != null)
3636 && (provider.provider.getPackageName() != null);
3637 }
3638
Joe Onoratobe386092009-11-17 17:32:16 -08003639 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003640 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003641 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3642 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3643 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3644 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003645 if (mLoaderTask != null) {
3646 mLoaderTask.dumpState();
3647 } else {
3648 Log.d(TAG, "mLoaderTask=null");
3649 }
Joe Onoratobe386092009-11-17 17:32:16 -08003650 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003651}