blob: dd948916b840e21547b4ba37eea7f9804b4e229e [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
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001388 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001389 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1390 }
1391
1392 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001393 synchronized (mLock) {
1394 if (DEBUG_LOADERS) {
1395 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1396 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001397
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001398 // Clear any deferred bind-runnables from the synchronized load process
1399 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001400 synchronized (mDeferredBindRunnables) {
1401 mDeferredBindRunnables.clear();
1402 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403
Joe Onorato36115782010-06-17 13:28:48 -04001404 // Don't bother to start the thread if we know it's not going to do anything
1405 if (mCallbacks != null && mCallbacks.get() != null) {
1406 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001407 // also, don't downgrade isLaunching if we're already running
1408 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001409 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001410 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1411 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001412 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1413 } else {
1414 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1415 sWorker.post(mLoaderTask);
1416 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001417 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001418 }
1419 }
1420
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001421 void bindRemainingSynchronousPages() {
1422 // Post the remaining side pages to be loaded
1423 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001424 Runnable[] deferredBindRunnables = null;
1425 synchronized (mDeferredBindRunnables) {
1426 deferredBindRunnables = mDeferredBindRunnables.toArray(
1427 new Runnable[mDeferredBindRunnables.size()]);
1428 mDeferredBindRunnables.clear();
1429 }
1430 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001431 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001432 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001433 }
1434 }
1435
Joe Onorato36115782010-06-17 13:28:48 -04001436 public void stopLoader() {
1437 synchronized (mLock) {
1438 if (mLoaderTask != null) {
1439 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001440 }
1441 }
Joe Onorato36115782010-06-17 13:28:48 -04001442 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001443
Winson Chung76828c82013-08-19 15:43:29 -07001444 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1445 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1446 final ContentResolver contentResolver = context.getContentResolver();
1447 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1448 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1449 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1450
1451 try {
1452 final int idIndex = sc.getColumnIndexOrThrow(
1453 LauncherSettings.WorkspaceScreens._ID);
1454 final int rankIndex = sc.getColumnIndexOrThrow(
1455 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1456 while (sc.moveToNext()) {
1457 try {
1458 long screenId = sc.getLong(idIndex);
1459 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001460 orderedScreens.put(rank, screenId);
1461 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001462 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001463 }
1464 }
1465 } finally {
1466 sc.close();
1467 }
Winson Chunga90303b2013-11-15 13:05:06 -08001468
1469 // Log to disk
1470 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1471 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1472 for (Integer i : orderedScreens.keySet()) {
1473 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1474 }
1475 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1476 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001477 return orderedScreens;
1478 }
1479
Michael Jurkac57b7a82011-08-09 22:02:20 -07001480 public boolean isAllAppsLoaded() {
1481 return mAllAppsLoaded;
1482 }
1483
Winson Chung36a62fe2012-05-06 18:04:42 -07001484 boolean isLoadingWorkspace() {
1485 synchronized (mLock) {
1486 if (mLoaderTask != null) {
1487 return mLoaderTask.isLoadingWorkspace();
1488 }
1489 }
1490 return false;
1491 }
1492
Joe Onorato36115782010-06-17 13:28:48 -04001493 /**
1494 * Runnable for the thread that loads the contents of the launcher:
1495 * - workspace icons
1496 * - widgets
1497 * - all apps icons
1498 */
1499 private class LoaderTask implements Runnable {
1500 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001501 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001502 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001503 private boolean mStopped;
1504 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001505 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001506
Winson Chungc3eecff2011-07-11 17:44:15 -07001507 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001508
Dan Sandlerd5024042014-01-09 15:01:33 -05001509 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001510 mContext = context;
1511 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001512 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001513 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001514 }
1515
Joe Onorato36115782010-06-17 13:28:48 -04001516 boolean isLaunching() {
1517 return mIsLaunching;
1518 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001519
Winson Chung36a62fe2012-05-06 18:04:42 -07001520 boolean isLoadingWorkspace() {
1521 return mIsLoadingAndBindingWorkspace;
1522 }
1523
Winson Chungc763c4e2013-07-19 13:49:06 -07001524 /** Returns whether this is an upgrade path */
1525 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001526 mIsLoadingAndBindingWorkspace = true;
1527
Joe Onorato36115782010-06-17 13:28:48 -04001528 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001529 if (DEBUG_LOADERS) {
1530 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001531 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001532
Winson Chungc763c4e2013-07-19 13:49:06 -07001533 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001534 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001535 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001536 synchronized (LoaderTask.this) {
1537 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001538 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001539 }
1540 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001541 }
1542 }
1543
Joe Onorato36115782010-06-17 13:28:48 -04001544 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001545 bindWorkspace(-1, isUpgradePath);
1546 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001547 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001548
Joe Onorato36115782010-06-17 13:28:48 -04001549 private void waitForIdle() {
1550 // Wait until the either we're stopped or the other threads are done.
1551 // This way we don't start loading all apps until the workspace has settled
1552 // down.
1553 synchronized (LoaderTask.this) {
1554 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001555
Joe Onorato36115782010-06-17 13:28:48 -04001556 mHandler.postIdle(new Runnable() {
1557 public void run() {
1558 synchronized (LoaderTask.this) {
1559 mLoadAndBindStepFinished = true;
1560 if (DEBUG_LOADERS) {
1561 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001562 }
Joe Onorato36115782010-06-17 13:28:48 -04001563 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001564 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001565 }
Joe Onorato36115782010-06-17 13:28:48 -04001566 });
1567
Michael Jurkac7700af2013-05-14 20:17:58 +02001568 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001569 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001570 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1571 // wait no longer than 1sec at a time
1572 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001573 } catch (InterruptedException ex) {
1574 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001575 }
1576 }
Joe Onorato36115782010-06-17 13:28:48 -04001577 if (DEBUG_LOADERS) {
1578 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001579 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001580 + "ms for previous step to finish binding");
1581 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001582 }
Joe Onorato36115782010-06-17 13:28:48 -04001583 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001584
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001586 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001587 // Ensure that we have a valid page index to load synchronously
1588 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1589 "valid page index");
1590 }
1591 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1592 // Ensure that we don't try and bind a specified page when the pages have not been
1593 // loaded already (we should load everything asynchronously in that case)
1594 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1595 }
1596 synchronized (mLock) {
1597 if (mIsLoaderTaskRunning) {
1598 // Ensure that we are never running the background loading at this point since
1599 // we also touch the background collections
1600 throw new RuntimeException("Error! Background loading is already running");
1601 }
1602 }
1603
1604 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1605 // data structures, we can't allow any other thread to touch that data, but because
1606 // this call is synchronous, we can get away with not locking).
1607
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001608 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001609 // operations from the previous activity. We need to ensure that all queued operations
1610 // are executed before any synchronous binding work is done.
1611 mHandler.flush();
1612
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001613 // Divide the set of loaded items into those that we are binding synchronously, and
1614 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001615 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001616 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1617 // arise from that.
1618 onlyBindAllApps();
1619 }
1620
Joe Onorato36115782010-06-17 13:28:48 -04001621 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001622 boolean isUpgrade = false;
1623
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001624 synchronized (mLock) {
1625 mIsLoaderTaskRunning = true;
1626 }
Joe Onorato36115782010-06-17 13:28:48 -04001627 // Optimize for end-user experience: if the Launcher is up and // running with the
1628 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1629 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001630 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001631 // Elevate priority when Home launches for the first time to avoid
1632 // starving at boot time. Staring at a blank home is not cool.
1633 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001634 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1635 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001636 android.os.Process.setThreadPriority(mIsLaunching
1637 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1638 }
Winson Chung64359a52013-07-08 17:17:08 -07001639 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001640 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001641
Joe Onorato36115782010-06-17 13:28:48 -04001642 if (mStopped) {
1643 break keep_running;
1644 }
1645
1646 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1647 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001648 synchronized (mLock) {
1649 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001650 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001651 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652 }
1653 }
Joe Onorato36115782010-06-17 13:28:48 -04001654 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001655
1656 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001657 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1658 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001659
1660 // Restore the default thread priority after we are done loading items
1661 synchronized (mLock) {
1662 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1663 }
Joe Onorato36115782010-06-17 13:28:48 -04001664 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001665
Winson Chungaac01e12011-08-17 10:37:13 -07001666 // Update the saved icons if necessary
1667 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001668 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001669 for (Object key : sBgDbIconCache.keySet()) {
1670 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1671 }
1672 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001673 }
Winson Chungaac01e12011-08-17 10:37:13 -07001674
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001675 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001676 // Ensure that all the applications that are in the system are
1677 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001678 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001679 verifyApplications();
1680 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001681 }
1682
Joe Onorato36115782010-06-17 13:28:48 -04001683 // Clear out this reference, otherwise we end up holding it until all of the
1684 // callback runnables are done.
1685 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001686
Joe Onorato36115782010-06-17 13:28:48 -04001687 synchronized (mLock) {
1688 // If we are still the last one to be scheduled, remove ourselves.
1689 if (mLoaderTask == this) {
1690 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001691 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001692 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001693 }
Joe Onorato36115782010-06-17 13:28:48 -04001694 }
1695
1696 public void stopLocked() {
1697 synchronized (LoaderTask.this) {
1698 mStopped = true;
1699 this.notify();
1700 }
1701 }
1702
1703 /**
1704 * Gets the callbacks object. If we've been stopped, or if the launcher object
1705 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1706 * object that was around when the deferred message was scheduled, and if there's
1707 * a new Callbacks object around then also return null. This will save us from
1708 * calling onto it with data that will be ignored.
1709 */
1710 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1711 synchronized (mLock) {
1712 if (mStopped) {
1713 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001714 }
Joe Onorato36115782010-06-17 13:28:48 -04001715
1716 if (mCallbacks == null) {
1717 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001718 }
Joe Onorato36115782010-06-17 13:28:48 -04001719
1720 final Callbacks callbacks = mCallbacks.get();
1721 if (callbacks != oldCallbacks) {
1722 return null;
1723 }
1724 if (callbacks == null) {
1725 Log.w(TAG, "no mCallbacks");
1726 return null;
1727 }
1728
1729 return callbacks;
1730 }
1731 }
1732
Winson Chungc763c4e2013-07-19 13:49:06 -07001733 private void verifyApplications() {
1734 final Context context = mApp.getContext();
1735
1736 // Cross reference all the applications in our apps list with items in the workspace
1737 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001738 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001739 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001740 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001741 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001742 if (tmpInfos.isEmpty()) {
1743 // We are missing an application icon, so add this to the workspace
1744 added.add(app);
1745 // This is a rare event, so lets log it
1746 Log.e(TAG, "Missing Application on load: " + app);
1747 }
1748 }
1749 }
1750 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001751 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001752 }
1753 }
1754
Joe Onorato36115782010-06-17 13:28:48 -04001755 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001756 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001757 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001758 LauncherAppState app = LauncherAppState.getInstance();
1759 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001760 final int countX = (int) grid.numColumns;
1761 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001762
Adam Cohendcd297f2013-06-18 13:13:40 -07001763 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001764 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001765 // Return early if we detect that an item is under the hotseat button
1766 if (mCallbacks == null ||
1767 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001768 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001769 Log.e(TAG, "Error loading shortcut into hotseat " + item
1770 + " into position (" + item.screenId + ":" + item.cellX + ","
1771 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001772 return false;
1773 }
1774
Dan Sandler295ae182013-12-10 16:05:47 -05001775 final ItemInfo[][] hotseatItems =
1776 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1777
Adam Cohenae4409d2013-11-26 10:34:59 -08001778 if (item.screenId >= grid.numHotseatIcons) {
1779 Log.e(TAG, "Error loading shortcut " + item
1780 + " into hotseat position " + item.screenId
1781 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1782 + ")");
1783 return false;
1784 }
1785
Dan Sandler295ae182013-12-10 16:05:47 -05001786 if (hotseatItems != null) {
1787 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001788 Log.e(TAG, "Error loading shortcut into hotseat " + item
1789 + " into position (" + item.screenId + ":" + item.cellX + ","
1790 + item.cellY + ") occupied by "
1791 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1792 [(int) item.screenId][0]);
1793 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001794 } else {
1795 hotseatItems[(int) item.screenId][0] = item;
1796 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001797 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001798 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001799 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 items[(int) item.screenId][0] = item;
1801 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001802 return true;
1803 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001804 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1805 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001806 return true;
1807 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001808
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001810 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001811 occupied.put(item.screenId, items);
1812 }
1813
Dan Sandler295ae182013-12-10 16:05:47 -05001814 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001815 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1816 item.cellX < 0 || item.cellY < 0 ||
1817 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1818 Log.e(TAG, "Error loading shortcut " + item
1819 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1820 + item.cellX + "," + item.cellY
1821 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1822 return false;
1823 }
1824
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001825 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001826 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1827 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001828 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001829 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001830 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001831 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001832 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001834 return false;
1835 }
1836 }
1837 }
1838 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1839 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001840 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001841 }
1842 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001843
Joe Onorato36115782010-06-17 13:28:48 -04001844 return true;
1845 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001846
Winson Chungba9c37f2013-08-30 14:11:37 -07001847 /** Clears all the sBg data structures */
1848 private void clearSBgDataStructures() {
1849 synchronized (sBgLock) {
1850 sBgWorkspaceItems.clear();
1851 sBgAppWidgets.clear();
1852 sBgFolders.clear();
1853 sBgItemsIdMap.clear();
1854 sBgDbIconCache.clear();
1855 sBgWorkspaceScreens.clear();
1856 }
1857 }
1858
Dan Sandlerd5024042014-01-09 15:01:33 -05001859 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001860 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001861 // Log to disk
1862 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1863
Joe Onorato36115782010-06-17 13:28:48 -04001864 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001865
Joe Onorato36115782010-06-17 13:28:48 -04001866 final Context context = mContext;
1867 final ContentResolver contentResolver = context.getContentResolver();
1868 final PackageManager manager = context.getPackageManager();
1869 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1870 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001871 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1872 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001873 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001874
Winson Chung892c74d2013-08-22 16:15:50 -07001875 LauncherAppState app = LauncherAppState.getInstance();
1876 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1877 int countX = (int) grid.numColumns;
1878 int countY = (int) grid.numRows;
1879
Dan Sandlerd5024042014-01-09 15:01:33 -05001880 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1881 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1882 LauncherAppState.getLauncherProvider().deleteDatabase();
1883 }
1884
1885 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1886 // append the user's Launcher2 shortcuts
1887 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1888 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1889 } else {
1890 // Make sure the default workspace is loaded
1891 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001892 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001893 }
Adam Cohene25af792013-06-06 23:08:25 -07001894
Adam Cohen71483f42014-05-15 14:04:01 -07001895 // This code path is for our old migration code and should no longer be exercised
1896 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001897
Winson Chung9f9f00b2013-11-15 13:27:00 -08001898 // Log to disk
1899 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001900
Winson Chung2abf94d2012-07-18 18:16:38 -07001901 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001902 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001903 final HashSet<String> installingPkgs = PackageInstallerCompat
1904 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001905
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001907 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001908 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001909 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001910 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001911
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001912 // +1 for the hotseat (it can be larger than the workspace)
1913 // Load workspace in reverse order to ensure that latest items are loaded first (and
1914 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001915 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001916
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001917 try {
1918 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1919 final int intentIndex = c.getColumnIndexOrThrow
1920 (LauncherSettings.Favorites.INTENT);
1921 final int titleIndex = c.getColumnIndexOrThrow
1922 (LauncherSettings.Favorites.TITLE);
1923 final int iconTypeIndex = c.getColumnIndexOrThrow(
1924 LauncherSettings.Favorites.ICON_TYPE);
1925 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1926 final int iconPackageIndex = c.getColumnIndexOrThrow(
1927 LauncherSettings.Favorites.ICON_PACKAGE);
1928 final int iconResourceIndex = c.getColumnIndexOrThrow(
1929 LauncherSettings.Favorites.ICON_RESOURCE);
1930 final int containerIndex = c.getColumnIndexOrThrow(
1931 LauncherSettings.Favorites.CONTAINER);
1932 final int itemTypeIndex = c.getColumnIndexOrThrow(
1933 LauncherSettings.Favorites.ITEM_TYPE);
1934 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1935 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001936 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1937 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001938 final int screenIndex = c.getColumnIndexOrThrow(
1939 LauncherSettings.Favorites.SCREEN);
1940 final int cellXIndex = c.getColumnIndexOrThrow
1941 (LauncherSettings.Favorites.CELLX);
1942 final int cellYIndex = c.getColumnIndexOrThrow
1943 (LauncherSettings.Favorites.CELLY);
1944 final int spanXIndex = c.getColumnIndexOrThrow
1945 (LauncherSettings.Favorites.SPANX);
1946 final int spanYIndex = c.getColumnIndexOrThrow(
1947 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001948 final int restoredIndex = c.getColumnIndexOrThrow(
1949 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001950 final int profileIdIndex = c.getColumnIndexOrThrow(
1951 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001952 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1953 //final int displayModeIndex = c.getColumnIndexOrThrow(
1954 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001955
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001956 ShortcutInfo info;
1957 String intentDescription;
1958 LauncherAppWidgetInfo appWidgetInfo;
1959 int container;
1960 long id;
1961 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001962 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001963
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001965 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001966 try {
1967 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001968 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001969 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001970
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001971 switch (itemType) {
1972 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1973 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001974 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001975 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001976 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001977 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001978 int promiseType = c.getInt(restoredIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001979 if (user == null) {
1980 // User has been deleted remove the item.
1981 itemsToRemove.add(id);
1982 continue;
1983 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001984 try {
1985 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001986 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001987 if (cn != null && cn.getPackageName() != null) {
1988 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1989 cn.getPackageName(), user);
1990 boolean validComponent = validPkg &&
1991 launcherApps.isActivityEnabledForProfile(cn, user);
1992
1993 if (validComponent) {
1994 if (restored) {
1995 // no special handling necessary for this item
1996 restoredRows.add(id);
1997 restored = false;
1998 }
1999 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07002000 intent = null;
2001 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2002 // We allow auto install apps to have their intent
2003 // updated after an install.
2004 intent = manager.getLaunchIntentForPackage(
2005 cn.getPackageName());
2006 if (intent != null) {
2007 ContentValues values = new ContentValues();
2008 values.put(LauncherSettings.Favorites.INTENT,
2009 intent.toUri(0));
2010 String where = BaseColumns._ID + "= ?";
2011 String[] args = {Long.toString(id)};
2012 contentResolver.update(contentUri, values, where, args);
2013 }
2014 }
2015
2016 if (intent == null) {
2017 // The app is installed but the component is no
2018 // longer available.
2019 Launcher.addDumpLog(TAG,
2020 "Invalid component removed: " + cn, true);
2021 itemsToRemove.add(id);
2022 continue;
2023 } else {
2024 // no special handling necessary for this item
2025 restoredRows.add(id);
2026 restored = false;
2027 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002028 } else if (restored) {
2029 // Package is not yet available but might be
2030 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002031 Launcher.addDumpLog(TAG,
2032 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002033
2034 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2035 // Restore has started once.
2036 } else if (installingPkgs.contains(cn.getPackageName())) {
2037 // App restore has started. Update the flag
2038 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2039 ContentValues values = new ContentValues();
2040 values.put(LauncherSettings.Favorites.RESTORED,
2041 promiseType);
2042 String where = BaseColumns._ID + "= ?";
2043 String[] args = {Long.toString(id)};
2044 contentResolver.update(contentUri, values, where, args);
2045
2046 } else if (REMOVE_UNRESTORED_ICONS) {
2047 Launcher.addDumpLog(TAG,
2048 "Unrestored package removed: " + cn, true);
2049 itemsToRemove.add(id);
2050 continue;
2051 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002052 } else if (isSdCardReady) {
2053 // Do not wait for external media load anymore.
2054 // Log the invalid package, and remove it
2055 Launcher.addDumpLog(TAG,
2056 "Invalid package removed: " + cn, true);
2057 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002058 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002059 } else {
2060 // SdCard is not ready yet. Package might get available,
2061 // once it is ready.
2062 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2063 + " (check again later)", true);
2064 HashSet<String> pkgs = sPendingPackages.get(user);
2065 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002066 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002067 sPendingPackages.put(user, pkgs);
2068 }
2069 pkgs.add(cn.getPackageName());
2070 allowMissingTarget = true;
2071 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002072 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002073 } else if (cn == null) {
2074 // For shortcuts with no component, keep them as they are
2075 restoredRows.add(id);
2076 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002077 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002078 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002079 Launcher.addDumpLog(TAG,
2080 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002081 continue;
2082 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002083
Chris Wrenf4d08112014-01-16 18:13:56 -05002084 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002085 if (user.equals(UserHandleCompat.myUserHandle())) {
2086 Launcher.addDumpLog(TAG,
2087 "constructing info for partially restored package",
2088 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002089 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002090 intent = getRestoredItemIntent(c, context, intent);
2091 } else {
2092 // Don't restore items for other profiles.
2093 itemsToRemove.add(id);
2094 continue;
2095 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002096 } else if (itemType ==
2097 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002098 info = getShortcutInfo(manager, intent, user, context, c,
2099 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002100 } else {
2101 info = getShortcutInfo(c, context, iconTypeIndex,
2102 iconPackageIndex, iconResourceIndex, iconIndex,
2103 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002104
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 // App shortcuts that used to be automatically added to Launcher
2106 // didn't always have the correct intent flags set, so do that
2107 // here
2108 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002109 intent.getCategories() != null &&
2110 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002111 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 intent.addFlags(
2113 Intent.FLAG_ACTIVITY_NEW_TASK |
2114 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2115 }
Michael Jurka96879562012-03-22 05:54:33 -07002116 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002117
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002119 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 container = c.getInt(containerIndex);
2122 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002123 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002124 info.cellX = c.getInt(cellXIndex);
2125 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002126 info.spanX = 1;
2127 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002128 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002129 info.isDisabled = isSafeMode
2130 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002131
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002132 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002133 deleteOnInvalidPlacement.set(false);
2134 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2135 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002136 itemsToRemove.add(id);
2137 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002138 break;
2139 }
2140
2141 switch (container) {
2142 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2143 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2144 sBgWorkspaceItems.add(info);
2145 break;
2146 default:
2147 // Item is in a user folder
2148 FolderInfo folderInfo =
2149 findOrMakeFolder(sBgFolders, container);
2150 folderInfo.add(info);
2151 break;
2152 }
2153 sBgItemsIdMap.put(info.id, info);
2154
2155 // now that we've loaded everthing re-save it with the
2156 // icon in case it disappears somehow.
2157 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002158 } else {
2159 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002160 }
2161 break;
2162
2163 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2164 id = c.getLong(idIndex);
2165 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2166
2167 folderInfo.title = c.getString(titleIndex);
2168 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002169 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002171 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002172 folderInfo.cellX = c.getInt(cellXIndex);
2173 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002174 folderInfo.spanX = 1;
2175 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002176
Daniel Sandler8802e962010-05-26 16:28:16 -04002177 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002178 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002179 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002180 deleteOnInvalidPlacement)) {
2181 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002182 itemsToRemove.add(id);
2183 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002184 break;
2185 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002186
Joe Onorato9c1289c2009-08-17 11:03:03 -04002187 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002188 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2189 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2190 sBgWorkspaceItems.add(folderInfo);
2191 break;
Joe Onorato36115782010-06-17 13:28:48 -04002192 }
Joe Onorato17a89222011-02-08 17:26:11 -08002193
Chris Wrenf4d08112014-01-16 18:13:56 -05002194 if (restored) {
2195 // no special handling required for restored folders
2196 restoredRows.add(id);
2197 }
2198
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002199 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2200 sBgFolders.put(folderInfo.id, folderInfo);
2201 break;
2202
2203 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2204 // Read all Launcher-specific widget details
2205 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002206 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002207 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002208 final ComponentName component =
2209 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002210
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002212 final boolean isIdValid = (restoreStatus &
2213 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002214
Sunny Goyalff572272014-07-23 13:58:07 -07002215 final boolean wasProviderReady = (restoreStatus &
2216 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002217
Sunny Goyalff572272014-07-23 13:58:07 -07002218 final AppWidgetProviderInfo provider = isIdValid
2219 ? widgets.getAppWidgetInfo(appWidgetId)
2220 : findAppWidgetProviderInfoWithComponent(context, component);
2221
2222 final boolean isProviderReady = isValidProvider(provider);
2223 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002224 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002225 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002226 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002227 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 itemsToRemove.add(id);
2229 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002230 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002231 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2232 provider.provider);
2233 int[] minSpan =
2234 Launcher.getMinSpanForWidget(context, provider);
2235 appWidgetInfo.minSpanX = minSpan[0];
2236 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002237
2238 int status = restoreStatus;
2239 if (!wasProviderReady) {
2240 // If provider was not previously ready, update the
2241 // status and UI flag.
2242
2243 // Id would be valid only if the widget restore broadcast was received.
2244 if (isIdValid) {
2245 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2246 } else {
2247 status &= ~LauncherAppWidgetInfo
2248 .FLAG_PROVIDER_NOT_READY;
2249 }
2250 }
2251 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002252 } else {
2253 Log.v(TAG, "Widget restore pending id=" + id
2254 + " appWidgetId=" + appWidgetId
2255 + " status =" + restoreStatus);
2256 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002257 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002258 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002259
2260 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2261 // Restore has started once.
2262 } else if (installingPkgs.contains(component.getPackageName())) {
2263 // App restore has started. Update the flag
2264 appWidgetInfo.restoreStatus |=
2265 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
2266 } else if (REMOVE_UNRESTORED_ICONS) {
2267 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002268 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002269 itemsToRemove.add(id);
2270 continue;
2271 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002272 }
Sunny Goyalff572272014-07-23 13:58:07 -07002273
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002274 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002275 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 appWidgetInfo.cellX = c.getInt(cellXIndex);
2277 appWidgetInfo.cellY = c.getInt(cellYIndex);
2278 appWidgetInfo.spanX = c.getInt(spanXIndex);
2279 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002280
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 container = c.getInt(containerIndex);
2282 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2283 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2284 Log.e(TAG, "Widget found where container != " +
2285 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2286 continue;
2287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288
Adam Cohene25af792013-06-06 23:08:25 -07002289 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002290 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002291 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002292 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002293 deleteOnInvalidPlacement)) {
2294 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002295 itemsToRemove.add(id);
2296 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002297 break;
2298 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002299
Sunny Goyal94485362014-09-18 16:13:58 -07002300 String providerName = appWidgetInfo.providerName.flattenToString();
2301 if (!providerName.equals(savedProvider) ||
2302 (appWidgetInfo.restoreStatus != restoreStatus)) {
2303 ContentValues values = new ContentValues();
2304 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2305 providerName);
2306 values.put(LauncherSettings.Favorites.RESTORED,
2307 appWidgetInfo.restoreStatus);
2308 String where = BaseColumns._ID + "= ?";
2309 String[] args = {Long.toString(id)};
2310 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002311 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2313 sBgAppWidgets.add(appWidgetInfo);
2314 }
Joe Onorato36115782010-06-17 13:28:48 -04002315 break;
2316 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002317 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002318 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002319 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002320 }
2321 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002322 if (c != null) {
2323 c.close();
2324 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002325 }
2326
Winson Chungba9c37f2013-08-30 14:11:37 -07002327 // Break early if we've stopped loading
2328 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002329 clearSBgDataStructures();
2330 return false;
2331 }
2332
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002333 if (itemsToRemove.size() > 0) {
2334 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002335 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002336 // Remove dead items
2337 for (long id : itemsToRemove) {
2338 if (DEBUG_LOADERS) {
2339 Log.d(TAG, "Removed id = " + id);
2340 }
2341 // Don't notify content observers
2342 try {
2343 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2344 null, null);
2345 } catch (RemoteException e) {
2346 Log.w(TAG, "Could not remove id = " + id);
2347 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002348 }
2349 }
2350
Chris Wrenf4d08112014-01-16 18:13:56 -05002351 if (restoredRows.size() > 0) {
2352 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002353 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002354 // Update restored items that no longer require special handling
2355 try {
2356 StringBuilder selectionBuilder = new StringBuilder();
2357 selectionBuilder.append(LauncherSettings.Favorites._ID);
2358 selectionBuilder.append(" IN (");
2359 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2360 selectionBuilder.append(")");
2361 ContentValues values = new ContentValues();
2362 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002363 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002364 values, selectionBuilder.toString(), null);
2365 } catch (RemoteException e) {
2366 Log.w(TAG, "Could not update restored rows");
2367 }
2368 }
2369
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002370 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2371 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002372 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002373 null, sWorker);
2374 }
2375
Winson Chungc763c4e2013-07-19 13:49:06 -07002376 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 long maxScreenId = 0;
2378 // If we're importing we use the old screen order.
2379 for (ItemInfo item: sBgItemsIdMap.values()) {
2380 long screenId = item.screenId;
2381 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2382 !sBgWorkspaceScreens.contains(screenId)) {
2383 sBgWorkspaceScreens.add(screenId);
2384 if (screenId > maxScreenId) {
2385 maxScreenId = screenId;
2386 }
2387 }
2388 }
2389 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002390 // Log to disk
2391 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2392 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2393 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002394
Michael Jurka414300a2013-08-27 15:42:35 +02002395 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002396 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002397
2398 // Update the max item id after we load an old db
2399 long maxItemId = 0;
2400 // If we're importing we use the old screen order.
2401 for (ItemInfo item: sBgItemsIdMap.values()) {
2402 maxItemId = Math.max(maxItemId, item.id);
2403 }
Michael Jurka414300a2013-08-27 15:42:35 +02002404 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002405 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002406 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2407 for (Integer i : orderedScreens.keySet()) {
2408 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002409 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002410 // Log to disk
2411 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2412 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002413
2414 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002415 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002416 for (ItemInfo item: sBgItemsIdMap.values()) {
2417 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002418 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2419 unusedScreens.contains(screenId)) {
2420 unusedScreens.remove(screenId);
2421 }
2422 }
2423
2424 // If there are any empty screens remove them, and update.
2425 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002426 // Log to disk
2427 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2428 TextUtils.join(", ", unusedScreens), true);
2429
Winson Chung933bae62013-08-29 11:42:30 -07002430 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002431 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2432 }
2433 }
2434
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 if (DEBUG_LOADERS) {
2436 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2437 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002438 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002439 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002441
Daniel Sandler566da102013-06-25 23:43:45 -04002442 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002443 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002444 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002445 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002446 line += " | ";
2447 }
Winson Chung892c74d2013-08-22 16:15:50 -07002448 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002449 ItemInfo[][] screen = occupied.get(screenId);
2450 if (x < screen.length && y < screen[x].length) {
2451 line += (screen[x][y] != null) ? "#" : ".";
2452 } else {
2453 line += "!";
2454 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002455 }
Joe Onorato36115782010-06-17 13:28:48 -04002456 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002458 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002459 }
Joe Onorato36115782010-06-17 13:28:48 -04002460 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002461 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002462 }
2463
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002464 /** Filters the set of items who are directly or indirectly (via another container) on the
2465 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002466 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467 ArrayList<ItemInfo> allWorkspaceItems,
2468 ArrayList<ItemInfo> currentScreenItems,
2469 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002470 // Purge any null ItemInfos
2471 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2472 while (iter.hasNext()) {
2473 ItemInfo i = iter.next();
2474 if (i == null) {
2475 iter.remove();
2476 }
2477 }
2478
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002479 // Order the set of items by their containers first, this allows use to walk through the
2480 // list sequentially, build up a list of containers that are in the specified screen,
2481 // as well as all items in those containers.
2482 Set<Long> itemsOnScreen = new HashSet<Long>();
2483 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2484 @Override
2485 public int compare(ItemInfo lhs, ItemInfo rhs) {
2486 return (int) (lhs.container - rhs.container);
2487 }
2488 });
2489 for (ItemInfo info : allWorkspaceItems) {
2490 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002491 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 currentScreenItems.add(info);
2493 itemsOnScreen.add(info.id);
2494 } else {
2495 otherScreenItems.add(info);
2496 }
2497 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2498 currentScreenItems.add(info);
2499 itemsOnScreen.add(info.id);
2500 } else {
2501 if (itemsOnScreen.contains(info.container)) {
2502 currentScreenItems.add(info);
2503 itemsOnScreen.add(info.id);
2504 } else {
2505 otherScreenItems.add(info);
2506 }
2507 }
2508 }
2509 }
2510
2511 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002512 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002513 ArrayList<LauncherAppWidgetInfo> appWidgets,
2514 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2515 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002516
2517 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002518 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002519 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002520 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 currentScreenWidgets.add(widget);
2522 } else {
2523 otherScreenWidgets.add(widget);
2524 }
2525 }
2526 }
2527
2528 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002529 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 HashMap<Long, ItemInfo> itemsIdMap,
2531 HashMap<Long, FolderInfo> folders,
2532 HashMap<Long, FolderInfo> currentScreenFolders,
2533 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534
2535 for (long id : folders.keySet()) {
2536 ItemInfo info = itemsIdMap.get(id);
2537 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002538 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002540 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002541 currentScreenFolders.put(id, folder);
2542 } else {
2543 otherScreenFolders.put(id, folder);
2544 }
2545 }
2546 }
2547
2548 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2549 * right) */
2550 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002551 final LauncherAppState app = LauncherAppState.getInstance();
2552 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553 // XXX: review this
2554 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002555 @Override
2556 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002557 int cellCountX = (int) grid.numColumns;
2558 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002559 int screenOffset = cellCountX * cellCountY;
2560 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002561 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002562 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002563 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002564 rhs.cellY * cellCountX + rhs.cellX);
2565 return (int) (lr - rr);
2566 }
2567 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002568 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002569
Adam Cohendcd297f2013-06-18 13:13:40 -07002570 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2571 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002572 final Runnable r = new Runnable() {
2573 @Override
2574 public void run() {
2575 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2576 if (callbacks != null) {
2577 callbacks.bindScreens(orderedScreens);
2578 }
2579 }
2580 };
2581 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2582 }
2583
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2585 final ArrayList<ItemInfo> workspaceItems,
2586 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2587 final HashMap<Long, FolderInfo> folders,
2588 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002589
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002590 final boolean postOnMainThread = (deferredBindRunnables != null);
2591
2592 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002593 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002594 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002595 final int start = i;
2596 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002597 final Runnable r = new Runnable() {
2598 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002599 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002600 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002601 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002602 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2603 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002604 }
2605 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002606 };
2607 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002608 synchronized (deferredBindRunnables) {
2609 deferredBindRunnables.add(r);
2610 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002612 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002613 }
Joe Onorato36115782010-06-17 13:28:48 -04002614 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615
2616 // Bind the folders
2617 if (!folders.isEmpty()) {
2618 final Runnable r = new Runnable() {
2619 public void run() {
2620 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2621 if (callbacks != null) {
2622 callbacks.bindFolders(folders);
2623 }
2624 }
2625 };
2626 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002627 synchronized (deferredBindRunnables) {
2628 deferredBindRunnables.add(r);
2629 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002630 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002631 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002632 }
2633 }
2634
2635 // Bind the widgets, one at a time
2636 N = appWidgets.size();
2637 for (int i = 0; i < N; i++) {
2638 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2639 final Runnable r = new Runnable() {
2640 public void run() {
2641 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2642 if (callbacks != null) {
2643 callbacks.bindAppWidget(widget);
2644 }
2645 }
2646 };
2647 if (postOnMainThread) {
2648 deferredBindRunnables.add(r);
2649 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002650 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002651 }
2652 }
2653 }
2654
2655 /**
2656 * Binds all loaded data to actual views on the main thread.
2657 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002658 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002659 final long t = SystemClock.uptimeMillis();
2660 Runnable r;
2661
2662 // Don't use these two variables in any of the callback runnables.
2663 // Otherwise we hold a reference to them.
2664 final Callbacks oldCallbacks = mCallbacks.get();
2665 if (oldCallbacks == null) {
2666 // This launcher has exited and nobody bothered to tell us. Just bail.
2667 Log.w(TAG, "LoaderTask running with no launcher");
2668 return;
2669 }
2670
Winson Chung9b9fb962013-11-15 15:39:34 -08002671 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2673 ArrayList<LauncherAppWidgetInfo> appWidgets =
2674 new ArrayList<LauncherAppWidgetInfo>();
2675 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2676 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002677 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002678 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002679 workspaceItems.addAll(sBgWorkspaceItems);
2680 appWidgets.addAll(sBgAppWidgets);
2681 folders.putAll(sBgFolders);
2682 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002683 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 }
2685
Derek Prothro7aff3992013-12-10 14:00:37 -05002686 final boolean isLoadingSynchronously =
2687 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002688 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002689 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002690 if (currScreen >= orderedScreenIds.size()) {
2691 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002692 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002693 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002694 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002695 final long currentScreenId = currentScreen < 0
2696 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002697
2698 // Load all the items that are on the current page first (and in the process, unbind
2699 // all the existing workspace items before we call startBinding() below.
2700 unbindWorkspaceItemsOnMainThread();
2701
2702 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002703 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2704 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2705 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2706 new ArrayList<LauncherAppWidgetInfo>();
2707 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2708 new ArrayList<LauncherAppWidgetInfo>();
2709 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2710 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2711
Winson Chung9b9fb962013-11-15 15:39:34 -08002712 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002713 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002714 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002715 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002716 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002717 otherFolders);
2718 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2719 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2720
2721 // Tell the workspace that we're about to start binding items
2722 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002723 public void run() {
2724 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2725 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002726 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002727 }
2728 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002729 };
Winson Chung81b52252012-08-27 15:34:29 -07002730 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002731
Adam Cohendcd297f2013-06-18 13:13:40 -07002732 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2733
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002734 // Load items on the current page
2735 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2736 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002737 if (isLoadingSynchronously) {
2738 r = new Runnable() {
2739 public void run() {
2740 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002741 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002742 callbacks.onPageBoundSynchronously(currentScreen);
2743 }
2744 }
2745 };
Winson Chung81b52252012-08-27 15:34:29 -07002746 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002747 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002748
Winson Chung4a2afa32012-07-19 14:53:05 -07002749 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2750 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002751 synchronized (mDeferredBindRunnables) {
2752 mDeferredBindRunnables.clear();
2753 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002754 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002755 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002756
2757 // Tell the workspace that we're done binding items
2758 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002759 public void run() {
2760 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2761 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002762 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002763 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002764
Winson Chung98e030b2012-05-07 16:01:11 -07002765 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002766 if (DEBUG_LOADERS) {
2767 Log.d(TAG, "bound workspace in "
2768 + (SystemClock.uptimeMillis()-t) + "ms");
2769 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002770
2771 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002772 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002773 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002774 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002775 synchronized (mDeferredBindRunnables) {
2776 mDeferredBindRunnables.add(r);
2777 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002778 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002779 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002780 }
Joe Onorato36115782010-06-17 13:28:48 -04002781 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002782
Joe Onorato36115782010-06-17 13:28:48 -04002783 private void loadAndBindAllApps() {
2784 if (DEBUG_LOADERS) {
2785 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2786 }
2787 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002788 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002789 synchronized (LoaderTask.this) {
2790 if (mStopped) {
2791 return;
2792 }
2793 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002794 }
Joe Onorato36115782010-06-17 13:28:48 -04002795 } else {
2796 onlyBindAllApps();
2797 }
2798 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002799
Joe Onorato36115782010-06-17 13:28:48 -04002800 private void onlyBindAllApps() {
2801 final Callbacks oldCallbacks = mCallbacks.get();
2802 if (oldCallbacks == null) {
2803 // This launcher has exited and nobody bothered to tell us. Just bail.
2804 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2805 return;
2806 }
2807
2808 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002809 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002810 final ArrayList<AppInfo> list
2811 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002812 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002813 public void run() {
2814 final long t = SystemClock.uptimeMillis();
2815 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2816 if (callbacks != null) {
2817 callbacks.bindAllApplications(list);
2818 }
2819 if (DEBUG_LOADERS) {
2820 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2821 + (SystemClock.uptimeMillis()-t) + "ms");
2822 }
2823 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002824 };
2825 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002826 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002827 r.run();
2828 } else {
2829 mHandler.post(r);
2830 }
Joe Onorato36115782010-06-17 13:28:48 -04002831 }
2832
Winson Chung64359a52013-07-08 17:17:08 -07002833 private void loadAllApps() {
2834 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002835
Joe Onorato36115782010-06-17 13:28:48 -04002836 final Callbacks oldCallbacks = mCallbacks.get();
2837 if (oldCallbacks == null) {
2838 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002839 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002840 return;
2841 }
2842
2843 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2844 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2845
Kenny Guyed131872014-04-30 03:02:21 +01002846 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2847
Winson Chung64359a52013-07-08 17:17:08 -07002848 // Clear the list of apps
2849 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002850 for (UserHandleCompat user : profiles) {
2851 // Query for the set of apps
2852 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2853 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2854 if (DEBUG_LOADERS) {
2855 Log.d(TAG, "getActivityList took "
2856 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2857 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2858 }
2859 // Fail if we don't have any apps
2860 if (apps == null || apps.isEmpty()) {
2861 return;
2862 }
2863 // Sort the applications by name
2864 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2865 Collections.sort(apps,
2866 new LauncherModel.ShortcutNameComparator(mLabelCache));
2867 if (DEBUG_LOADERS) {
2868 Log.d(TAG, "sort took "
2869 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2870 }
Joe Onorato36115782010-06-17 13:28:48 -04002871
Kenny Guyed131872014-04-30 03:02:21 +01002872 // Create the ApplicationInfos
2873 for (int i = 0; i < apps.size(); i++) {
2874 LauncherActivityInfoCompat app = apps.get(i);
2875 // This builds the icon bitmaps.
2876 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2877 }
Winson Chung64359a52013-07-08 17:17:08 -07002878 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002879 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002880 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2881 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002882
2883 // Post callback on main thread
2884 mHandler.post(new Runnable() {
2885 public void run() {
2886 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002887 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002888 if (callbacks != null) {
2889 callbacks.bindAllApplications(added);
2890 if (DEBUG_LOADERS) {
2891 Log.d(TAG, "bound " + added.size() + " apps in "
2892 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2893 }
2894 } else {
2895 Log.i(TAG, "not binding apps: no Launcher activity");
2896 }
2897 }
2898 });
2899
Joe Onorato36115782010-06-17 13:28:48 -04002900 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002901 Log.d(TAG, "Icons processed in "
2902 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002903 }
2904 }
2905
2906 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002907 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002908 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2909 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2910 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2911 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2912 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2913 }
Joe Onorato36115782010-06-17 13:28:48 -04002914 }
2915 }
2916
2917 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002918 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002919 }
2920
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002921 private class AppsAvailabilityCheck extends BroadcastReceiver {
2922
2923 @Override
2924 public void onReceive(Context context, Intent intent) {
2925 synchronized (sBgLock) {
2926 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2927 .getInstance(mApp.getContext());
2928 ArrayList<String> packagesRemoved;
2929 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2930 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002931 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002932 for (String pkg : entry.getValue()) {
2933 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2934 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2935 packagesRemoved.add(pkg);
2936 }
2937 }
2938 if (!packagesRemoved.isEmpty()) {
2939 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2940 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2941 }
2942 }
Sunny Goyal34942622014-08-29 17:20:55 -07002943 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002944 }
2945 }
2946 }
2947
Joe Onorato36115782010-06-17 13:28:48 -04002948 private class PackageUpdatedTask implements Runnable {
2949 int mOp;
2950 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002951 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002952
2953 public static final int OP_NONE = 0;
2954 public static final int OP_ADD = 1;
2955 public static final int OP_UPDATE = 2;
2956 public static final int OP_REMOVE = 3; // uninstlled
2957 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2958
2959
Kenny Guyed131872014-04-30 03:02:21 +01002960 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002961 mOp = op;
2962 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002963 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002964 }
2965
2966 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002967 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002968
2969 final String[] packages = mPackages;
2970 final int N = packages.length;
2971 switch (mOp) {
2972 case OP_ADD:
2973 for (int i=0; i<N; i++) {
2974 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002975 mIconCache.remove(packages[i], mUser);
2976 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002977 }
2978 break;
2979 case OP_UPDATE:
2980 for (int i=0; i<N; i++) {
2981 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002982 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002983 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002984 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002985 }
2986 break;
2987 case OP_REMOVE:
2988 case OP_UNAVAILABLE:
2989 for (int i=0; i<N; i++) {
2990 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002991 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002992 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002993 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002994 }
2995 break;
2996 }
2997
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002998 ArrayList<AppInfo> added = null;
2999 ArrayList<AppInfo> modified = null;
3000 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003001
Adam Cohen487f7dd2012-06-28 18:12:10 -07003002 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003003 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003004 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003005 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003006 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003007 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003008 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003009 }
Winson Chung5d55f332012-07-16 20:45:03 -07003010 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003011 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003012 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003013 }
3014
Joe Onorato36115782010-06-17 13:28:48 -04003015 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
3016 if (callbacks == null) {
3017 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3018 return;
3019 }
3020
3021 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003022 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003023 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003024 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003025 addAndBindAddedWorkspaceApps(context, addedInfos);
3026 } else {
3027 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003028 }
Joe Onorato36115782010-06-17 13:28:48 -04003029 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003030
Joe Onorato36115782010-06-17 13:28:48 -04003031 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003032 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07003033
3034 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003035 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07003036 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01003037 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07003038 for (ItemInfo i : infos) {
3039 if (isShortcutInfoUpdateable(i)) {
3040 ShortcutInfo info = (ShortcutInfo) i;
3041 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003042 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07003043 updateItemInDatabase(context, info);
3044 }
3045 }
3046 }
3047
Joe Onorato36115782010-06-17 13:28:48 -04003048 mHandler.post(new Runnable() {
3049 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003050 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3051 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003052 callbacks.bindAppsUpdated(modifiedFinal);
3053 }
3054 }
3055 });
3056 }
Winson Chung83892cc2013-05-01 16:53:33 -07003057
Winson Chungdf95eb12013-10-16 14:57:07 -07003058 final ArrayList<String> removedPackageNames =
3059 new ArrayList<String>();
3060 if (mOp == OP_REMOVE) {
3061 // Mark all packages in the broadcast to be removed
3062 removedPackageNames.addAll(Arrays.asList(packages));
3063 } else if (mOp == OP_UPDATE) {
3064 // Mark disabled packages in the broadcast to be removed
3065 final PackageManager pm = context.getPackageManager();
3066 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003067 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003068 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003069 }
3070 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003071 }
3072 // Remove all the components associated with this package
3073 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003074 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003075 }
3076 // Remove all the specific components
3077 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003078 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003079 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003080 }
3081 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3082 // Remove any queued items from the install queue
3083 String spKey = LauncherAppState.getSharedPreferencesKey();
3084 SharedPreferences sp =
3085 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3086 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3087 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003088 mHandler.post(new Runnable() {
3089 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003090 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3091 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003092 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003093 }
3094 }
3095 });
Joe Onoratobe386092009-11-17 17:32:16 -08003096 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003097
Michael Jurkac402cd92013-05-20 15:49:32 +02003098 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003099 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003100 mHandler.post(new Runnable() {
3101 @Override
3102 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003103 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3104 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003105 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003106 }
3107 }
3108 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003109
3110 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003111 mHandler.post(new Runnable() {
3112 public void run() {
3113 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3114 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003115 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003116 }
3117 }
3118 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003119 }
3120 }
3121
Michael Jurkac402cd92013-05-20 15:49:32 +02003122 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3123 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3124 PackageManager packageManager = context.getPackageManager();
3125 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003126 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3127
Michael Jurkac402cd92013-05-20 15:49:32 +02003128 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3129 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003130 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003131 return widgetsAndShortcuts;
3132 }
3133
Kenny Guyed131872014-04-30 03:02:21 +01003134 private static boolean isPackageDisabled(Context context, String packageName,
3135 UserHandleCompat user) {
3136 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3137 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003138 }
Adam Cohen556f6132014-01-15 15:18:08 -08003139
Kenny Guyed131872014-04-30 03:02:21 +01003140 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3141 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003142 if (cn == null) {
3143 return false;
3144 }
Kenny Guyed131872014-04-30 03:02:21 +01003145 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3146 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003147 return false;
3148 }
Kenny Guyed131872014-04-30 03:02:21 +01003149 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003150 }
3151
Adam Cohena28b78e2014-05-20 17:03:04 -07003152 public static boolean isValidPackage(Context context, String packageName,
3153 UserHandleCompat user) {
3154 if (packageName == null) {
3155 return false;
3156 }
3157 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3158 return launcherApps.isPackageEnabledForProfile(packageName, user);
3159 }
3160
Joe Onorato9c1289c2009-08-17 11:03:03 -04003161 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003162 * Make an ShortcutInfo object for a restored application or shortcut item that points
3163 * to a package that is not yet installed on the system.
3164 */
Sunny Goyal34942622014-08-29 17:20:55 -07003165 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3166 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003167 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003168 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003169 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3170
3171 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3172 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3173 if (!TextUtils.isEmpty(title)) {
3174 info.title = title;
3175 }
3176 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3177 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3178 if (TextUtils.isEmpty(info.title)) {
3179 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3180 }
3181 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3182 } else {
3183 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3184 }
3185
Kenny Guyc2bd8102014-06-30 12:30:31 +01003186 info.contentDescription = mUserManager.getBadgedLabelForUser(
3187 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003188 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003189 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003190 return info;
3191 }
3192
3193 /**
3194 * Make an Intent object for a restored application or shortcut item that points
3195 * to the market page for the item.
3196 */
3197 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3198 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003199 return getMarketIntent(componentName.getPackageName());
3200 }
3201
3202 static Intent getMarketIntent(String packageName) {
3203 return new Intent(Intent.ACTION_VIEW)
3204 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003205 .scheme("market")
3206 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003207 .appendQueryParameter("id", packageName)
3208 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003209 }
3210
3211 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003212 * This is called from the code that adds shortcuts from the intent receiver. This
3213 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003214 */
Kenny Guyed131872014-04-30 03:02:21 +01003215 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3216 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003217 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003218 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003219
Joe Onorato56d82912010-03-07 14:32:10 -05003220 /**
3221 * Make an ShortcutInfo object for a shortcut that is an application.
3222 *
3223 * If c is not null, then it will be used to fill in missing data like the title and icon.
3224 */
Kenny Guyed131872014-04-30 03:02:21 +01003225 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3226 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003227 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003228 if (user == null) {
3229 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003230 return null;
3231 }
3232
Kenny Guyed131872014-04-30 03:02:21 +01003233 ComponentName componentName = intent.getComponent();
3234 if (componentName == null) {
3235 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3236 return null;
3237 }
3238
3239 Intent newIntent = new Intent(intent.getAction(), null);
3240 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3241 newIntent.setComponent(componentName);
3242 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003243 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003244 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3245 return null;
3246 }
3247
3248 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003249
Joe Onorato56d82912010-03-07 14:32:10 -05003250 // the resource -- This may implicitly give us back the fallback icon,
3251 // but don't worry about that. All we're doing with usingFallbackIcon is
3252 // to avoid saving lots of copies of that in the database, and most apps
3253 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003254 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003255
Joe Onorato56d82912010-03-07 14:32:10 -05003256 // the db
3257 if (icon == null) {
3258 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003259 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003260 }
3261 }
3262 // the fallback icon
3263 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003264 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003265 info.usingFallbackIcon = true;
3266 }
3267 info.setIcon(icon);
3268
Kenny Guyed131872014-04-30 03:02:21 +01003269 // From the cache.
3270 if (labelCache != null) {
3271 info.title = labelCache.get(componentName);
3272 }
3273
Joe Onorato56d82912010-03-07 14:32:10 -05003274 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003275 if (info.title == null && lai != null) {
3276 info.title = lai.getLabel();
3277 if (labelCache != null) {
3278 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003279 }
Joe Onorato56d82912010-03-07 14:32:10 -05003280 }
3281 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003282 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003283 if (c != null) {
3284 info.title = c.getString(titleIndex);
3285 }
3286 }
3287 // fall back to the class name of the activity
3288 if (info.title == null) {
3289 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003290 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003291 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003292 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003293 info.contentDescription = mUserManager.getBadgedLabelForUser(
3294 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003295 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003296 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003297
Winson Chung64359a52013-07-08 17:17:08 -07003298 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3299 ItemInfoFilter f) {
3300 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3301 for (ItemInfo i : infos) {
3302 if (i instanceof ShortcutInfo) {
3303 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003304 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003305 if (cn != null && f.filterItem(null, info, cn)) {
3306 filtered.add(info);
3307 }
3308 } else if (i instanceof FolderInfo) {
3309 FolderInfo info = (FolderInfo) i;
3310 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003311 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003312 if (cn != null && f.filterItem(info, s, cn)) {
3313 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003314 }
3315 }
Winson Chung64359a52013-07-08 17:17:08 -07003316 } else if (i instanceof LauncherAppWidgetInfo) {
3317 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3318 ComponentName cn = info.providerName;
3319 if (cn != null && f.filterItem(null, info, cn)) {
3320 filtered.add(info);
3321 }
Winson Chung8a435102012-08-30 17:16:53 -07003322 }
3323 }
Winson Chung64359a52013-07-08 17:17:08 -07003324 return new ArrayList<ItemInfo>(filtered);
3325 }
3326
Kenny Guyed131872014-04-30 03:02:21 +01003327 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3328 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003329 ItemInfoFilter filter = new ItemInfoFilter() {
3330 @Override
3331 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003332 if (info.user == null) {
3333 return cn.equals(cname);
3334 } else {
3335 return cn.equals(cname) && info.user.equals(user);
3336 }
Winson Chung64359a52013-07-08 17:17:08 -07003337 }
3338 };
3339 return filterItemInfos(sBgItemsIdMap.values(), filter);
3340 }
3341
3342 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3343 if (i instanceof ShortcutInfo) {
3344 ShortcutInfo info = (ShortcutInfo) i;
3345 // We need to check for ACTION_MAIN otherwise getComponent() might
3346 // return null for some shortcuts (for instance, for shortcuts to
3347 // web pages.)
3348 Intent intent = info.intent;
3349 ComponentName name = intent.getComponent();
3350 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3351 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3352 return true;
3353 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003354 // placeholder shortcuts get special treatment, let them through too.
Sunny Goyal34942622014-08-29 17:20:55 -07003355 if (info.isPromise()) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003356 return true;
3357 }
Winson Chung64359a52013-07-08 17:17:08 -07003358 }
3359 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003360 }
3361
3362 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003363 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003364 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003365 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003366 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3367 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003368
Joe Onorato56d82912010-03-07 14:32:10 -05003369 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003370 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003371 // Non-app shortcuts are only supported for current user.
3372 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003373 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003374
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003375 // TODO: If there's an explicit component and we can't install that, delete it.
3376
Joe Onorato56d82912010-03-07 14:32:10 -05003377 info.title = c.getString(titleIndex);
3378
Joe Onorato9c1289c2009-08-17 11:03:03 -04003379 int iconType = c.getInt(iconTypeIndex);
3380 switch (iconType) {
3381 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3382 String packageName = c.getString(iconPackageIndex);
3383 String resourceName = c.getString(iconResourceIndex);
3384 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003385 info.customIcon = false;
3386 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003387 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003388 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003389 if (resources != null) {
3390 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003391 icon = Utilities.createIconBitmap(
3392 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003393 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003394 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003395 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003396 }
Joe Onorato56d82912010-03-07 14:32:10 -05003397 // the db
3398 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003399 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003400 }
3401 // the fallback icon
3402 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003403 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003404 info.usingFallbackIcon = true;
3405 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003406 break;
3407 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003408 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003409 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003410 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003411 info.customIcon = false;
3412 info.usingFallbackIcon = true;
3413 } else {
3414 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003415 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003416 break;
3417 default:
Kenny Guyed131872014-04-30 03:02:21 +01003418 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003419 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003420 info.customIcon = false;
3421 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003422 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003423 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003424 return info;
3425 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003426
Michael Jurka931dc972011-08-05 15:08:15 -07003427 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003428 @SuppressWarnings("all") // suppress dead code warning
3429 final boolean debug = false;
3430 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003431 Log.d(TAG, "getIconFromCursor app="
3432 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3433 }
3434 byte[] data = c.getBlob(iconIndex);
3435 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003436 return Utilities.createIconBitmap(
3437 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003438 } catch (Exception e) {
3439 return null;
3440 }
3441 }
3442
Winson Chung3d503fb2011-07-13 17:25:49 -07003443 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3444 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003445 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003446 if (info == null) {
3447 return null;
3448 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003449 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003450
3451 return info;
3452 }
3453
Winson Chunga9abd0e2010-10-27 17:18:37 -07003454 /**
Winson Chung55cef262010-10-28 14:14:18 -07003455 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3456 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003457 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003458 ComponentName component) {
3459 List<AppWidgetProviderInfo> widgets =
3460 AppWidgetManager.getInstance(context).getInstalledProviders();
3461 for (AppWidgetProviderInfo info : widgets) {
3462 if (info.provider.equals(component)) {
3463 return info;
3464 }
3465 }
3466 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003467 }
3468
3469 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003470 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3471 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3472 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3473
Adam Cohend9198822011-11-22 16:42:47 -08003474 if (intent == null) {
3475 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3476 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3477 return null;
3478 }
3479
Joe Onorato0589f0f2010-02-08 13:44:00 -08003480 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003481 boolean customIcon = false;
3482 ShortcutIconResource iconResource = null;
3483
3484 if (bitmap != null && bitmap instanceof Bitmap) {
3485 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003486 customIcon = true;
3487 } else {
3488 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3489 if (extra != null && extra instanceof ShortcutIconResource) {
3490 try {
3491 iconResource = (ShortcutIconResource) extra;
3492 final PackageManager packageManager = context.getPackageManager();
3493 Resources resources = packageManager.getResourcesForApplication(
3494 iconResource.packageName);
3495 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003496 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003497 mIconCache.getFullResIcon(resources, id),
3498 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003499 } catch (Exception e) {
3500 Log.w(TAG, "Could not load shortcut icon: " + extra);
3501 }
3502 }
3503 }
3504
Michael Jurkac9d95c52011-08-29 14:03:34 -07003505 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003506
Kenny Guyed131872014-04-30 03:02:21 +01003507 // Only support intents for current user for now. Intents sent from other
3508 // users wouldn't get here without intent forwarding anyway.
3509 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003510 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003511 if (fallbackIcon != null) {
3512 icon = fallbackIcon;
3513 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003514 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003515 info.usingFallbackIcon = true;
3516 }
Joe Onorato56d82912010-03-07 14:32:10 -05003517 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003518 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003519
Joe Onorato0589f0f2010-02-08 13:44:00 -08003520 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003521 info.contentDescription = mUserManager.getBadgedLabelForUser(
3522 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003523 info.intent = intent;
3524 info.customIcon = customIcon;
3525 info.iconResource = iconResource;
3526
3527 return info;
3528 }
3529
Winson Chungaac01e12011-08-17 10:37:13 -07003530 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3531 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003532 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003533 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003534 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003535 }
Joe Onorato56d82912010-03-07 14:32:10 -05003536 // If this icon doesn't have a custom icon, check to see
3537 // what's stored in the DB, and if it doesn't match what
3538 // we're going to show, store what we are going to show back
3539 // into the DB. We do this so when we're loading, if the
3540 // package manager can't find an icon (for example because
3541 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003542 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003543 cache.put(info, c.getBlob(iconIndex));
3544 return true;
3545 }
3546 return false;
3547 }
3548 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3549 boolean needSave = false;
3550 try {
3551 if (data != null) {
3552 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3553 Bitmap loaded = info.getIcon(mIconCache);
3554 needSave = !saved.sameAs(loaded);
3555 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003556 needSave = true;
3557 }
Winson Chungaac01e12011-08-17 10:37:13 -07003558 } catch (Exception e) {
3559 needSave = true;
3560 }
3561 if (needSave) {
3562 Log.d(TAG, "going to save icon bitmap for info=" + info);
3563 // This is slower than is ideal, but this only happens once
3564 // or when the app is updated with a new icon.
3565 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003566 }
3567 }
3568
Joe Onorato9c1289c2009-08-17 11:03:03 -04003569 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003570 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003571 * or make a new one.
3572 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003573 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003574 // See if a placeholder was created for us already
3575 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003576 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003577 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003578 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003579 folders.put(id, folderInfo);
3580 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003581 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003582 }
3583
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003584 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003585 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003586 return new Comparator<AppInfo>() {
3587 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003588 if (a.user.equals(b.user)) {
3589 int result = collator.compare(a.title.toString().trim(),
3590 b.title.toString().trim());
3591 if (result == 0) {
3592 result = a.componentName.compareTo(b.componentName);
3593 }
3594 return result;
3595 } else {
3596 // TODO Need to figure out rules for sorting
3597 // profiles, this puts work second.
3598 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003599 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003600 }
Winson Chung11904872012-09-17 16:58:46 -07003601 };
3602 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003603 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3604 = new Comparator<AppInfo>() {
3605 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003606 if (a.firstInstallTime < b.firstInstallTime) return 1;
3607 if (a.firstInstallTime > b.firstInstallTime) return -1;
3608 return 0;
3609 }
3610 };
Winson Chung5308f242011-08-18 12:12:41 -07003611 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3612 if (info.activityInfo != null) {
3613 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3614 } else {
3615 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3616 }
3617 }
Kenny Guyed131872014-04-30 03:02:21 +01003618 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003619 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003620 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003621 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003622 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003623 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003624 }
Kenny Guyed131872014-04-30 03:02:21 +01003625 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003626 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003627 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003628 }
Kenny Guyed131872014-04-30 03:02:21 +01003629 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003630 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003631 ComponentName keyA = a.getComponentName();
3632 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003633 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003634 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003635 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003636 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003637
Winson Chung5308f242011-08-18 12:12:41 -07003638 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003639 }
Winson Chung5308f242011-08-18 12:12:41 -07003640 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003641 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003642 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003643 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003644
Winson Chung5308f242011-08-18 12:12:41 -07003645 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003646 }
Winson Chung11904872012-09-17 16:58:46 -07003647 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003648 }
3649 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003650 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003651 private final AppWidgetManagerCompat mManager;
3652 private final PackageManager mPackageManager;
3653 private final HashMap<Object, String> mLabelCache;
3654 private final Collator mCollator;
3655
3656 WidgetAndShortcutNameComparator(Context context) {
3657 mManager = AppWidgetManagerCompat.getInstance(context);
3658 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003659 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003660 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003661 }
3662 public final int compare(Object a, Object b) {
3663 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003664 if (mLabelCache.containsKey(a)) {
3665 labelA = mLabelCache.get(a);
3666 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003667 labelA = (a instanceof AppWidgetProviderInfo)
3668 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3669 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003670 mLabelCache.put(a, labelA);
3671 }
3672 if (mLabelCache.containsKey(b)) {
3673 labelB = mLabelCache.get(b);
3674 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003675 labelB = (b instanceof AppWidgetProviderInfo)
3676 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3677 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003678 mLabelCache.put(b, labelB);
3679 }
Winson Chung11904872012-09-17 16:58:46 -07003680 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003681 }
3682 };
Joe Onoratobe386092009-11-17 17:32:16 -08003683
Sunny Goyal651077b2014-06-30 14:15:31 -07003684 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3685 return (provider != null) && (provider.provider != null)
3686 && (provider.provider.getPackageName() != null);
3687 }
3688
Joe Onoratobe386092009-11-17 17:32:16 -08003689 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003690 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003691 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3692 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3693 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3694 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003695 if (mLoaderTask != null) {
3696 mLoaderTask.dumpState();
3697 } else {
3698 Log.d(TAG, "mLoaderTask=null");
3699 }
Joe Onoratobe386092009-11-17 17:32:16 -08003700 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003701}