blob: 550535edd7a82fe5199bd7b56d48945cf1922f7d [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 Wrenee523362014-09-09 10:09:02 -040088 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070089 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Chris Wrenb358f812014-04-16 13:37:00 -040090
Joe Onorato9c1289c2009-08-17 11:03:03 -040091 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070092
Daniel Sandler8707e0f2013-08-15 15:54:18 -070093 // true = use a "More Apps" folder for non-workspace apps on upgrade
94 // false = strew non-workspace apps across the workspace on upgrade
95 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050096 public static final int LOADER_FLAG_NONE = 0;
97 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
98 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
99
Joe Onorato36115782010-06-17 13:28:48 -0400100 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500101 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800102
Winson Chungee055712013-07-30 14:46:24 -0700103 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800104 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400105
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400106 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400107 private final Object mLock = new Object();
108 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400109 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700110 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200111 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Winson Chung81b52252012-08-27 15:34:29 -0700113 // Specific runnable types that are run on the main thread deferred handler, this allows us to
114 // clear all queued binding runnables when the Launcher activity is destroyed.
115 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
116 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
117
Jason Monkbbe1e242014-05-16 17:37:34 -0400118 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700119
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700120 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
121 static {
122 sWorkerThread.start();
123 }
124 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
125
Joe Onoratocc67f472010-06-08 10:54:30 -0700126 // We start off with everything not loaded. After that, we assume that
127 // our monitoring of the package manager provides all updates and we never
128 // need to do a requery. These are only ever touched from the loader thread.
129 private boolean mWorkspaceLoaded;
130 private boolean mAllAppsLoaded;
131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // When we are loading pages synchronously, we can't just post the binding of items on the side
133 // pages as this delays the rotation process. Instead, we wait for a callback from the first
134 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
135 // a normal load, we also clear this set of Runnables.
136 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
137
Joe Onorato9c1289c2009-08-17 11:03:03 -0400138 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700141 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800142
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700143 // The lock that must be acquired before referencing any static bg data structures. Unlike
144 // other locks, this one can generally be held long-term because we never expect any of these
145 // static data structures to be referenced outside of the worker thread except on the first
146 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700147 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
154 // created by LauncherModel that are directly on the home screen (however, no widgets or
155 // shortcuts within folders).
156 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
159 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 new ArrayList<LauncherAppWidgetInfo>();
161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
163 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700164
Adam Cohen487f7dd2012-06-28 18:12:10 -0700165 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
166 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700167
168 // sBgWorkspaceScreens is the ordered set of workspace screens.
169 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
170
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700172 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
173 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700174
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 // </ only access in worker thread >
176
177 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
Reena Lee99a73f32011-10-24 17:27:37 -0700179 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700180
Kenny Guyed131872014-04-30 03:02:21 +0100181 private final LauncherAppsCompat mLauncherApps;
182 private final UserManagerCompat mUserManager;
183
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700185 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public int getCurrentWorkspaceScreen();
187 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
189 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700190 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700191 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500192 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700193 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200195 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700196 public void bindAppsAdded(ArrayList<Long> newScreens,
197 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700198 ArrayList<ItemInfo> addAnimated,
199 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200200 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyale755d462014-07-22 13:48:29 -0700201 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700202 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700203 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100204 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200205 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100206 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700207 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700208 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700209 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400210 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211
Winson Chung64359a52013-07-08 17:17:08 -0700212 public interface ItemInfoFilter {
213 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
214 }
215
Bjorn Bringert1307f632013-10-03 22:31:03 +0100216 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800217 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400218
Winson Chungee055712013-07-30 14:46:24 -0700219 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700220 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400221 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
222 // resource string.
223 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
224 ProviderInfo providerInfo =
225 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
226 ProviderInfo redirectProvider =
227 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700228
229 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400230 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700231
232 if (mOldContentProviderExists) {
233 Log.d(TAG, "Old launcher provider exists.");
234 } else {
235 Log.d(TAG, "Old launcher provider does not exist.");
236 }
237
Daniel Sandlere4f98912013-06-25 15:13:26 -0400238 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100239 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800240 mIconCache = iconCache;
241
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400242 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700243 Configuration config = res.getConfiguration();
244 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100245 mLauncherApps = LauncherAppsCompat.getInstance(context);
246 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800247 }
248
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700249 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
250 * posted on the main thread handler. */
251 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700252 runOnMainThread(r, 0);
253 }
254 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700255 if (sWorkerThread.getThreadId() == Process.myTid()) {
256 // If we are on the worker thread, post onto the main handler
257 mHandler.post(r);
258 } else {
259 r.run();
260 }
261 }
262
263 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
264 * posted on the worker thread handler. */
265 private static void runOnWorkerThread(Runnable r) {
266 if (sWorkerThread.getThreadId() == Process.myTid()) {
267 r.run();
268 } else {
269 // If we are not on the worker thread, then post to the worker handler
270 sWorker.post(r);
271 }
272 }
273
Winson Chunge43a1e72014-01-15 10:33:02 -0800274 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
275 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800276 }
277
Winson Chungc9168342013-06-26 14:54:55 -0700278 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
279 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700280 LauncherAppState app = LauncherAppState.getInstance();
281 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
282 final int xCount = (int) grid.numColumns;
283 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700284 boolean[][] occupied = new boolean[xCount][yCount];
285
286 int cellX, cellY, spanX, spanY;
287 for (int i = 0; i < items.size(); ++i) {
288 final ItemInfo item = items.get(i);
289 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
290 if (item.screenId == screen) {
291 cellX = item.cellX;
292 cellY = item.cellY;
293 spanX = item.spanX;
294 spanY = item.spanY;
295 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
296 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
297 occupied[x][y] = true;
298 }
299 }
300 }
301 }
302 }
303
304 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
305 }
306 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700307 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700308 int firstScreenIndex,
309 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700310 // Lock on the app so that we don't try and get the items while apps are being added
311 LauncherAppState app = LauncherAppState.getInstance();
312 LauncherModel model = app.getModel();
313 boolean found = false;
314 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700315 if (sWorkerThread.getThreadId() != Process.myTid()) {
316 // Flush the LauncherModel worker thread, so that if we just did another
317 // processInstallShortcut, we give it time for its shortcut to get added to the
318 // database (getItemsInLocalCoordinates reads the database)
319 model.flushWorkerThread();
320 }
Winson Chungc9168342013-06-26 14:54:55 -0700321 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700322
323 // Try adding to the workspace screens incrementally, starting at the default or center
324 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700325 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
326 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700327 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700328 int[] tmpCoordinates = new int[2];
329 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700330 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700331 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700332 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700333 }
334 }
335 }
Winson Chungc9168342013-06-26 14:54:55 -0700336 return null;
337 }
338
Sunny Goyale755d462014-07-22 13:48:29 -0700339 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500340 // Process the updated package state
341 Runnable r = new Runnable() {
342 public void run() {
343 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
344 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700345 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500346 }
347 }
348 };
349 mHandler.post(r);
350 }
351
Sunny Goyala22666f2014-09-18 13:25:15 -0700352 public void updatePackageBadge(final String packageName) {
353 // Process the updated package badge
354 Runnable r = new Runnable() {
355 public void run() {
356 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
357 if (callbacks != null) {
358 callbacks.updatePackageBadge(packageName);
359 }
360 }
361 };
362 mHandler.post(r);
363 }
364
Adam Cohen76a47a12014-02-05 11:47:43 -0800365 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
366 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
367
368 if (allAppsApps == null) {
369 throw new RuntimeException("allAppsApps must not be null");
370 }
371 if (allAppsApps.isEmpty()) {
372 return;
373 }
374
Chris Wrenb6d4c282014-01-27 14:17:08 -0500375 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
376 Iterator<AppInfo> iter = allAppsApps.iterator();
377 while (iter.hasNext()) {
378 ItemInfo a = iter.next();
Sunny Goyal34942622014-08-29 17:20:55 -0700379 if (LauncherModel.appWasPromise(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500380 restoredAppsFinal.add((AppInfo) a);
381 }
382 }
383
Adam Cohen76a47a12014-02-05 11:47:43 -0800384 // Process the newly added applications and add them to the database first
385 Runnable r = new Runnable() {
386 public void run() {
387 runOnMainThread(new Runnable() {
388 public void run() {
389 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
390 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500391 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500392 for (AppInfo info : restoredAppsFinal) {
393 final Intent intent = info.getIntent();
394 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100395 mIconCache.deletePreloadedIcon(intent.getComponent(),
396 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500397 }
398 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500399 callbacks.bindAppsUpdated(restoredAppsFinal);
400 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500401 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800402 }
403 }
404 });
405 }
406 };
407 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700408 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800409
410 public void addAndBindAddedWorkspaceApps(final Context context,
411 final ArrayList<ItemInfo> workspaceApps) {
412 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
413
414 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800415 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
416 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800417 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700418 return;
Winson Chung997a9232013-07-24 15:33:46 -0700419 }
Winson Chung64359a52013-07-08 17:17:08 -0700420 // Process the newly added applications and add them to the database first
421 Runnable r = new Runnable() {
422 public void run() {
423 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
424 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500425 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700426
Winson Chung76828c82013-08-19 15:43:29 -0700427 // Get the list of workspace screens. We need to append to this list and
428 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
429 // called.
430 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
431 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
432 for (Integer i : orderedScreens.keySet()) {
433 long screenId = orderedScreens.get(i);
434 workspaceScreens.add(screenId);
435 }
436
Winson Chung64359a52013-07-08 17:17:08 -0700437 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700438 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700439 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700440 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700441 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700442 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700443
444 // Short-circuit this logic if the icon exists somewhere on the workspace
445 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500446 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
447 if (a instanceof AppInfo &&
Sunny Goyal34942622014-08-29 17:20:55 -0700448 LauncherModel.appWasPromise(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500449 restoredAppsFinal.add((AppInfo) a);
450 }
Winson Chung64359a52013-07-08 17:17:08 -0700451 continue;
452 }
453
Winson Chung87412982013-10-03 18:34:14 -0700454 // Add this icon to the db, creating a new page if necessary. If there
455 // is only the empty page then we just add items to the first page.
456 // Otherwise, we add them to the next pages.
457 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700458 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700459 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700460 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200461 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700462
463 // If we can't find a valid position, then just add a new screen.
464 // This takes time so we need to re-queue the add until the new
465 // page is added. Create as many screens as necessary to satisfy
466 // the startSearchPageIndex.
467 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700468 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700469 while (numPagesToAdd > 0) {
470 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700471 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700472 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700473 addedWorkspaceScreensFinal.add(screenId);
474 numPagesToAdd--;
475 }
Winson Chung76828c82013-08-19 15:43:29 -0700476
Winson Chung64359a52013-07-08 17:17:08 -0700477 // Find the coordinate again
478 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700479 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700480 }
481 if (coords == null) {
482 throw new RuntimeException("Coordinates should not be null");
483 }
484
Winson Chung997a9232013-07-24 15:33:46 -0700485 ShortcutInfo shortcutInfo;
486 if (a instanceof ShortcutInfo) {
487 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200488 } else if (a instanceof AppInfo) {
489 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700490 } else {
491 throw new RuntimeException("Unexpected info type");
492 }
Winson Chung94d67682013-09-25 16:29:40 -0700493
Winson Chung64359a52013-07-08 17:17:08 -0700494 // Add the shortcut to the db
495 addItemToDatabase(context, shortcutInfo,
496 LauncherSettings.Favorites.CONTAINER_DESKTOP,
497 coords.first, coords.second[0], coords.second[1], false);
498 // Save the ShortcutInfo for binding in the workspace
499 addedShortcutsFinal.add(shortcutInfo);
500 }
501 }
502
Winson Chung76828c82013-08-19 15:43:29 -0700503 // Update the workspace screens
504 updateWorkspaceScreenOrder(context, workspaceScreens);
505
Adam Cohen76a47a12014-02-05 11:47:43 -0800506 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700507 runOnMainThread(new Runnable() {
508 public void run() {
509 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
510 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700511 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
512 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700513 if (!addedShortcutsFinal.isEmpty()) {
514 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
515 long lastScreenId = info.screenId;
516 for (ItemInfo i : addedShortcutsFinal) {
517 if (i.screenId == lastScreenId) {
518 addAnimated.add(i);
519 } else {
520 addNotAnimated.add(i);
521 }
Winson Chung997a9232013-07-24 15:33:46 -0700522 }
523 }
Winson Chungd64d1762013-08-20 14:37:16 -0700524 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800525 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500526 if (!restoredAppsFinal.isEmpty()) {
527 callbacks.bindAppsUpdated(restoredAppsFinal);
528 }
Winson Chung997a9232013-07-24 15:33:46 -0700529 }
Winson Chung64359a52013-07-08 17:17:08 -0700530 }
Winson Chung997a9232013-07-24 15:33:46 -0700531 });
532 }
Winson Chung64359a52013-07-08 17:17:08 -0700533 }
534 };
535 runOnWorkerThread(r);
536 }
537
Winson Chung81b52252012-08-27 15:34:29 -0700538 public void unbindItemInfosAndClearQueuedBindRunnables() {
539 if (sWorkerThread.getThreadId() == Process.myTid()) {
540 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
541 "main thread");
542 }
543
544 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400545 synchronized (mDeferredBindRunnables) {
546 mDeferredBindRunnables.clear();
547 }
Winson Chung81b52252012-08-27 15:34:29 -0700548 // Remove any queued bind runnables
549 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
550 // Unbind all the workspace items
551 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700552 }
553
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700554 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700555 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700556 // Ensure that we don't use the same workspace items data structure on the main thread
557 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700558 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
559 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700560 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700561 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
562 tmpAppWidgets.addAll(sBgAppWidgets);
563 }
564 Runnable r = new Runnable() {
565 @Override
566 public void run() {
567 for (ItemInfo item : tmpWorkspaceItems) {
568 item.unbind();
569 }
570 for (ItemInfo item : tmpAppWidgets) {
571 item.unbind();
572 }
573 }
574 };
575 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700576 }
577
Joe Onorato9c1289c2009-08-17 11:03:03 -0400578 /**
579 * Adds an item to the DB if it was not created previously, or move it to a new
580 * <container, screen, cellX, cellY>
581 */
582 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400584 if (item.container == ItemInfo.NO_ID) {
585 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700586 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400587 } else {
588 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700589 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800590 }
591 }
592
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700593 static void checkItemInfoLocked(
594 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
595 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
596 if (modelItem != null && item != modelItem) {
597 // check all the data is consistent
598 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
599 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
600 ShortcutInfo shortcut = (ShortcutInfo) item;
601 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
602 modelShortcut.intent.filterEquals(shortcut.intent) &&
603 modelShortcut.id == shortcut.id &&
604 modelShortcut.itemType == shortcut.itemType &&
605 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700606 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700607 modelShortcut.cellX == shortcut.cellX &&
608 modelShortcut.cellY == shortcut.cellY &&
609 modelShortcut.spanX == shortcut.spanX &&
610 modelShortcut.spanY == shortcut.spanY &&
611 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
612 (modelShortcut.dropPos != null &&
613 shortcut.dropPos != null &&
614 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
615 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
616 // For all intents and purposes, this is the same object
617 return;
618 }
619 }
620
621 // the modelItem needs to match up perfectly with item if our model is
622 // to be consistent with the database-- for now, just require
623 // modelItem == item or the equality check above
624 String msg = "item: " + ((item != null) ? item.toString() : "null") +
625 "modelItem: " +
626 ((modelItem != null) ? modelItem.toString() : "null") +
627 "Error: ItemInfo passed to checkItemInfo doesn't match original";
628 RuntimeException e = new RuntimeException(msg);
629 if (stackTrace != null) {
630 e.setStackTrace(stackTrace);
631 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800632 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700633 }
634 }
635
Michael Jurka816474f2012-06-25 14:49:02 -0700636 static void checkItemInfo(final ItemInfo item) {
637 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
638 final long itemId = item.id;
639 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700640 public void run() {
641 synchronized (sBgLock) {
642 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700643 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700644 }
645 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700646 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700647 }
648
Michael Jurkac9d95c52011-08-29 14:03:34 -0700649 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
650 final ItemInfo item, final String callingFunction) {
651 final long itemId = item.id;
652 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
653 final ContentResolver cr = context.getContentResolver();
654
Adam Cohen487f7dd2012-06-28 18:12:10 -0700655 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700656 Runnable r = new Runnable() {
657 public void run() {
658 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700659 updateItemArrays(item, itemId, stackTrace);
660 }
661 };
662 runOnWorkerThread(r);
663 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700664
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700665 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
666 final ArrayList<ItemInfo> items, final String callingFunction) {
667 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700668
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700669 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
670 Runnable r = new Runnable() {
671 public void run() {
672 ArrayList<ContentProviderOperation> ops =
673 new ArrayList<ContentProviderOperation>();
674 int count = items.size();
675 for (int i = 0; i < count; i++) {
676 ItemInfo item = items.get(i);
677 final long itemId = item.id;
678 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
679 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700680
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700681 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
682 updateItemArrays(item, itemId, stackTrace);
683
684 }
685 try {
686 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
687 } catch (Exception e) {
688 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700689 }
690 }
691 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700692 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700693 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700694
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700695 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
696 // Lock on mBgLock *after* the db operation
697 synchronized (sBgLock) {
698 checkItemInfoLocked(itemId, item, stackTrace);
699
700 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
701 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
702 // Item is in a folder, make sure this folder exists
703 if (!sBgFolders.containsKey(item.container)) {
704 // An items container is being set to a that of an item which is not in
705 // the list of Folders.
706 String msg = "item: " + item + " container being set to: " +
707 item.container + ", not in the list of folders";
708 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700709 }
710 }
711
712 // Items are added/removed from the corresponding FolderInfo elsewhere, such
713 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
714 // that are on the desktop, as appropriate
715 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800716 if (modelItem != null &&
717 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
718 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700719 switch (modelItem.itemType) {
720 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
721 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
722 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
723 if (!sBgWorkspaceItems.contains(modelItem)) {
724 sBgWorkspaceItems.add(modelItem);
725 }
726 break;
727 default:
728 break;
729 }
730 } else {
731 sBgWorkspaceItems.remove(modelItem);
732 }
733 }
734 }
735
Michael Jurkac7700af2013-05-14 20:17:58 +0200736 public void flushWorkerThread() {
737 mFlushingWorkerThread = true;
738 Runnable waiter = new Runnable() {
739 public void run() {
740 synchronized (this) {
741 notifyAll();
742 mFlushingWorkerThread = false;
743 }
744 }
745 };
746
747 synchronized(waiter) {
748 runOnWorkerThread(waiter);
749 if (mLoaderTask != null) {
750 synchronized(mLoaderTask) {
751 mLoaderTask.notify();
752 }
753 }
754 boolean success = false;
755 while (!success) {
756 try {
757 waiter.wait();
758 success = true;
759 } catch (InterruptedException e) {
760 }
761 }
762 }
763 }
764
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800765 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700767 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700768 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700769 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400770 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400771 item.cellX = cellX;
772 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700773
Winson Chung3d503fb2011-07-13 17:25:49 -0700774 // We store hotseat items in canonical form which is this orientation invariant position
775 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700776 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700777 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700778 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700779 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700780 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700781 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400782
783 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400784 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700785 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
786 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700787 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400788
Michael Jurkac9d95c52011-08-29 14:03:34 -0700789 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700790 }
791
792 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700793 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
794 * cellX, cellY have already been updated on the ItemInfos.
795 */
796 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
797 final long container, final int screen) {
798
799 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
800 int count = items.size();
801
802 for (int i = 0; i < count; i++) {
803 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700804 item.container = container;
805
806 // We store hotseat items in canonical form which is this orientation invariant position
807 // in the hotseat
808 if (context instanceof Launcher && screen < 0 &&
809 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700810 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700811 item.cellY);
812 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700814 }
815
816 final ContentValues values = new ContentValues();
817 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
818 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
819 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700821
822 contentValues.add(values);
823 }
824 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
825 }
826
827 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700828 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800829 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700830 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700831 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700832 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800833 item.cellX = cellX;
834 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700835 item.spanX = spanX;
836 item.spanY = spanY;
837
838 // We store hotseat items in canonical form which is this orientation invariant position
839 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700840 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700841 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700842 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700843 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700844 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700845 }
Adam Cohend4844c32011-02-18 19:25:06 -0800846
Adam Cohend4844c32011-02-18 19:25:06 -0800847 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800848 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700849 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
850 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
851 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
852 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700853 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800854
Michael Jurka816474f2012-06-25 14:49:02 -0700855 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700856 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700857
858 /**
859 * Update an item to the database in a specified container.
860 */
861 static void updateItemInDatabase(Context context, final ItemInfo item) {
862 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100863 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700864 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
865 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800866 }
867
868 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400869 * Returns true if the shortcuts already exists in the database.
870 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800871 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400872 static boolean shortcutExists(Context context, String title, Intent intent) {
873 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700874 final Intent intentWithPkg, intentWithoutPkg;
875
876 if (intent.getComponent() != null) {
877 // If component is not null, an intent with null package will produce
878 // the same result and should also be a match.
879 if (intent.getPackage() != null) {
880 intentWithPkg = intent;
881 intentWithoutPkg = new Intent(intent).setPackage(null);
882 } else {
883 intentWithPkg = new Intent(intent).setPackage(
884 intent.getComponent().getPackageName());
885 intentWithoutPkg = intent;
886 }
887 } else {
888 intentWithPkg = intent;
889 intentWithoutPkg = intent;
890 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400891 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700892 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
893 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400894 boolean result = false;
895 try {
896 result = c.moveToFirst();
897 } finally {
898 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800899 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400900 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700901 }
902
Joe Onorato9c1289c2009-08-17 11:03:03 -0400903 /**
Sunny Goyal34942622014-08-29 17:20:55 -0700904 * Returns true if the promise shortcuts with the same package name exists on the workspace.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500905 */
Sunny Goyal34942622014-08-29 17:20:55 -0700906 static boolean appWasPromise(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500907 final ComponentName component = intent.getComponent();
908 if (component == null) {
909 return false;
910 }
Sunny Goyal34942622014-08-29 17:20:55 -0700911 return !getItemsByPackageName(component.getPackageName(), user).isEmpty();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500912 }
913
914 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700915 * Returns an ItemInfo array containing all the items in the LauncherModel.
916 * The ItemInfo.id is not set through this function.
917 */
918 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
919 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
920 final ContentResolver cr = context.getContentResolver();
921 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
922 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100923 LauncherSettings.Favorites.SCREEN,
924 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
925 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
926 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700927
928 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
929 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
930 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
931 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
932 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
933 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
934 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100935 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
936 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700937 try {
938 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700939 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700940 item.cellX = c.getInt(cellXIndex);
941 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700942 item.spanX = Math.max(1, c.getInt(spanXIndex));
943 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700944 item.container = c.getInt(containerIndex);
945 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700946 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100947 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100948 item.user = userManager.getUserForSerialNumber(serialNumber);
949 // Skip if user has been deleted.
950 if (item.user != null) {
951 items.add(item);
952 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700953 }
954 } catch (Exception e) {
955 items.clear();
956 } finally {
957 c.close();
958 }
959
960 return items;
961 }
962
963 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400964 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
965 */
966 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
967 final ContentResolver cr = context.getContentResolver();
968 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
969 "_id=? and (itemType=? or itemType=?)",
970 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700971 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700972
Joe Onorato9c1289c2009-08-17 11:03:03 -0400973 try {
974 if (c.moveToFirst()) {
975 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
976 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
977 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
978 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
979 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
980 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800981
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982 FolderInfo folderInfo = null;
983 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700984 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
985 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400986 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700987 }
988
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989 folderInfo.title = c.getString(titleIndex);
990 folderInfo.id = id;
991 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700992 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700993 folderInfo.cellX = c.getInt(cellXIndex);
994 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995
996 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700997 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998 } finally {
999 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001000 }
1001
1002 return null;
1003 }
1004
Joe Onorato9c1289c2009-08-17 11:03:03 -04001005 /**
1006 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1007 * cellY fields of the item. Also assigns an ID to the item.
1008 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001009 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001010 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001011 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012 item.cellX = cellX;
1013 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001014 // We store hotseat items in canonical form which is this orientation invariant position
1015 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001016 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001017 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001018 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001019 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001021 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001022
1023 final ContentValues values = new ContentValues();
1024 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001025 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001026
Michael Jurka414300a2013-08-27 15:42:35 +02001027 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001028 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001029 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001030
Jason Monk8e19cf22014-03-20 15:06:57 -04001031 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001032 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001033 public void run() {
1034 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1035 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001036
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001037 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001038 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001039 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 sBgItemsIdMap.put(item.id, item);
1041 switch (item.itemType) {
1042 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1043 sBgFolders.put(item.id, (FolderInfo) item);
1044 // Fall through
1045 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1046 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1047 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1048 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1049 sBgWorkspaceItems.add(item);
1050 } else {
1051 if (!sBgFolders.containsKey(item.container)) {
1052 // Adding an item to a folder that doesn't exist.
1053 String msg = "adding item: " + item + " to a folder that " +
1054 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001055 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001056 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001057 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001058 break;
1059 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1060 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1061 break;
1062 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001063 }
1064 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001065 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001066 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001067 }
1068
Joe Onorato9c1289c2009-08-17 11:03:03 -04001069 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001070 * Creates a new unique child id, for a given cell span across all layouts.
1071 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001072 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001073 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001074 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001076 }
1077
Sunny Goyal34942622014-08-29 17:20:55 -07001078 private static ArrayList<ItemInfo> getItemsByPackageName(
1079 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001080 ItemInfoFilter filter = new ItemInfoFilter() {
1081 @Override
1082 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1083 return cn.getPackageName().equals(pn) && info.user.equals(user);
1084 }
1085 };
Sunny Goyal34942622014-08-29 17:20:55 -07001086 return filterItemInfos(sBgItemsIdMap.values(), filter);
1087 }
1088
1089 /**
1090 * Removes all the items from the database corresponding to the specified package.
1091 */
1092 static void deletePackageFromDatabase(Context context, final String pn,
1093 final UserHandleCompat user) {
1094 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001095 }
1096
1097 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001098 * Removes the specified item from the database
1099 * @param context
1100 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001101 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001102 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001103 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1104 items.add(item);
1105 deleteItemsFromDatabase(context, items);
1106 }
1107
1108 /**
1109 * Removes the specified items from the database
1110 * @param context
1111 * @param item
1112 */
1113 static void deleteItemsFromDatabase(Context context, final ArrayList<ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001114 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001115
Michael Jurka83df1882011-08-31 20:59:26 -07001116 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001117 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001118 for (ItemInfo item : items) {
1119 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1120 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001122 // Lock on mBgLock *after* the db operation
1123 synchronized (sBgLock) {
1124 switch (item.itemType) {
1125 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1126 sBgFolders.remove(item.id);
1127 for (ItemInfo info: sBgItemsIdMap.values()) {
1128 if (info.container == item.id) {
1129 // We are deleting a folder which still contains items that
1130 // think they are contained by that folder.
1131 String msg = "deleting a folder (" + item + ") which still " +
1132 "contains items (" + info + ")";
1133 Log.e(TAG, msg);
1134 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001135 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001136 sBgWorkspaceItems.remove(item);
1137 break;
1138 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1139 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1140 sBgWorkspaceItems.remove(item);
1141 break;
1142 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1143 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1144 break;
1145 }
1146 sBgItemsIdMap.remove(item.id);
1147 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001148 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001149 }
1150 }
Michael Jurka83df1882011-08-31 20:59:26 -07001151 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001152 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001153 }
1154
1155 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001156 * Update the order of the workspace screens in the database. The array list contains
1157 * a list of screen ids in the order that they should appear.
1158 */
Winson Chungc9168342013-06-26 14:54:55 -07001159 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001160 // Log to disk
1161 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1162 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1163
Winson Chung64359a52013-07-08 17:17:08 -07001164 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001165 final ContentResolver cr = context.getContentResolver();
1166 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1167
1168 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001169 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001170 while (iter.hasNext()) {
1171 long id = iter.next();
1172 if (id < 0) {
1173 iter.remove();
1174 }
1175 }
1176
1177 Runnable r = new Runnable() {
1178 @Override
1179 public void run() {
Yura085c8532014-02-11 15:15:29 +00001180 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001181 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001182 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001183 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001184 for (int i = 0; i < count; i++) {
1185 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001186 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001187 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1188 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001189 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001190 }
Yura085c8532014-02-11 15:15:29 +00001191
1192 try {
1193 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1194 } catch (Exception ex) {
1195 throw new RuntimeException(ex);
1196 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001197
Winson Chungba9c37f2013-08-30 14:11:37 -07001198 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001199 sBgWorkspaceScreens.clear();
1200 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001201 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001202 }
1203 };
1204 runOnWorkerThread(r);
1205 }
1206
1207 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001208 * Remove the contents of the specified folder from the database
1209 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001210 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001211 final ContentResolver cr = context.getContentResolver();
1212
Michael Jurkac9d95c52011-08-29 14:03:34 -07001213 Runnable r = new Runnable() {
1214 public void run() {
1215 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001216 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001217 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 sBgItemsIdMap.remove(info.id);
1219 sBgFolders.remove(info.id);
1220 sBgDbIconCache.remove(info);
1221 sBgWorkspaceItems.remove(info);
1222 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001223
Michael Jurkac9d95c52011-08-29 14:03:34 -07001224 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1225 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001226 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001227 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001228 for (ItemInfo childInfo : info.contents) {
1229 sBgItemsIdMap.remove(childInfo.id);
1230 sBgDbIconCache.remove(childInfo);
1231 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001232 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001233 }
1234 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001235 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001236 }
1237
1238 /**
1239 * Set this as the current Launcher activity object for the loader.
1240 */
1241 public void initialize(Callbacks callbacks) {
1242 synchronized (mLock) {
1243 mCallbacks = new WeakReference<Callbacks>(callbacks);
1244 }
1245 }
1246
Kenny Guyed131872014-04-30 03:02:21 +01001247 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001248 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001249 int op = PackageUpdatedTask.OP_UPDATE;
1250 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1251 user));
1252 }
1253
1254 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001255 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001256 int op = PackageUpdatedTask.OP_REMOVE;
1257 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1258 user));
1259 }
1260
1261 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001262 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001263 int op = PackageUpdatedTask.OP_ADD;
1264 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1265 user));
1266 }
1267
1268 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001269 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001270 boolean replacing) {
1271 if (!replacing) {
1272 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1273 user));
1274 if (mAppsCanBeOnRemoveableStorage) {
1275 // Only rebind if we support removable storage. It catches the
1276 // case where
1277 // apps on the external sd card need to be reloaded
1278 startLoaderFromBackground();
1279 }
1280 } else {
1281 // If we are replacing then just update the packages in the list
1282 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1283 packageNames, user));
1284 }
1285 }
1286
1287 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001288 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001289 boolean replacing) {
1290 if (!replacing) {
1291 enqueuePackageUpdated(new PackageUpdatedTask(
1292 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1293 user));
1294 }
1295
1296 }
1297
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001298 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001299 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1300 * ACTION_PACKAGE_CHANGED.
1301 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001302 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001303 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001304 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001305
Joe Onorato36115782010-06-17 13:28:48 -04001306 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001307 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001308 // If we have changed locale we need to clear out the labels in all apps/workspace.
1309 forceReload();
1310 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1311 // Check if configuration change was an mcc/mnc change which would affect app resources
1312 // and we would need to clear out the labels in all apps/workspace. Same handling as
1313 // above for ACTION_LOCALE_CHANGED
1314 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001315 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001316 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001317 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001318 forceReload();
1319 }
1320 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001321 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001322 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1323 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001324 if (mCallbacks != null) {
1325 Callbacks callbacks = mCallbacks.get();
1326 if (callbacks != null) {
1327 callbacks.bindSearchablesChanged();
1328 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001329 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001330 }
1331 }
1332
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001333 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001334 resetLoadedState(true, true);
1335
Reena Lee93f824a2011-09-23 17:20:28 -07001336 // Do this here because if the launcher activity is running it will be restarted.
1337 // If it's not running startLoaderFromBackground will merely tell it that it needs
1338 // to reload.
1339 startLoaderFromBackground();
1340 }
1341
Winson Chungf0c6ae02012-03-21 16:10:31 -07001342 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1343 synchronized (mLock) {
1344 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1345 // mWorkspaceLoaded to true later
1346 stopLoaderLocked();
1347 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1348 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1349 }
1350 }
1351
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001352 /**
1353 * When the launcher is in the background, it's possible for it to miss paired
1354 * configuration changes. So whenever we trigger the loader from the background
1355 * tell the launcher that it needs to re-run the loader when it comes back instead
1356 * of doing it now.
1357 */
1358 public void startLoaderFromBackground() {
1359 boolean runLoader = false;
1360 if (mCallbacks != null) {
1361 Callbacks callbacks = mCallbacks.get();
1362 if (callbacks != null) {
1363 // Only actually run the loader if they're not paused.
1364 if (!callbacks.setLoadOnResume()) {
1365 runLoader = true;
1366 }
1367 }
1368 }
1369 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001370 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001371 }
Joe Onorato36115782010-06-17 13:28:48 -04001372 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001373
Reena Lee93f824a2011-09-23 17:20:28 -07001374 // If there is already a loader task running, tell it to stop.
1375 // returns true if isLaunching() was true on the old task
1376 private boolean stopLoaderLocked() {
1377 boolean isLaunching = false;
1378 LoaderTask oldTask = mLoaderTask;
1379 if (oldTask != null) {
1380 if (oldTask.isLaunching()) {
1381 isLaunching = true;
1382 }
1383 oldTask.stopLocked();
1384 }
1385 return isLaunching;
1386 }
1387
Adam Cohen1a85c582014-09-30 09:48:49 -07001388 public boolean isCurrentCallbacks(Callbacks callbacks) {
1389 return (mCallbacks != null && mCallbacks.get() == callbacks);
1390 }
1391
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001392 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001393 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1394 }
1395
1396 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001397 synchronized (mLock) {
1398 if (DEBUG_LOADERS) {
1399 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1400 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001401
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 // Clear any deferred bind-runnables from the synchronized load process
1403 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001404 synchronized (mDeferredBindRunnables) {
1405 mDeferredBindRunnables.clear();
1406 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001407
Joe Onorato36115782010-06-17 13:28:48 -04001408 // Don't bother to start the thread if we know it's not going to do anything
1409 if (mCallbacks != null && mCallbacks.get() != null) {
1410 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001411 // also, don't downgrade isLaunching if we're already running
1412 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001413 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001414 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1415 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001416 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1417 } else {
1418 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1419 sWorker.post(mLoaderTask);
1420 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001421 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001422 }
1423 }
1424
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001425 void bindRemainingSynchronousPages() {
1426 // Post the remaining side pages to be loaded
1427 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001428 Runnable[] deferredBindRunnables = null;
1429 synchronized (mDeferredBindRunnables) {
1430 deferredBindRunnables = mDeferredBindRunnables.toArray(
1431 new Runnable[mDeferredBindRunnables.size()]);
1432 mDeferredBindRunnables.clear();
1433 }
1434 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001435 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001436 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001437 }
1438 }
1439
Joe Onorato36115782010-06-17 13:28:48 -04001440 public void stopLoader() {
1441 synchronized (mLock) {
1442 if (mLoaderTask != null) {
1443 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001444 }
1445 }
Joe Onorato36115782010-06-17 13:28:48 -04001446 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001447
Winson Chung76828c82013-08-19 15:43:29 -07001448 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1449 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1450 final ContentResolver contentResolver = context.getContentResolver();
1451 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1452 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1453 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1454
1455 try {
1456 final int idIndex = sc.getColumnIndexOrThrow(
1457 LauncherSettings.WorkspaceScreens._ID);
1458 final int rankIndex = sc.getColumnIndexOrThrow(
1459 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1460 while (sc.moveToNext()) {
1461 try {
1462 long screenId = sc.getLong(idIndex);
1463 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001464 orderedScreens.put(rank, screenId);
1465 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001466 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001467 }
1468 }
1469 } finally {
1470 sc.close();
1471 }
Winson Chunga90303b2013-11-15 13:05:06 -08001472
1473 // Log to disk
1474 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1475 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1476 for (Integer i : orderedScreens.keySet()) {
1477 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1478 }
1479 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1480 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001481 return orderedScreens;
1482 }
1483
Michael Jurkac57b7a82011-08-09 22:02:20 -07001484 public boolean isAllAppsLoaded() {
1485 return mAllAppsLoaded;
1486 }
1487
Winson Chung36a62fe2012-05-06 18:04:42 -07001488 boolean isLoadingWorkspace() {
1489 synchronized (mLock) {
1490 if (mLoaderTask != null) {
1491 return mLoaderTask.isLoadingWorkspace();
1492 }
1493 }
1494 return false;
1495 }
1496
Joe Onorato36115782010-06-17 13:28:48 -04001497 /**
1498 * Runnable for the thread that loads the contents of the launcher:
1499 * - workspace icons
1500 * - widgets
1501 * - all apps icons
1502 */
1503 private class LoaderTask implements Runnable {
1504 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001505 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001506 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001507 private boolean mStopped;
1508 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001509 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001510
Winson Chungc3eecff2011-07-11 17:44:15 -07001511 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001512
Dan Sandlerd5024042014-01-09 15:01:33 -05001513 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001514 mContext = context;
1515 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001516 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001517 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001518 }
1519
Joe Onorato36115782010-06-17 13:28:48 -04001520 boolean isLaunching() {
1521 return mIsLaunching;
1522 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001523
Winson Chung36a62fe2012-05-06 18:04:42 -07001524 boolean isLoadingWorkspace() {
1525 return mIsLoadingAndBindingWorkspace;
1526 }
1527
Winson Chungc763c4e2013-07-19 13:49:06 -07001528 /** Returns whether this is an upgrade path */
1529 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001530 mIsLoadingAndBindingWorkspace = true;
1531
Joe Onorato36115782010-06-17 13:28:48 -04001532 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001533 if (DEBUG_LOADERS) {
1534 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001535 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001536
Winson Chungc763c4e2013-07-19 13:49:06 -07001537 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001538 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001539 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001540 synchronized (LoaderTask.this) {
1541 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001542 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001543 }
1544 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001545 }
1546 }
1547
Joe Onorato36115782010-06-17 13:28:48 -04001548 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001549 bindWorkspace(-1, isUpgradePath);
1550 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001551 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001552
Joe Onorato36115782010-06-17 13:28:48 -04001553 private void waitForIdle() {
1554 // Wait until the either we're stopped or the other threads are done.
1555 // This way we don't start loading all apps until the workspace has settled
1556 // down.
1557 synchronized (LoaderTask.this) {
1558 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001559
Joe Onorato36115782010-06-17 13:28:48 -04001560 mHandler.postIdle(new Runnable() {
1561 public void run() {
1562 synchronized (LoaderTask.this) {
1563 mLoadAndBindStepFinished = true;
1564 if (DEBUG_LOADERS) {
1565 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001566 }
Joe Onorato36115782010-06-17 13:28:48 -04001567 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001568 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001569 }
Joe Onorato36115782010-06-17 13:28:48 -04001570 });
1571
Michael Jurkac7700af2013-05-14 20:17:58 +02001572 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001573 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001574 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1575 // wait no longer than 1sec at a time
1576 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001577 } catch (InterruptedException ex) {
1578 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001579 }
1580 }
Joe Onorato36115782010-06-17 13:28:48 -04001581 if (DEBUG_LOADERS) {
1582 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001583 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001584 + "ms for previous step to finish binding");
1585 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001586 }
Joe Onorato36115782010-06-17 13:28:48 -04001587 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001588
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001590 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001591 // Ensure that we have a valid page index to load synchronously
1592 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1593 "valid page index");
1594 }
1595 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1596 // Ensure that we don't try and bind a specified page when the pages have not been
1597 // loaded already (we should load everything asynchronously in that case)
1598 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1599 }
1600 synchronized (mLock) {
1601 if (mIsLoaderTaskRunning) {
1602 // Ensure that we are never running the background loading at this point since
1603 // we also touch the background collections
1604 throw new RuntimeException("Error! Background loading is already running");
1605 }
1606 }
1607
1608 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1609 // data structures, we can't allow any other thread to touch that data, but because
1610 // this call is synchronous, we can get away with not locking).
1611
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001612 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001613 // operations from the previous activity. We need to ensure that all queued operations
1614 // are executed before any synchronous binding work is done.
1615 mHandler.flush();
1616
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001617 // Divide the set of loaded items into those that we are binding synchronously, and
1618 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001619 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001620 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1621 // arise from that.
1622 onlyBindAllApps();
1623 }
1624
Joe Onorato36115782010-06-17 13:28:48 -04001625 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001626 boolean isUpgrade = false;
1627
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001628 synchronized (mLock) {
1629 mIsLoaderTaskRunning = true;
1630 }
Joe Onorato36115782010-06-17 13:28:48 -04001631 // Optimize for end-user experience: if the Launcher is up and // running with the
1632 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1633 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001634 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001635 // Elevate priority when Home launches for the first time to avoid
1636 // starving at boot time. Staring at a blank home is not cool.
1637 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001638 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1639 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001640 android.os.Process.setThreadPriority(mIsLaunching
1641 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1642 }
Winson Chung64359a52013-07-08 17:17:08 -07001643 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001644 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001645
Joe Onorato36115782010-06-17 13:28:48 -04001646 if (mStopped) {
1647 break keep_running;
1648 }
1649
1650 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1651 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001652 synchronized (mLock) {
1653 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001654 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001655 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656 }
1657 }
Joe Onorato36115782010-06-17 13:28:48 -04001658 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001659
1660 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001661 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1662 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001663
1664 // Restore the default thread priority after we are done loading items
1665 synchronized (mLock) {
1666 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1667 }
Joe Onorato36115782010-06-17 13:28:48 -04001668 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001669
Winson Chungaac01e12011-08-17 10:37:13 -07001670 // Update the saved icons if necessary
1671 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001672 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001673 for (Object key : sBgDbIconCache.keySet()) {
1674 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1675 }
1676 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001677 }
Winson Chungaac01e12011-08-17 10:37:13 -07001678
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001679 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001680 // Ensure that all the applications that are in the system are
1681 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001682 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001683 verifyApplications();
1684 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001685 }
1686
Joe Onorato36115782010-06-17 13:28:48 -04001687 // Clear out this reference, otherwise we end up holding it until all of the
1688 // callback runnables are done.
1689 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001690
Joe Onorato36115782010-06-17 13:28:48 -04001691 synchronized (mLock) {
1692 // If we are still the last one to be scheduled, remove ourselves.
1693 if (mLoaderTask == this) {
1694 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001695 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001696 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001697 }
Joe Onorato36115782010-06-17 13:28:48 -04001698 }
1699
1700 public void stopLocked() {
1701 synchronized (LoaderTask.this) {
1702 mStopped = true;
1703 this.notify();
1704 }
1705 }
1706
1707 /**
1708 * Gets the callbacks object. If we've been stopped, or if the launcher object
1709 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1710 * object that was around when the deferred message was scheduled, and if there's
1711 * a new Callbacks object around then also return null. This will save us from
1712 * calling onto it with data that will be ignored.
1713 */
1714 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1715 synchronized (mLock) {
1716 if (mStopped) {
1717 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001718 }
Joe Onorato36115782010-06-17 13:28:48 -04001719
1720 if (mCallbacks == null) {
1721 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001722 }
Joe Onorato36115782010-06-17 13:28:48 -04001723
1724 final Callbacks callbacks = mCallbacks.get();
1725 if (callbacks != oldCallbacks) {
1726 return null;
1727 }
1728 if (callbacks == null) {
1729 Log.w(TAG, "no mCallbacks");
1730 return null;
1731 }
1732
1733 return callbacks;
1734 }
1735 }
1736
Winson Chungc763c4e2013-07-19 13:49:06 -07001737 private void verifyApplications() {
1738 final Context context = mApp.getContext();
1739
1740 // Cross reference all the applications in our apps list with items in the workspace
1741 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001742 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001743 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001744 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001745 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001746 if (tmpInfos.isEmpty()) {
1747 // We are missing an application icon, so add this to the workspace
1748 added.add(app);
1749 // This is a rare event, so lets log it
1750 Log.e(TAG, "Missing Application on load: " + app);
1751 }
1752 }
1753 }
1754 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001755 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001756 }
1757 }
1758
Joe Onorato36115782010-06-17 13:28:48 -04001759 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001760 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001761 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001762 LauncherAppState app = LauncherAppState.getInstance();
1763 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001764 final int countX = (int) grid.numColumns;
1765 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001766
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001768 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001769 // Return early if we detect that an item is under the hotseat button
1770 if (mCallbacks == null ||
1771 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001772 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001773 Log.e(TAG, "Error loading shortcut into hotseat " + item
1774 + " into position (" + item.screenId + ":" + item.cellX + ","
1775 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001776 return false;
1777 }
1778
Dan Sandler295ae182013-12-10 16:05:47 -05001779 final ItemInfo[][] hotseatItems =
1780 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1781
Adam Cohenae4409d2013-11-26 10:34:59 -08001782 if (item.screenId >= grid.numHotseatIcons) {
1783 Log.e(TAG, "Error loading shortcut " + item
1784 + " into hotseat position " + item.screenId
1785 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1786 + ")");
1787 return false;
1788 }
1789
Dan Sandler295ae182013-12-10 16:05:47 -05001790 if (hotseatItems != null) {
1791 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001792 Log.e(TAG, "Error loading shortcut into hotseat " + item
1793 + " into position (" + item.screenId + ":" + item.cellX + ","
1794 + item.cellY + ") occupied by "
1795 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1796 [(int) item.screenId][0]);
1797 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001798 } else {
1799 hotseatItems[(int) item.screenId][0] = item;
1800 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001801 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001802 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001803 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001804 items[(int) item.screenId][0] = item;
1805 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001806 return true;
1807 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001808 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1809 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001810 return true;
1811 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001812
Adam Cohendcd297f2013-06-18 13:13:40 -07001813 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001814 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001815 occupied.put(item.screenId, items);
1816 }
1817
Dan Sandler295ae182013-12-10 16:05:47 -05001818 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001819 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1820 item.cellX < 0 || item.cellY < 0 ||
1821 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1822 Log.e(TAG, "Error loading shortcut " + item
1823 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1824 + item.cellX + "," + item.cellY
1825 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1826 return false;
1827 }
1828
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001829 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001830 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1831 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001832 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001833 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001834 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001835 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001836 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001837 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001838 return false;
1839 }
1840 }
1841 }
1842 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1843 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001844 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001845 }
1846 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001847
Joe Onorato36115782010-06-17 13:28:48 -04001848 return true;
1849 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001850
Winson Chungba9c37f2013-08-30 14:11:37 -07001851 /** Clears all the sBg data structures */
1852 private void clearSBgDataStructures() {
1853 synchronized (sBgLock) {
1854 sBgWorkspaceItems.clear();
1855 sBgAppWidgets.clear();
1856 sBgFolders.clear();
1857 sBgItemsIdMap.clear();
1858 sBgDbIconCache.clear();
1859 sBgWorkspaceScreens.clear();
1860 }
1861 }
1862
Dan Sandlerd5024042014-01-09 15:01:33 -05001863 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001864 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001865 // Log to disk
1866 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1867
Joe Onorato36115782010-06-17 13:28:48 -04001868 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001869
Joe Onorato36115782010-06-17 13:28:48 -04001870 final Context context = mContext;
1871 final ContentResolver contentResolver = context.getContentResolver();
1872 final PackageManager manager = context.getPackageManager();
1873 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1874 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001875 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1876 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001877 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001878
Winson Chung892c74d2013-08-22 16:15:50 -07001879 LauncherAppState app = LauncherAppState.getInstance();
1880 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1881 int countX = (int) grid.numColumns;
1882 int countY = (int) grid.numRows;
1883
Dan Sandlerd5024042014-01-09 15:01:33 -05001884 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1885 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1886 LauncherAppState.getLauncherProvider().deleteDatabase();
1887 }
1888
1889 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1890 // append the user's Launcher2 shortcuts
1891 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1892 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1893 } else {
1894 // Make sure the default workspace is loaded
1895 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001896 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001897 }
Adam Cohene25af792013-06-06 23:08:25 -07001898
Adam Cohen71483f42014-05-15 14:04:01 -07001899 // This code path is for our old migration code and should no longer be exercised
1900 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001901
Winson Chung9f9f00b2013-11-15 13:27:00 -08001902 // Log to disk
1903 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001904
Winson Chung2abf94d2012-07-18 18:16:38 -07001905 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001906 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001907 final HashSet<String> installingPkgs = PackageInstallerCompat
1908 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001909
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001910 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001911 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001912 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001913 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001914 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001915
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001916 // +1 for the hotseat (it can be larger than the workspace)
1917 // Load workspace in reverse order to ensure that latest items are loaded first (and
1918 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001919 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001920
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001921 try {
1922 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1923 final int intentIndex = c.getColumnIndexOrThrow
1924 (LauncherSettings.Favorites.INTENT);
1925 final int titleIndex = c.getColumnIndexOrThrow
1926 (LauncherSettings.Favorites.TITLE);
1927 final int iconTypeIndex = c.getColumnIndexOrThrow(
1928 LauncherSettings.Favorites.ICON_TYPE);
1929 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1930 final int iconPackageIndex = c.getColumnIndexOrThrow(
1931 LauncherSettings.Favorites.ICON_PACKAGE);
1932 final int iconResourceIndex = c.getColumnIndexOrThrow(
1933 LauncherSettings.Favorites.ICON_RESOURCE);
1934 final int containerIndex = c.getColumnIndexOrThrow(
1935 LauncherSettings.Favorites.CONTAINER);
1936 final int itemTypeIndex = c.getColumnIndexOrThrow(
1937 LauncherSettings.Favorites.ITEM_TYPE);
1938 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1939 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001940 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1941 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001942 final int screenIndex = c.getColumnIndexOrThrow(
1943 LauncherSettings.Favorites.SCREEN);
1944 final int cellXIndex = c.getColumnIndexOrThrow
1945 (LauncherSettings.Favorites.CELLX);
1946 final int cellYIndex = c.getColumnIndexOrThrow
1947 (LauncherSettings.Favorites.CELLY);
1948 final int spanXIndex = c.getColumnIndexOrThrow
1949 (LauncherSettings.Favorites.SPANX);
1950 final int spanYIndex = c.getColumnIndexOrThrow(
1951 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001952 final int restoredIndex = c.getColumnIndexOrThrow(
1953 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001954 final int profileIdIndex = c.getColumnIndexOrThrow(
1955 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001956 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1957 //final int displayModeIndex = c.getColumnIndexOrThrow(
1958 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001959
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001960 ShortcutInfo info;
1961 String intentDescription;
1962 LauncherAppWidgetInfo appWidgetInfo;
1963 int container;
1964 long id;
1965 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001966 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001967
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001968 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001969 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001970 try {
1971 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001972 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001973 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001974
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001975 switch (itemType) {
1976 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1977 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001978 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001979 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001980 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001981 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001982 int promiseType = c.getInt(restoredIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001983 if (user == null) {
1984 // User has been deleted remove the item.
1985 itemsToRemove.add(id);
1986 continue;
1987 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001988 try {
1989 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001990 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001991 if (cn != null && cn.getPackageName() != null) {
1992 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1993 cn.getPackageName(), user);
1994 boolean validComponent = validPkg &&
1995 launcherApps.isActivityEnabledForProfile(cn, user);
1996
1997 if (validComponent) {
1998 if (restored) {
1999 // no special handling necessary for this item
2000 restoredRows.add(id);
2001 restored = false;
2002 }
2003 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07002004 intent = null;
2005 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2006 // We allow auto install apps to have their intent
2007 // updated after an install.
2008 intent = manager.getLaunchIntentForPackage(
2009 cn.getPackageName());
2010 if (intent != null) {
2011 ContentValues values = new ContentValues();
2012 values.put(LauncherSettings.Favorites.INTENT,
2013 intent.toUri(0));
2014 String where = BaseColumns._ID + "= ?";
2015 String[] args = {Long.toString(id)};
2016 contentResolver.update(contentUri, values, where, args);
2017 }
2018 }
2019
2020 if (intent == null) {
2021 // The app is installed but the component is no
2022 // longer available.
2023 Launcher.addDumpLog(TAG,
2024 "Invalid component removed: " + cn, true);
2025 itemsToRemove.add(id);
2026 continue;
2027 } else {
2028 // no special handling necessary for this item
2029 restoredRows.add(id);
2030 restored = false;
2031 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002032 } else if (restored) {
2033 // Package is not yet available but might be
2034 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002035 Launcher.addDumpLog(TAG,
2036 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002037
2038 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2039 // Restore has started once.
2040 } else if (installingPkgs.contains(cn.getPackageName())) {
2041 // App restore has started. Update the flag
2042 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2043 ContentValues values = new ContentValues();
2044 values.put(LauncherSettings.Favorites.RESTORED,
2045 promiseType);
2046 String where = BaseColumns._ID + "= ?";
2047 String[] args = {Long.toString(id)};
2048 contentResolver.update(contentUri, values, where, args);
2049
2050 } else if (REMOVE_UNRESTORED_ICONS) {
2051 Launcher.addDumpLog(TAG,
2052 "Unrestored package removed: " + cn, true);
2053 itemsToRemove.add(id);
2054 continue;
2055 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002056 } else if (isSdCardReady) {
2057 // Do not wait for external media load anymore.
2058 // Log the invalid package, and remove it
2059 Launcher.addDumpLog(TAG,
2060 "Invalid package removed: " + cn, true);
2061 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002062 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002063 } else {
2064 // SdCard is not ready yet. Package might get available,
2065 // once it is ready.
2066 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2067 + " (check again later)", true);
2068 HashSet<String> pkgs = sPendingPackages.get(user);
2069 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002070 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002071 sPendingPackages.put(user, pkgs);
2072 }
2073 pkgs.add(cn.getPackageName());
2074 allowMissingTarget = true;
2075 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002076 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002077 } else if (cn == null) {
2078 // For shortcuts with no component, keep them as they are
2079 restoredRows.add(id);
2080 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002081 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002083 Launcher.addDumpLog(TAG,
2084 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 continue;
2086 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002087
Chris Wrenf4d08112014-01-16 18:13:56 -05002088 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002089 if (user.equals(UserHandleCompat.myUserHandle())) {
2090 Launcher.addDumpLog(TAG,
2091 "constructing info for partially restored package",
2092 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002093 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002094 intent = getRestoredItemIntent(c, context, intent);
2095 } else {
2096 // Don't restore items for other profiles.
2097 itemsToRemove.add(id);
2098 continue;
2099 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002100 } else if (itemType ==
2101 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002102 info = getShortcutInfo(manager, intent, user, context, c,
2103 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002104 } else {
2105 info = getShortcutInfo(c, context, iconTypeIndex,
2106 iconPackageIndex, iconResourceIndex, iconIndex,
2107 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002108
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 // App shortcuts that used to be automatically added to Launcher
2110 // didn't always have the correct intent flags set, so do that
2111 // here
2112 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002113 intent.getCategories() != null &&
2114 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002115 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 intent.addFlags(
2117 Intent.FLAG_ACTIVITY_NEW_TASK |
2118 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2119 }
Michael Jurka96879562012-03-22 05:54:33 -07002120 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002121
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002123 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002124 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002125 container = c.getInt(containerIndex);
2126 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002127 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002128 info.cellX = c.getInt(cellXIndex);
2129 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002130 info.spanX = 1;
2131 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002132 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002133 info.isDisabled = isSafeMode
2134 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002135
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002136 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002137 deleteOnInvalidPlacement.set(false);
2138 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2139 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002140 itemsToRemove.add(id);
2141 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 break;
2143 }
2144
2145 switch (container) {
2146 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2147 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2148 sBgWorkspaceItems.add(info);
2149 break;
2150 default:
2151 // Item is in a user folder
2152 FolderInfo folderInfo =
2153 findOrMakeFolder(sBgFolders, container);
2154 folderInfo.add(info);
2155 break;
2156 }
2157 sBgItemsIdMap.put(info.id, info);
2158
2159 // now that we've loaded everthing re-save it with the
2160 // icon in case it disappears somehow.
2161 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002162 } else {
2163 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002164 }
2165 break;
2166
2167 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2168 id = c.getLong(idIndex);
2169 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2170
2171 folderInfo.title = c.getString(titleIndex);
2172 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002173 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002174 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002175 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002176 folderInfo.cellX = c.getInt(cellXIndex);
2177 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002178 folderInfo.spanX = 1;
2179 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002180
Daniel Sandler8802e962010-05-26 16:28:16 -04002181 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002182 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002183 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002184 deleteOnInvalidPlacement)) {
2185 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002186 itemsToRemove.add(id);
2187 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002188 break;
2189 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002190
Joe Onorato9c1289c2009-08-17 11:03:03 -04002191 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002192 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2193 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2194 sBgWorkspaceItems.add(folderInfo);
2195 break;
Joe Onorato36115782010-06-17 13:28:48 -04002196 }
Joe Onorato17a89222011-02-08 17:26:11 -08002197
Chris Wrenf4d08112014-01-16 18:13:56 -05002198 if (restored) {
2199 // no special handling required for restored folders
2200 restoredRows.add(id);
2201 }
2202
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002203 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2204 sBgFolders.put(folderInfo.id, folderInfo);
2205 break;
2206
2207 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2208 // Read all Launcher-specific widget details
2209 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002210 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002211 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002212 final ComponentName component =
2213 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002214
Sunny Goyal651077b2014-06-30 14:15:31 -07002215 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002216 final boolean isIdValid = (restoreStatus &
2217 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002218
Sunny Goyalff572272014-07-23 13:58:07 -07002219 final boolean wasProviderReady = (restoreStatus &
2220 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002221
Sunny Goyalff572272014-07-23 13:58:07 -07002222 final AppWidgetProviderInfo provider = isIdValid
2223 ? widgets.getAppWidgetInfo(appWidgetId)
2224 : findAppWidgetProviderInfoWithComponent(context, component);
2225
2226 final boolean isProviderReady = isValidProvider(provider);
2227 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002228 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002229 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002230 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002231 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 itemsToRemove.add(id);
2233 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002234 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002235 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2236 provider.provider);
2237 int[] minSpan =
2238 Launcher.getMinSpanForWidget(context, provider);
2239 appWidgetInfo.minSpanX = minSpan[0];
2240 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002241
2242 int status = restoreStatus;
2243 if (!wasProviderReady) {
2244 // If provider was not previously ready, update the
2245 // status and UI flag.
2246
2247 // Id would be valid only if the widget restore broadcast was received.
2248 if (isIdValid) {
2249 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2250 } else {
2251 status &= ~LauncherAppWidgetInfo
2252 .FLAG_PROVIDER_NOT_READY;
2253 }
2254 }
2255 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002256 } else {
2257 Log.v(TAG, "Widget restore pending id=" + id
2258 + " appWidgetId=" + appWidgetId
2259 + " status =" + restoreStatus);
2260 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002261 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002262 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002263
2264 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2265 // Restore has started once.
2266 } else if (installingPkgs.contains(component.getPackageName())) {
2267 // App restore has started. Update the flag
2268 appWidgetInfo.restoreStatus |=
2269 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
2270 } else if (REMOVE_UNRESTORED_ICONS) {
2271 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002272 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002273 itemsToRemove.add(id);
2274 continue;
2275 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002276 }
Sunny Goyalff572272014-07-23 13:58:07 -07002277
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002278 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002279 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 appWidgetInfo.cellX = c.getInt(cellXIndex);
2281 appWidgetInfo.cellY = c.getInt(cellYIndex);
2282 appWidgetInfo.spanX = c.getInt(spanXIndex);
2283 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002284
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 container = c.getInt(containerIndex);
2286 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2287 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2288 Log.e(TAG, "Widget found where container != " +
2289 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2290 continue;
2291 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002292
Adam Cohene25af792013-06-06 23:08:25 -07002293 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002294 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002295 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002296 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002297 deleteOnInvalidPlacement)) {
2298 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002299 itemsToRemove.add(id);
2300 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 break;
2302 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002303
Sunny Goyal94485362014-09-18 16:13:58 -07002304 String providerName = appWidgetInfo.providerName.flattenToString();
2305 if (!providerName.equals(savedProvider) ||
2306 (appWidgetInfo.restoreStatus != restoreStatus)) {
2307 ContentValues values = new ContentValues();
2308 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2309 providerName);
2310 values.put(LauncherSettings.Favorites.RESTORED,
2311 appWidgetInfo.restoreStatus);
2312 String where = BaseColumns._ID + "= ?";
2313 String[] args = {Long.toString(id)};
2314 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002315 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002316 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2317 sBgAppWidgets.add(appWidgetInfo);
2318 }
Joe Onorato36115782010-06-17 13:28:48 -04002319 break;
2320 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002321 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002322 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002323 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002324 }
2325 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002326 if (c != null) {
2327 c.close();
2328 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002329 }
2330
Winson Chungba9c37f2013-08-30 14:11:37 -07002331 // Break early if we've stopped loading
2332 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002333 clearSBgDataStructures();
2334 return false;
2335 }
2336
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 if (itemsToRemove.size() > 0) {
2338 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002339 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002340 // Remove dead items
2341 for (long id : itemsToRemove) {
2342 if (DEBUG_LOADERS) {
2343 Log.d(TAG, "Removed id = " + id);
2344 }
2345 // Don't notify content observers
2346 try {
2347 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2348 null, null);
2349 } catch (RemoteException e) {
2350 Log.w(TAG, "Could not remove id = " + id);
2351 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002352 }
2353 }
2354
Chris Wrenf4d08112014-01-16 18:13:56 -05002355 if (restoredRows.size() > 0) {
2356 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002357 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002358 // Update restored items that no longer require special handling
2359 try {
2360 StringBuilder selectionBuilder = new StringBuilder();
2361 selectionBuilder.append(LauncherSettings.Favorites._ID);
2362 selectionBuilder.append(" IN (");
2363 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2364 selectionBuilder.append(")");
2365 ContentValues values = new ContentValues();
2366 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002367 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002368 values, selectionBuilder.toString(), null);
2369 } catch (RemoteException e) {
2370 Log.w(TAG, "Could not update restored rows");
2371 }
2372 }
2373
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002374 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2375 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002376 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002377 null, sWorker);
2378 }
2379
Winson Chungc763c4e2013-07-19 13:49:06 -07002380 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002381 long maxScreenId = 0;
2382 // If we're importing we use the old screen order.
2383 for (ItemInfo item: sBgItemsIdMap.values()) {
2384 long screenId = item.screenId;
2385 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2386 !sBgWorkspaceScreens.contains(screenId)) {
2387 sBgWorkspaceScreens.add(screenId);
2388 if (screenId > maxScreenId) {
2389 maxScreenId = screenId;
2390 }
2391 }
2392 }
2393 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002394 // Log to disk
2395 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2396 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2397 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002398
Michael Jurka414300a2013-08-27 15:42:35 +02002399 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002400 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002401
2402 // Update the max item id after we load an old db
2403 long maxItemId = 0;
2404 // If we're importing we use the old screen order.
2405 for (ItemInfo item: sBgItemsIdMap.values()) {
2406 maxItemId = Math.max(maxItemId, item.id);
2407 }
Michael Jurka414300a2013-08-27 15:42:35 +02002408 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002409 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002410 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2411 for (Integer i : orderedScreens.keySet()) {
2412 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002413 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002414 // Log to disk
2415 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2416 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002417
2418 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002419 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002420 for (ItemInfo item: sBgItemsIdMap.values()) {
2421 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002422 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2423 unusedScreens.contains(screenId)) {
2424 unusedScreens.remove(screenId);
2425 }
2426 }
2427
2428 // If there are any empty screens remove them, and update.
2429 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002430 // Log to disk
2431 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2432 TextUtils.join(", ", unusedScreens), true);
2433
Winson Chung933bae62013-08-29 11:42:30 -07002434 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002435 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2436 }
2437 }
2438
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002439 if (DEBUG_LOADERS) {
2440 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2441 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002442 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002443 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002444 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002445
Daniel Sandler566da102013-06-25 23:43:45 -04002446 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002447 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002448 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002449 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002450 line += " | ";
2451 }
Winson Chung892c74d2013-08-22 16:15:50 -07002452 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002453 ItemInfo[][] screen = occupied.get(screenId);
2454 if (x < screen.length && y < screen[x].length) {
2455 line += (screen[x][y] != null) ? "#" : ".";
2456 } else {
2457 line += "!";
2458 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 }
Joe Onorato36115782010-06-17 13:28:48 -04002460 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002462 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002463 }
Joe Onorato36115782010-06-17 13:28:48 -04002464 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002465 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002466 }
2467
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 /** Filters the set of items who are directly or indirectly (via another container) on the
2469 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002470 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471 ArrayList<ItemInfo> allWorkspaceItems,
2472 ArrayList<ItemInfo> currentScreenItems,
2473 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002474 // Purge any null ItemInfos
2475 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2476 while (iter.hasNext()) {
2477 ItemInfo i = iter.next();
2478 if (i == null) {
2479 iter.remove();
2480 }
2481 }
2482
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002483 // Order the set of items by their containers first, this allows use to walk through the
2484 // list sequentially, build up a list of containers that are in the specified screen,
2485 // as well as all items in those containers.
2486 Set<Long> itemsOnScreen = new HashSet<Long>();
2487 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2488 @Override
2489 public int compare(ItemInfo lhs, ItemInfo rhs) {
2490 return (int) (lhs.container - rhs.container);
2491 }
2492 });
2493 for (ItemInfo info : allWorkspaceItems) {
2494 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002495 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002496 currentScreenItems.add(info);
2497 itemsOnScreen.add(info.id);
2498 } else {
2499 otherScreenItems.add(info);
2500 }
2501 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2502 currentScreenItems.add(info);
2503 itemsOnScreen.add(info.id);
2504 } else {
2505 if (itemsOnScreen.contains(info.container)) {
2506 currentScreenItems.add(info);
2507 itemsOnScreen.add(info.id);
2508 } else {
2509 otherScreenItems.add(info);
2510 }
2511 }
2512 }
2513 }
2514
2515 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002516 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002517 ArrayList<LauncherAppWidgetInfo> appWidgets,
2518 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2519 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520
2521 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002522 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002524 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002525 currentScreenWidgets.add(widget);
2526 } else {
2527 otherScreenWidgets.add(widget);
2528 }
2529 }
2530 }
2531
2532 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002533 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 HashMap<Long, ItemInfo> itemsIdMap,
2535 HashMap<Long, FolderInfo> folders,
2536 HashMap<Long, FolderInfo> currentScreenFolders,
2537 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002538
2539 for (long id : folders.keySet()) {
2540 ItemInfo info = itemsIdMap.get(id);
2541 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002542 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002543 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002544 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 currentScreenFolders.put(id, folder);
2546 } else {
2547 otherScreenFolders.put(id, folder);
2548 }
2549 }
2550 }
2551
2552 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2553 * right) */
2554 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002555 final LauncherAppState app = LauncherAppState.getInstance();
2556 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002557 // XXX: review this
2558 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002559 @Override
2560 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002561 int cellCountX = (int) grid.numColumns;
2562 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002563 int screenOffset = cellCountX * cellCountY;
2564 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002565 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002566 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002567 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002568 rhs.cellY * cellCountX + rhs.cellX);
2569 return (int) (lr - rr);
2570 }
2571 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002572 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002573
Adam Cohendcd297f2013-06-18 13:13:40 -07002574 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2575 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002576 final Runnable r = new Runnable() {
2577 @Override
2578 public void run() {
2579 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2580 if (callbacks != null) {
2581 callbacks.bindScreens(orderedScreens);
2582 }
2583 }
2584 };
2585 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2586 }
2587
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002588 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2589 final ArrayList<ItemInfo> workspaceItems,
2590 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2591 final HashMap<Long, FolderInfo> folders,
2592 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002593
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002594 final boolean postOnMainThread = (deferredBindRunnables != null);
2595
2596 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002597 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002599 final int start = i;
2600 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 final Runnable r = new Runnable() {
2602 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002603 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002604 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002605 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002606 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2607 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002608 }
2609 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002610 };
2611 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002612 synchronized (deferredBindRunnables) {
2613 deferredBindRunnables.add(r);
2614 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002616 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002617 }
Joe Onorato36115782010-06-17 13:28:48 -04002618 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002619
2620 // Bind the folders
2621 if (!folders.isEmpty()) {
2622 final Runnable r = new Runnable() {
2623 public void run() {
2624 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2625 if (callbacks != null) {
2626 callbacks.bindFolders(folders);
2627 }
2628 }
2629 };
2630 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002631 synchronized (deferredBindRunnables) {
2632 deferredBindRunnables.add(r);
2633 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002634 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002635 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002636 }
2637 }
2638
2639 // Bind the widgets, one at a time
2640 N = appWidgets.size();
2641 for (int i = 0; i < N; i++) {
2642 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2643 final Runnable r = new Runnable() {
2644 public void run() {
2645 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2646 if (callbacks != null) {
2647 callbacks.bindAppWidget(widget);
2648 }
2649 }
2650 };
2651 if (postOnMainThread) {
2652 deferredBindRunnables.add(r);
2653 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002654 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655 }
2656 }
2657 }
2658
2659 /**
2660 * Binds all loaded data to actual views on the main thread.
2661 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002662 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663 final long t = SystemClock.uptimeMillis();
2664 Runnable r;
2665
2666 // Don't use these two variables in any of the callback runnables.
2667 // Otherwise we hold a reference to them.
2668 final Callbacks oldCallbacks = mCallbacks.get();
2669 if (oldCallbacks == null) {
2670 // This launcher has exited and nobody bothered to tell us. Just bail.
2671 Log.w(TAG, "LoaderTask running with no launcher");
2672 return;
2673 }
2674
Winson Chung9b9fb962013-11-15 15:39:34 -08002675 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002676 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2677 ArrayList<LauncherAppWidgetInfo> appWidgets =
2678 new ArrayList<LauncherAppWidgetInfo>();
2679 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2680 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002681 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002682 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002683 workspaceItems.addAll(sBgWorkspaceItems);
2684 appWidgets.addAll(sBgAppWidgets);
2685 folders.putAll(sBgFolders);
2686 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002687 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002688 }
2689
Derek Prothro7aff3992013-12-10 14:00:37 -05002690 final boolean isLoadingSynchronously =
2691 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002692 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002693 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002694 if (currScreen >= orderedScreenIds.size()) {
2695 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002696 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002697 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002698 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002699 final long currentScreenId = currentScreen < 0
2700 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002701
2702 // Load all the items that are on the current page first (and in the process, unbind
2703 // all the existing workspace items before we call startBinding() below.
2704 unbindWorkspaceItemsOnMainThread();
2705
2706 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002707 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2708 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2709 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2710 new ArrayList<LauncherAppWidgetInfo>();
2711 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2712 new ArrayList<LauncherAppWidgetInfo>();
2713 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2714 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2715
Winson Chung9b9fb962013-11-15 15:39:34 -08002716 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002717 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002718 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002719 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002720 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002721 otherFolders);
2722 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2723 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2724
2725 // Tell the workspace that we're about to start binding items
2726 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002727 public void run() {
2728 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2729 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002730 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002731 }
2732 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002733 };
Winson Chung81b52252012-08-27 15:34:29 -07002734 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002735
Adam Cohendcd297f2013-06-18 13:13:40 -07002736 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2737
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002738 // Load items on the current page
2739 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2740 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002741 if (isLoadingSynchronously) {
2742 r = new Runnable() {
2743 public void run() {
2744 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002745 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002746 callbacks.onPageBoundSynchronously(currentScreen);
2747 }
2748 }
2749 };
Winson Chung81b52252012-08-27 15:34:29 -07002750 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002751 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002752
Winson Chung4a2afa32012-07-19 14:53:05 -07002753 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2754 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002755 synchronized (mDeferredBindRunnables) {
2756 mDeferredBindRunnables.clear();
2757 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002758 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002759 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002760
2761 // Tell the workspace that we're done binding items
2762 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002763 public void run() {
2764 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2765 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002766 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002767 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002768
Winson Chung98e030b2012-05-07 16:01:11 -07002769 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002770 if (DEBUG_LOADERS) {
2771 Log.d(TAG, "bound workspace in "
2772 + (SystemClock.uptimeMillis()-t) + "ms");
2773 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002774
2775 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002776 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002777 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002778 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002779 synchronized (mDeferredBindRunnables) {
2780 mDeferredBindRunnables.add(r);
2781 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002782 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002783 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002784 }
Joe Onorato36115782010-06-17 13:28:48 -04002785 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002786
Joe Onorato36115782010-06-17 13:28:48 -04002787 private void loadAndBindAllApps() {
2788 if (DEBUG_LOADERS) {
2789 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2790 }
2791 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002792 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002793 synchronized (LoaderTask.this) {
2794 if (mStopped) {
2795 return;
2796 }
2797 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002798 }
Joe Onorato36115782010-06-17 13:28:48 -04002799 } else {
2800 onlyBindAllApps();
2801 }
2802 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002803
Joe Onorato36115782010-06-17 13:28:48 -04002804 private void onlyBindAllApps() {
2805 final Callbacks oldCallbacks = mCallbacks.get();
2806 if (oldCallbacks == null) {
2807 // This launcher has exited and nobody bothered to tell us. Just bail.
2808 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2809 return;
2810 }
2811
2812 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002813 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002814 final ArrayList<AppInfo> list
2815 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002816 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002817 public void run() {
2818 final long t = SystemClock.uptimeMillis();
2819 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2820 if (callbacks != null) {
2821 callbacks.bindAllApplications(list);
2822 }
2823 if (DEBUG_LOADERS) {
2824 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2825 + (SystemClock.uptimeMillis()-t) + "ms");
2826 }
2827 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002828 };
2829 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002830 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002831 r.run();
2832 } else {
2833 mHandler.post(r);
2834 }
Joe Onorato36115782010-06-17 13:28:48 -04002835 }
2836
Winson Chung64359a52013-07-08 17:17:08 -07002837 private void loadAllApps() {
2838 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002839
Joe Onorato36115782010-06-17 13:28:48 -04002840 final Callbacks oldCallbacks = mCallbacks.get();
2841 if (oldCallbacks == null) {
2842 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002843 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002844 return;
2845 }
2846
2847 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2848 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2849
Kenny Guyed131872014-04-30 03:02:21 +01002850 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2851
Winson Chung64359a52013-07-08 17:17:08 -07002852 // Clear the list of apps
2853 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002854 for (UserHandleCompat user : profiles) {
2855 // Query for the set of apps
2856 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2857 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2858 if (DEBUG_LOADERS) {
2859 Log.d(TAG, "getActivityList took "
2860 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2861 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2862 }
2863 // Fail if we don't have any apps
2864 if (apps == null || apps.isEmpty()) {
2865 return;
2866 }
2867 // Sort the applications by name
2868 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2869 Collections.sort(apps,
2870 new LauncherModel.ShortcutNameComparator(mLabelCache));
2871 if (DEBUG_LOADERS) {
2872 Log.d(TAG, "sort took "
2873 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2874 }
Joe Onorato36115782010-06-17 13:28:48 -04002875
Kenny Guyed131872014-04-30 03:02:21 +01002876 // Create the ApplicationInfos
2877 for (int i = 0; i < apps.size(); i++) {
2878 LauncherActivityInfoCompat app = apps.get(i);
2879 // This builds the icon bitmaps.
2880 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2881 }
Winson Chung64359a52013-07-08 17:17:08 -07002882 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002883 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002884 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2885 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002886
2887 // Post callback on main thread
2888 mHandler.post(new Runnable() {
2889 public void run() {
2890 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002891 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002892 if (callbacks != null) {
2893 callbacks.bindAllApplications(added);
2894 if (DEBUG_LOADERS) {
2895 Log.d(TAG, "bound " + added.size() + " apps in "
2896 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2897 }
2898 } else {
2899 Log.i(TAG, "not binding apps: no Launcher activity");
2900 }
2901 }
2902 });
2903
Joe Onorato36115782010-06-17 13:28:48 -04002904 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002905 Log.d(TAG, "Icons processed in "
2906 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002907 }
2908 }
2909
2910 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002911 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002912 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2913 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2914 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2915 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2916 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2917 }
Joe Onorato36115782010-06-17 13:28:48 -04002918 }
2919 }
2920
2921 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002922 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002923 }
2924
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002925 private class AppsAvailabilityCheck extends BroadcastReceiver {
2926
2927 @Override
2928 public void onReceive(Context context, Intent intent) {
2929 synchronized (sBgLock) {
2930 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2931 .getInstance(mApp.getContext());
2932 ArrayList<String> packagesRemoved;
2933 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2934 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002935 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 for (String pkg : entry.getValue()) {
2937 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2938 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2939 packagesRemoved.add(pkg);
2940 }
2941 }
2942 if (!packagesRemoved.isEmpty()) {
2943 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2944 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2945 }
2946 }
Sunny Goyal34942622014-08-29 17:20:55 -07002947 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002948 }
2949 }
2950 }
2951
Joe Onorato36115782010-06-17 13:28:48 -04002952 private class PackageUpdatedTask implements Runnable {
2953 int mOp;
2954 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002955 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002956
2957 public static final int OP_NONE = 0;
2958 public static final int OP_ADD = 1;
2959 public static final int OP_UPDATE = 2;
2960 public static final int OP_REMOVE = 3; // uninstlled
2961 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2962
2963
Kenny Guyed131872014-04-30 03:02:21 +01002964 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002965 mOp = op;
2966 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002967 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002968 }
2969
2970 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002971 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002972
2973 final String[] packages = mPackages;
2974 final int N = packages.length;
2975 switch (mOp) {
2976 case OP_ADD:
2977 for (int i=0; i<N; i++) {
2978 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002979 mIconCache.remove(packages[i], mUser);
2980 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002981 }
2982 break;
2983 case OP_UPDATE:
2984 for (int i=0; i<N; i++) {
2985 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002986 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002987 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002988 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002989 }
2990 break;
2991 case OP_REMOVE:
2992 case OP_UNAVAILABLE:
2993 for (int i=0; i<N; i++) {
2994 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002995 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002996 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002997 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002998 }
2999 break;
3000 }
3001
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003002 ArrayList<AppInfo> added = null;
3003 ArrayList<AppInfo> modified = null;
3004 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003005
Adam Cohen487f7dd2012-06-28 18:12:10 -07003006 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003007 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003008 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003009 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003010 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003011 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003012 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003013 }
Winson Chung5d55f332012-07-16 20:45:03 -07003014 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003015 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003016 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003017 }
3018
Joe Onorato36115782010-06-17 13:28:48 -04003019 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
3020 if (callbacks == null) {
3021 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3022 return;
3023 }
3024
3025 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003026 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003027 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003028 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003029 addAndBindAddedWorkspaceApps(context, addedInfos);
3030 } else {
3031 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003032 }
Joe Onorato36115782010-06-17 13:28:48 -04003033 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003034
Joe Onorato36115782010-06-17 13:28:48 -04003035 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003036 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07003037
3038 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003039 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07003040 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01003041 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07003042 for (ItemInfo i : infos) {
3043 if (isShortcutInfoUpdateable(i)) {
3044 ShortcutInfo info = (ShortcutInfo) i;
3045 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003046 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07003047 updateItemInDatabase(context, info);
3048 }
3049 }
3050 }
3051
Joe Onorato36115782010-06-17 13:28:48 -04003052 mHandler.post(new Runnable() {
3053 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003054 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3055 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003056 callbacks.bindAppsUpdated(modifiedFinal);
3057 }
3058 }
3059 });
3060 }
Winson Chung83892cc2013-05-01 16:53:33 -07003061
Winson Chungdf95eb12013-10-16 14:57:07 -07003062 final ArrayList<String> removedPackageNames =
3063 new ArrayList<String>();
3064 if (mOp == OP_REMOVE) {
3065 // Mark all packages in the broadcast to be removed
3066 removedPackageNames.addAll(Arrays.asList(packages));
3067 } else if (mOp == OP_UPDATE) {
3068 // Mark disabled packages in the broadcast to be removed
3069 final PackageManager pm = context.getPackageManager();
3070 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003071 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003072 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003073 }
3074 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003075 }
3076 // Remove all the components associated with this package
3077 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003078 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003079 }
3080 // Remove all the specific components
3081 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003082 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003083 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003084 }
3085 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3086 // Remove any queued items from the install queue
3087 String spKey = LauncherAppState.getSharedPreferencesKey();
3088 SharedPreferences sp =
3089 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3090 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3091 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003092 mHandler.post(new Runnable() {
3093 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003094 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3095 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003096 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003097 }
3098 }
3099 });
Joe Onoratobe386092009-11-17 17:32:16 -08003100 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003101
Michael Jurkac402cd92013-05-20 15:49:32 +02003102 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003103 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003104 mHandler.post(new Runnable() {
3105 @Override
3106 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003107 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3108 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003109 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003110 }
3111 }
3112 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003113
3114 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003115 mHandler.post(new Runnable() {
3116 public void run() {
3117 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3118 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003119 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003120 }
3121 }
3122 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003123 }
3124 }
3125
Michael Jurkac402cd92013-05-20 15:49:32 +02003126 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3127 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3128 PackageManager packageManager = context.getPackageManager();
3129 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003130 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3131
Michael Jurkac402cd92013-05-20 15:49:32 +02003132 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3133 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003134 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003135 return widgetsAndShortcuts;
3136 }
3137
Kenny Guyed131872014-04-30 03:02:21 +01003138 private static boolean isPackageDisabled(Context context, String packageName,
3139 UserHandleCompat user) {
3140 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3141 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003142 }
Adam Cohen556f6132014-01-15 15:18:08 -08003143
Kenny Guyed131872014-04-30 03:02:21 +01003144 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3145 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003146 if (cn == null) {
3147 return false;
3148 }
Kenny Guyed131872014-04-30 03:02:21 +01003149 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3150 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003151 return false;
3152 }
Kenny Guyed131872014-04-30 03:02:21 +01003153 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003154 }
3155
Adam Cohena28b78e2014-05-20 17:03:04 -07003156 public static boolean isValidPackage(Context context, String packageName,
3157 UserHandleCompat user) {
3158 if (packageName == null) {
3159 return false;
3160 }
3161 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3162 return launcherApps.isPackageEnabledForProfile(packageName, user);
3163 }
3164
Joe Onorato9c1289c2009-08-17 11:03:03 -04003165 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003166 * Make an ShortcutInfo object for a restored application or shortcut item that points
3167 * to a package that is not yet installed on the system.
3168 */
Sunny Goyal34942622014-08-29 17:20:55 -07003169 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3170 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003171 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003172 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003173 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3174
3175 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3176 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3177 if (!TextUtils.isEmpty(title)) {
3178 info.title = title;
3179 }
3180 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3181 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3182 if (TextUtils.isEmpty(info.title)) {
3183 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3184 }
3185 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3186 } else {
3187 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3188 }
3189
Kenny Guyc2bd8102014-06-30 12:30:31 +01003190 info.contentDescription = mUserManager.getBadgedLabelForUser(
3191 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003192 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003193 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003194 return info;
3195 }
3196
3197 /**
3198 * Make an Intent object for a restored application or shortcut item that points
3199 * to the market page for the item.
3200 */
3201 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3202 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003203 return getMarketIntent(componentName.getPackageName());
3204 }
3205
3206 static Intent getMarketIntent(String packageName) {
3207 return new Intent(Intent.ACTION_VIEW)
3208 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003209 .scheme("market")
3210 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003211 .appendQueryParameter("id", packageName)
3212 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003213 }
3214
3215 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003216 * This is called from the code that adds shortcuts from the intent receiver. This
3217 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003218 */
Kenny Guyed131872014-04-30 03:02:21 +01003219 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3220 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003221 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003222 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003223
Joe Onorato56d82912010-03-07 14:32:10 -05003224 /**
3225 * Make an ShortcutInfo object for a shortcut that is an application.
3226 *
3227 * If c is not null, then it will be used to fill in missing data like the title and icon.
3228 */
Kenny Guyed131872014-04-30 03:02:21 +01003229 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3230 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003231 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003232 if (user == null) {
3233 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003234 return null;
3235 }
3236
Kenny Guyed131872014-04-30 03:02:21 +01003237 ComponentName componentName = intent.getComponent();
3238 if (componentName == null) {
3239 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3240 return null;
3241 }
3242
3243 Intent newIntent = new Intent(intent.getAction(), null);
3244 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3245 newIntent.setComponent(componentName);
3246 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003247 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003248 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3249 return null;
3250 }
3251
3252 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003253
Joe Onorato56d82912010-03-07 14:32:10 -05003254 // the resource -- This may implicitly give us back the fallback icon,
3255 // but don't worry about that. All we're doing with usingFallbackIcon is
3256 // to avoid saving lots of copies of that in the database, and most apps
3257 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003258 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003259
Joe Onorato56d82912010-03-07 14:32:10 -05003260 // the db
3261 if (icon == null) {
3262 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003263 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003264 }
3265 }
3266 // the fallback icon
3267 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003268 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003269 info.usingFallbackIcon = true;
3270 }
3271 info.setIcon(icon);
3272
Kenny Guyed131872014-04-30 03:02:21 +01003273 // From the cache.
3274 if (labelCache != null) {
3275 info.title = labelCache.get(componentName);
3276 }
3277
Joe Onorato56d82912010-03-07 14:32:10 -05003278 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003279 if (info.title == null && lai != null) {
3280 info.title = lai.getLabel();
3281 if (labelCache != null) {
3282 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003283 }
Joe Onorato56d82912010-03-07 14:32:10 -05003284 }
3285 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003286 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003287 if (c != null) {
3288 info.title = c.getString(titleIndex);
3289 }
3290 }
3291 // fall back to the class name of the activity
3292 if (info.title == null) {
3293 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003294 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003295 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003296 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003297 info.contentDescription = mUserManager.getBadgedLabelForUser(
3298 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003299 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003300 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003301
Winson Chung64359a52013-07-08 17:17:08 -07003302 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3303 ItemInfoFilter f) {
3304 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3305 for (ItemInfo i : infos) {
3306 if (i instanceof ShortcutInfo) {
3307 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003308 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003309 if (cn != null && f.filterItem(null, info, cn)) {
3310 filtered.add(info);
3311 }
3312 } else if (i instanceof FolderInfo) {
3313 FolderInfo info = (FolderInfo) i;
3314 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003315 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003316 if (cn != null && f.filterItem(info, s, cn)) {
3317 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003318 }
3319 }
Winson Chung64359a52013-07-08 17:17:08 -07003320 } else if (i instanceof LauncherAppWidgetInfo) {
3321 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3322 ComponentName cn = info.providerName;
3323 if (cn != null && f.filterItem(null, info, cn)) {
3324 filtered.add(info);
3325 }
Winson Chung8a435102012-08-30 17:16:53 -07003326 }
3327 }
Winson Chung64359a52013-07-08 17:17:08 -07003328 return new ArrayList<ItemInfo>(filtered);
3329 }
3330
Kenny Guyed131872014-04-30 03:02:21 +01003331 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3332 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003333 ItemInfoFilter filter = new ItemInfoFilter() {
3334 @Override
3335 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003336 if (info.user == null) {
3337 return cn.equals(cname);
3338 } else {
3339 return cn.equals(cname) && info.user.equals(user);
3340 }
Winson Chung64359a52013-07-08 17:17:08 -07003341 }
3342 };
3343 return filterItemInfos(sBgItemsIdMap.values(), filter);
3344 }
3345
3346 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3347 if (i instanceof ShortcutInfo) {
3348 ShortcutInfo info = (ShortcutInfo) i;
3349 // We need to check for ACTION_MAIN otherwise getComponent() might
3350 // return null for some shortcuts (for instance, for shortcuts to
3351 // web pages.)
3352 Intent intent = info.intent;
3353 ComponentName name = intent.getComponent();
3354 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3355 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3356 return true;
3357 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003358 // placeholder shortcuts get special treatment, let them through too.
Sunny Goyal34942622014-08-29 17:20:55 -07003359 if (info.isPromise()) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003360 return true;
3361 }
Winson Chung64359a52013-07-08 17:17:08 -07003362 }
3363 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003364 }
3365
3366 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003367 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003368 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003369 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003370 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3371 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003372
Joe Onorato56d82912010-03-07 14:32:10 -05003373 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003374 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003375 // Non-app shortcuts are only supported for current user.
3376 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003377 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003378
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003379 // TODO: If there's an explicit component and we can't install that, delete it.
3380
Joe Onorato56d82912010-03-07 14:32:10 -05003381 info.title = c.getString(titleIndex);
3382
Joe Onorato9c1289c2009-08-17 11:03:03 -04003383 int iconType = c.getInt(iconTypeIndex);
3384 switch (iconType) {
3385 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3386 String packageName = c.getString(iconPackageIndex);
3387 String resourceName = c.getString(iconResourceIndex);
3388 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003389 info.customIcon = false;
3390 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003391 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003392 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003393 if (resources != null) {
3394 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003395 icon = Utilities.createIconBitmap(
3396 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003397 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003398 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003399 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003400 }
Joe Onorato56d82912010-03-07 14:32:10 -05003401 // the db
3402 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003403 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003404 }
3405 // the fallback icon
3406 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003407 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003408 info.usingFallbackIcon = true;
3409 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003410 break;
3411 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003412 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003413 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003414 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003415 info.customIcon = false;
3416 info.usingFallbackIcon = true;
3417 } else {
3418 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003419 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003420 break;
3421 default:
Kenny Guyed131872014-04-30 03:02:21 +01003422 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003423 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003424 info.customIcon = false;
3425 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003426 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003427 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003428 return info;
3429 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003430
Michael Jurka931dc972011-08-05 15:08:15 -07003431 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003432 @SuppressWarnings("all") // suppress dead code warning
3433 final boolean debug = false;
3434 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003435 Log.d(TAG, "getIconFromCursor app="
3436 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3437 }
3438 byte[] data = c.getBlob(iconIndex);
3439 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003440 return Utilities.createIconBitmap(
3441 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003442 } catch (Exception e) {
3443 return null;
3444 }
3445 }
3446
Winson Chung3d503fb2011-07-13 17:25:49 -07003447 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3448 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003449 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003450 if (info == null) {
3451 return null;
3452 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003453 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003454
3455 return info;
3456 }
3457
Winson Chunga9abd0e2010-10-27 17:18:37 -07003458 /**
Winson Chung55cef262010-10-28 14:14:18 -07003459 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3460 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003461 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003462 ComponentName component) {
3463 List<AppWidgetProviderInfo> widgets =
3464 AppWidgetManager.getInstance(context).getInstalledProviders();
3465 for (AppWidgetProviderInfo info : widgets) {
3466 if (info.provider.equals(component)) {
3467 return info;
3468 }
3469 }
3470 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003471 }
3472
3473 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003474 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3475 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3476 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3477
Adam Cohend9198822011-11-22 16:42:47 -08003478 if (intent == null) {
3479 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3480 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3481 return null;
3482 }
3483
Joe Onorato0589f0f2010-02-08 13:44:00 -08003484 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003485 boolean customIcon = false;
3486 ShortcutIconResource iconResource = null;
3487
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003488 if (bitmap instanceof Bitmap) {
3489 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003490 customIcon = true;
3491 } else {
3492 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3493 if (extra != null && extra instanceof ShortcutIconResource) {
3494 try {
3495 iconResource = (ShortcutIconResource) extra;
3496 final PackageManager packageManager = context.getPackageManager();
3497 Resources resources = packageManager.getResourcesForApplication(
3498 iconResource.packageName);
3499 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003500 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003501 mIconCache.getFullResIcon(resources, id),
3502 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003503 } catch (Exception e) {
3504 Log.w(TAG, "Could not load shortcut icon: " + extra);
3505 }
3506 }
3507 }
3508
Michael Jurkac9d95c52011-08-29 14:03:34 -07003509 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003510
Kenny Guyed131872014-04-30 03:02:21 +01003511 // Only support intents for current user for now. Intents sent from other
3512 // users wouldn't get here without intent forwarding anyway.
3513 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003514 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003515 if (fallbackIcon != null) {
3516 icon = fallbackIcon;
3517 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003518 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003519 info.usingFallbackIcon = true;
3520 }
Joe Onorato56d82912010-03-07 14:32:10 -05003521 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003522 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003523
Joe Onorato0589f0f2010-02-08 13:44:00 -08003524 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003525 info.contentDescription = mUserManager.getBadgedLabelForUser(
3526 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003527 info.intent = intent;
3528 info.customIcon = customIcon;
3529 info.iconResource = iconResource;
3530
3531 return info;
3532 }
3533
Winson Chungaac01e12011-08-17 10:37:13 -07003534 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3535 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003536 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003537 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003538 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003539 }
Joe Onorato56d82912010-03-07 14:32:10 -05003540 // If this icon doesn't have a custom icon, check to see
3541 // what's stored in the DB, and if it doesn't match what
3542 // we're going to show, store what we are going to show back
3543 // into the DB. We do this so when we're loading, if the
3544 // package manager can't find an icon (for example because
3545 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003546 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003547 cache.put(info, c.getBlob(iconIndex));
3548 return true;
3549 }
3550 return false;
3551 }
3552 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3553 boolean needSave = false;
3554 try {
3555 if (data != null) {
3556 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3557 Bitmap loaded = info.getIcon(mIconCache);
3558 needSave = !saved.sameAs(loaded);
3559 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003560 needSave = true;
3561 }
Winson Chungaac01e12011-08-17 10:37:13 -07003562 } catch (Exception e) {
3563 needSave = true;
3564 }
3565 if (needSave) {
3566 Log.d(TAG, "going to save icon bitmap for info=" + info);
3567 // This is slower than is ideal, but this only happens once
3568 // or when the app is updated with a new icon.
3569 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003570 }
3571 }
3572
Joe Onorato9c1289c2009-08-17 11:03:03 -04003573 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003574 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003575 * or make a new one.
3576 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003577 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003578 // See if a placeholder was created for us already
3579 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003580 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003581 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003582 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003583 folders.put(id, folderInfo);
3584 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003585 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003586 }
3587
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003588 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003589 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003590 return new Comparator<AppInfo>() {
3591 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003592 if (a.user.equals(b.user)) {
3593 int result = collator.compare(a.title.toString().trim(),
3594 b.title.toString().trim());
3595 if (result == 0) {
3596 result = a.componentName.compareTo(b.componentName);
3597 }
3598 return result;
3599 } else {
3600 // TODO Need to figure out rules for sorting
3601 // profiles, this puts work second.
3602 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003603 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003604 }
Winson Chung11904872012-09-17 16:58:46 -07003605 };
3606 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003607 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3608 = new Comparator<AppInfo>() {
3609 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003610 if (a.firstInstallTime < b.firstInstallTime) return 1;
3611 if (a.firstInstallTime > b.firstInstallTime) return -1;
3612 return 0;
3613 }
3614 };
Winson Chung5308f242011-08-18 12:12:41 -07003615 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3616 if (info.activityInfo != null) {
3617 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3618 } else {
3619 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3620 }
3621 }
Kenny Guyed131872014-04-30 03:02:21 +01003622 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003623 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003624 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003625 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003626 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003627 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003628 }
Kenny Guyed131872014-04-30 03:02:21 +01003629 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003630 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003631 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003632 }
Kenny Guyed131872014-04-30 03:02:21 +01003633 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003634 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003635 ComponentName keyA = a.getComponentName();
3636 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003637 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003638 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003639 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003640 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003641
Winson Chung5308f242011-08-18 12:12:41 -07003642 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003643 }
Winson Chung5308f242011-08-18 12:12:41 -07003644 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003645 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003646 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003647 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003648
Winson Chung5308f242011-08-18 12:12:41 -07003649 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003650 }
Winson Chung11904872012-09-17 16:58:46 -07003651 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003652 }
3653 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003654 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003655 private final AppWidgetManagerCompat mManager;
3656 private final PackageManager mPackageManager;
3657 private final HashMap<Object, String> mLabelCache;
3658 private final Collator mCollator;
3659
3660 WidgetAndShortcutNameComparator(Context context) {
3661 mManager = AppWidgetManagerCompat.getInstance(context);
3662 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003663 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003664 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003665 }
3666 public final int compare(Object a, Object b) {
3667 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003668 if (mLabelCache.containsKey(a)) {
3669 labelA = mLabelCache.get(a);
3670 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003671 labelA = (a instanceof AppWidgetProviderInfo)
3672 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3673 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003674 mLabelCache.put(a, labelA);
3675 }
3676 if (mLabelCache.containsKey(b)) {
3677 labelB = mLabelCache.get(b);
3678 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003679 labelB = (b instanceof AppWidgetProviderInfo)
3680 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3681 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003682 mLabelCache.put(b, labelB);
3683 }
Winson Chung11904872012-09-17 16:58:46 -07003684 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003685 }
3686 };
Joe Onoratobe386092009-11-17 17:32:16 -08003687
Sunny Goyal651077b2014-06-30 14:15:31 -07003688 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3689 return (provider != null) && (provider.provider != null)
3690 && (provider.provider.getPackageName() != null);
3691 }
3692
Joe Onoratobe386092009-11-17 17:32:16 -08003693 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003694 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003695 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3696 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3697 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3698 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003699 if (mLoaderTask != null) {
3700 mLoaderTask.dumpState();
3701 } else {
3702 Log.d(TAG, "mLoaderTask=null");
3703 }
Joe Onoratobe386092009-11-17 17:32:16 -08003704 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003705}