blob: bcb45011ec53f7dd8ee2e5b993f1dec5901b6f2d [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 Goyale755d462014-07-22 13:48:29 -070057import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010058import com.android.launcher3.compat.UserHandleCompat;
59import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080060
Michael Jurkac2f801e2011-07-12 14:19:46 -070061import java.lang.ref.WeakReference;
62import java.net.URISyntaxException;
63import java.text.Collator;
64import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070065import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070066import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070067import java.util.Collections;
68import java.util.Comparator;
69import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070070import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070071import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070072import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070073import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070074import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070075import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070076import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040086 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
87
Joe Onorato9c1289c2009-08-17 11:03:03 -040088 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070089
Daniel Sandler8707e0f2013-08-15 15:54:18 -070090 // true = use a "More Apps" folder for non-workspace apps on upgrade
91 // false = strew non-workspace apps across the workspace on upgrade
92 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050093 public static final int LOADER_FLAG_NONE = 0;
94 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
95 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
96
Joe Onorato36115782010-06-17 13:28:48 -040097 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050098 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080099
Winson Chungee055712013-07-30 14:46:24 -0700100 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800101 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400102
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400103 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private final Object mLock = new Object();
105 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400106 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700107 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200108 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Winson Chung81b52252012-08-27 15:34:29 -0700110 // Specific runnable types that are run on the main thread deferred handler, this allows us to
111 // clear all queued binding runnables when the Launcher activity is destroyed.
112 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
113 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
114
Jason Monkbbe1e242014-05-16 17:37:34 -0400115 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700116
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700117 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
118 static {
119 sWorkerThread.start();
120 }
121 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
122
Joe Onoratocc67f472010-06-08 10:54:30 -0700123 // We start off with everything not loaded. After that, we assume that
124 // our monitoring of the package manager provides all updates and we never
125 // need to do a requery. These are only ever touched from the loader thread.
126 private boolean mWorkspaceLoaded;
127 private boolean mAllAppsLoaded;
128
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700129 // When we are loading pages synchronously, we can't just post the binding of items on the side
130 // pages as this delays the rotation process. Instead, we wait for a callback from the first
131 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
132 // a normal load, we also clear this set of Runnables.
133 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
134
Joe Onorato9c1289c2009-08-17 11:03:03 -0400135 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700138 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800139
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700140 // The lock that must be acquired before referencing any static bg data structures. Unlike
141 // other locks, this one can generally be held long-term because we never expect any of these
142 // static data structures to be referenced outside of the worker thread except on the first
143 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700144 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
151 // created by LauncherModel that are directly on the home screen (however, no widgets or
152 // shortcuts within folders).
153 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
156 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 new ArrayList<LauncherAppWidgetInfo>();
158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
160 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
163 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700164
165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700168 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700169 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
170 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700172 // </ only access in worker thread >
173
174 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175
Reena Lee99a73f32011-10-24 17:27:37 -0700176 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700177
Kenny Guyed131872014-04-30 03:02:21 +0100178 private final LauncherAppsCompat mLauncherApps;
179 private final UserManagerCompat mUserManager;
180
Joe Onorato9c1289c2009-08-17 11:03:03 -0400181 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700182 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public int getCurrentWorkspaceScreen();
184 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700185 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
186 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700187 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500189 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700190 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400191 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200192 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700193 public void bindAppsAdded(ArrayList<Long> newScreens,
194 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700195 ArrayList<ItemInfo> addAnimated,
196 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200197 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyale755d462014-07-22 13:48:29 -0700198 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Winson Chung83892cc2013-05-01 16:53:33 -0700199 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100200 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200201 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100202 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700203 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700204 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700205 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400206 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800207
Winson Chung64359a52013-07-08 17:17:08 -0700208 public interface ItemInfoFilter {
209 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
210 }
211
Bjorn Bringert1307f632013-10-03 22:31:03 +0100212 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800213 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400214
Winson Chungee055712013-07-30 14:46:24 -0700215 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700216 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400217 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
218 // resource string.
219 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
220 ProviderInfo providerInfo =
221 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
222 ProviderInfo redirectProvider =
223 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700224
225 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400226 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700227
228 if (mOldContentProviderExists) {
229 Log.d(TAG, "Old launcher provider exists.");
230 } else {
231 Log.d(TAG, "Old launcher provider does not exist.");
232 }
233
Daniel Sandlere4f98912013-06-25 15:13:26 -0400234 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100235 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800236 mIconCache = iconCache;
237
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400238 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700239 Configuration config = res.getConfiguration();
240 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100241 mLauncherApps = LauncherAppsCompat.getInstance(context);
242 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800243 }
244
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700245 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
246 * posted on the main thread handler. */
247 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700248 runOnMainThread(r, 0);
249 }
250 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700251 if (sWorkerThread.getThreadId() == Process.myTid()) {
252 // If we are on the worker thread, post onto the main handler
253 mHandler.post(r);
254 } else {
255 r.run();
256 }
257 }
258
259 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
260 * posted on the worker thread handler. */
261 private static void runOnWorkerThread(Runnable r) {
262 if (sWorkerThread.getThreadId() == Process.myTid()) {
263 r.run();
264 } else {
265 // If we are not on the worker thread, then post to the worker handler
266 sWorker.post(r);
267 }
268 }
269
Winson Chunge43a1e72014-01-15 10:33:02 -0800270 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
271 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800272 }
273
Winson Chungc9168342013-06-26 14:54:55 -0700274 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
275 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700276 LauncherAppState app = LauncherAppState.getInstance();
277 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
278 final int xCount = (int) grid.numColumns;
279 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700280 boolean[][] occupied = new boolean[xCount][yCount];
281
282 int cellX, cellY, spanX, spanY;
283 for (int i = 0; i < items.size(); ++i) {
284 final ItemInfo item = items.get(i);
285 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
286 if (item.screenId == screen) {
287 cellX = item.cellX;
288 cellY = item.cellY;
289 spanX = item.spanX;
290 spanY = item.spanY;
291 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
292 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
293 occupied[x][y] = true;
294 }
295 }
296 }
297 }
298 }
299
300 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
301 }
302 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700303 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700304 int firstScreenIndex,
305 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700306 // Lock on the app so that we don't try and get the items while apps are being added
307 LauncherAppState app = LauncherAppState.getInstance();
308 LauncherModel model = app.getModel();
309 boolean found = false;
310 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700311 if (sWorkerThread.getThreadId() != Process.myTid()) {
312 // Flush the LauncherModel worker thread, so that if we just did another
313 // processInstallShortcut, we give it time for its shortcut to get added to the
314 // database (getItemsInLocalCoordinates reads the database)
315 model.flushWorkerThread();
316 }
Winson Chungc9168342013-06-26 14:54:55 -0700317 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700318
319 // Try adding to the workspace screens incrementally, starting at the default or center
320 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700321 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
322 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700323 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700324 int[] tmpCoordinates = new int[2];
325 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700326 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700327 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700328 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700329 }
330 }
331 }
Winson Chungc9168342013-06-26 14:54:55 -0700332 return null;
333 }
334
Sunny Goyale755d462014-07-22 13:48:29 -0700335 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500336 // Process the updated package state
337 Runnable r = new Runnable() {
338 public void run() {
339 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
340 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700341 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500342 }
343 }
344 };
345 mHandler.post(r);
346 }
347
Adam Cohen76a47a12014-02-05 11:47:43 -0800348 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
349 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
350
351 if (allAppsApps == null) {
352 throw new RuntimeException("allAppsApps must not be null");
353 }
354 if (allAppsApps.isEmpty()) {
355 return;
356 }
357
Chris Wrenb6d4c282014-01-27 14:17:08 -0500358 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
359 Iterator<AppInfo> iter = allAppsApps.iterator();
360 while (iter.hasNext()) {
361 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100362 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500363 restoredAppsFinal.add((AppInfo) a);
364 }
365 }
366
Adam Cohen76a47a12014-02-05 11:47:43 -0800367 // Process the newly added applications and add them to the database first
368 Runnable r = new Runnable() {
369 public void run() {
370 runOnMainThread(new Runnable() {
371 public void run() {
372 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
373 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500374 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500375 for (AppInfo info : restoredAppsFinal) {
376 final Intent intent = info.getIntent();
377 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100378 mIconCache.deletePreloadedIcon(intent.getComponent(),
379 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500380 }
381 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500382 callbacks.bindAppsUpdated(restoredAppsFinal);
383 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500384 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800385 }
386 }
387 });
388 }
389 };
390 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700391 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800392
393 public void addAndBindAddedWorkspaceApps(final Context context,
394 final ArrayList<ItemInfo> workspaceApps) {
395 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
396
397 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800398 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
399 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800400 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700401 return;
Winson Chung997a9232013-07-24 15:33:46 -0700402 }
Winson Chung64359a52013-07-08 17:17:08 -0700403 // Process the newly added applications and add them to the database first
404 Runnable r = new Runnable() {
405 public void run() {
406 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
407 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500408 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700409
Winson Chung76828c82013-08-19 15:43:29 -0700410 // Get the list of workspace screens. We need to append to this list and
411 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
412 // called.
413 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
414 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
415 for (Integer i : orderedScreens.keySet()) {
416 long screenId = orderedScreens.get(i);
417 workspaceScreens.add(screenId);
418 }
419
Winson Chung64359a52013-07-08 17:17:08 -0700420 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700421 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700422 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700423 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700424 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700425 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700426
427 // Short-circuit this logic if the icon exists somewhere on the workspace
428 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500429 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
430 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100431 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500432 restoredAppsFinal.add((AppInfo) a);
433 }
Winson Chung64359a52013-07-08 17:17:08 -0700434 continue;
435 }
436
Winson Chung87412982013-10-03 18:34:14 -0700437 // Add this icon to the db, creating a new page if necessary. If there
438 // is only the empty page then we just add items to the first page.
439 // Otherwise, we add them to the next pages.
440 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700441 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700442 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700443 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200444 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700445
446 // If we can't find a valid position, then just add a new screen.
447 // This takes time so we need to re-queue the add until the new
448 // page is added. Create as many screens as necessary to satisfy
449 // the startSearchPageIndex.
450 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700451 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700452 while (numPagesToAdd > 0) {
453 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700454 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700455 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 addedWorkspaceScreensFinal.add(screenId);
457 numPagesToAdd--;
458 }
Winson Chung76828c82013-08-19 15:43:29 -0700459
Winson Chung64359a52013-07-08 17:17:08 -0700460 // Find the coordinate again
461 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700462 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700463 }
464 if (coords == null) {
465 throw new RuntimeException("Coordinates should not be null");
466 }
467
Winson Chung997a9232013-07-24 15:33:46 -0700468 ShortcutInfo shortcutInfo;
469 if (a instanceof ShortcutInfo) {
470 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200471 } else if (a instanceof AppInfo) {
472 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700473 } else {
474 throw new RuntimeException("Unexpected info type");
475 }
Winson Chung94d67682013-09-25 16:29:40 -0700476
Winson Chung64359a52013-07-08 17:17:08 -0700477 // Add the shortcut to the db
478 addItemToDatabase(context, shortcutInfo,
479 LauncherSettings.Favorites.CONTAINER_DESKTOP,
480 coords.first, coords.second[0], coords.second[1], false);
481 // Save the ShortcutInfo for binding in the workspace
482 addedShortcutsFinal.add(shortcutInfo);
483 }
484 }
485
Winson Chung76828c82013-08-19 15:43:29 -0700486 // Update the workspace screens
487 updateWorkspaceScreenOrder(context, workspaceScreens);
488
Adam Cohen76a47a12014-02-05 11:47:43 -0800489 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700490 runOnMainThread(new Runnable() {
491 public void run() {
492 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
493 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700494 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
495 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700496 if (!addedShortcutsFinal.isEmpty()) {
497 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
498 long lastScreenId = info.screenId;
499 for (ItemInfo i : addedShortcutsFinal) {
500 if (i.screenId == lastScreenId) {
501 addAnimated.add(i);
502 } else {
503 addNotAnimated.add(i);
504 }
Winson Chung997a9232013-07-24 15:33:46 -0700505 }
506 }
Winson Chungd64d1762013-08-20 14:37:16 -0700507 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800508 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500509 if (!restoredAppsFinal.isEmpty()) {
510 callbacks.bindAppsUpdated(restoredAppsFinal);
511 }
Winson Chung997a9232013-07-24 15:33:46 -0700512 }
Winson Chung64359a52013-07-08 17:17:08 -0700513 }
Winson Chung997a9232013-07-24 15:33:46 -0700514 });
515 }
Winson Chung64359a52013-07-08 17:17:08 -0700516 }
517 };
518 runOnWorkerThread(r);
519 }
520
Winson Chung81b52252012-08-27 15:34:29 -0700521 public void unbindItemInfosAndClearQueuedBindRunnables() {
522 if (sWorkerThread.getThreadId() == Process.myTid()) {
523 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
524 "main thread");
525 }
526
527 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400528 synchronized (mDeferredBindRunnables) {
529 mDeferredBindRunnables.clear();
530 }
Winson Chung81b52252012-08-27 15:34:29 -0700531 // Remove any queued bind runnables
532 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
533 // Unbind all the workspace items
534 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700535 }
536
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700537 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700538 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700539 // Ensure that we don't use the same workspace items data structure on the main thread
540 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700541 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
542 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700543 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700544 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
545 tmpAppWidgets.addAll(sBgAppWidgets);
546 }
547 Runnable r = new Runnable() {
548 @Override
549 public void run() {
550 for (ItemInfo item : tmpWorkspaceItems) {
551 item.unbind();
552 }
553 for (ItemInfo item : tmpAppWidgets) {
554 item.unbind();
555 }
556 }
557 };
558 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700559 }
560
Joe Onorato9c1289c2009-08-17 11:03:03 -0400561 /**
562 * Adds an item to the DB if it was not created previously, or move it to a new
563 * <container, screen, cellX, cellY>
564 */
565 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700566 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400567 if (item.container == ItemInfo.NO_ID) {
568 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700569 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400570 } else {
571 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700572 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 }
574 }
575
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700576 static void checkItemInfoLocked(
577 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
578 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
579 if (modelItem != null && item != modelItem) {
580 // check all the data is consistent
581 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
582 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
583 ShortcutInfo shortcut = (ShortcutInfo) item;
584 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
585 modelShortcut.intent.filterEquals(shortcut.intent) &&
586 modelShortcut.id == shortcut.id &&
587 modelShortcut.itemType == shortcut.itemType &&
588 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700589 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700590 modelShortcut.cellX == shortcut.cellX &&
591 modelShortcut.cellY == shortcut.cellY &&
592 modelShortcut.spanX == shortcut.spanX &&
593 modelShortcut.spanY == shortcut.spanY &&
594 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
595 (modelShortcut.dropPos != null &&
596 shortcut.dropPos != null &&
597 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
598 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
599 // For all intents and purposes, this is the same object
600 return;
601 }
602 }
603
604 // the modelItem needs to match up perfectly with item if our model is
605 // to be consistent with the database-- for now, just require
606 // modelItem == item or the equality check above
607 String msg = "item: " + ((item != null) ? item.toString() : "null") +
608 "modelItem: " +
609 ((modelItem != null) ? modelItem.toString() : "null") +
610 "Error: ItemInfo passed to checkItemInfo doesn't match original";
611 RuntimeException e = new RuntimeException(msg);
612 if (stackTrace != null) {
613 e.setStackTrace(stackTrace);
614 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800615 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700616 }
617 }
618
Michael Jurka816474f2012-06-25 14:49:02 -0700619 static void checkItemInfo(final ItemInfo item) {
620 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
621 final long itemId = item.id;
622 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700623 public void run() {
624 synchronized (sBgLock) {
625 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700626 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700627 }
628 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700629 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700630 }
631
Michael Jurkac9d95c52011-08-29 14:03:34 -0700632 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
633 final ItemInfo item, final String callingFunction) {
634 final long itemId = item.id;
635 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
636 final ContentResolver cr = context.getContentResolver();
637
Adam Cohen487f7dd2012-06-28 18:12:10 -0700638 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700639 Runnable r = new Runnable() {
640 public void run() {
641 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700642 updateItemArrays(item, itemId, stackTrace);
643 }
644 };
645 runOnWorkerThread(r);
646 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700647
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700648 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
649 final ArrayList<ItemInfo> items, final String callingFunction) {
650 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700651
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700652 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
653 Runnable r = new Runnable() {
654 public void run() {
655 ArrayList<ContentProviderOperation> ops =
656 new ArrayList<ContentProviderOperation>();
657 int count = items.size();
658 for (int i = 0; i < count; i++) {
659 ItemInfo item = items.get(i);
660 final long itemId = item.id;
661 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
662 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700663
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700664 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
665 updateItemArrays(item, itemId, stackTrace);
666
667 }
668 try {
669 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
670 } catch (Exception e) {
671 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700672 }
673 }
674 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700675 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700676 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700677
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700678 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
679 // Lock on mBgLock *after* the db operation
680 synchronized (sBgLock) {
681 checkItemInfoLocked(itemId, item, stackTrace);
682
683 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
684 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
685 // Item is in a folder, make sure this folder exists
686 if (!sBgFolders.containsKey(item.container)) {
687 // An items container is being set to a that of an item which is not in
688 // the list of Folders.
689 String msg = "item: " + item + " container being set to: " +
690 item.container + ", not in the list of folders";
691 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700692 }
693 }
694
695 // Items are added/removed from the corresponding FolderInfo elsewhere, such
696 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
697 // that are on the desktop, as appropriate
698 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800699 if (modelItem != null &&
700 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
701 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700702 switch (modelItem.itemType) {
703 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
704 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
705 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
706 if (!sBgWorkspaceItems.contains(modelItem)) {
707 sBgWorkspaceItems.add(modelItem);
708 }
709 break;
710 default:
711 break;
712 }
713 } else {
714 sBgWorkspaceItems.remove(modelItem);
715 }
716 }
717 }
718
Michael Jurkac7700af2013-05-14 20:17:58 +0200719 public void flushWorkerThread() {
720 mFlushingWorkerThread = true;
721 Runnable waiter = new Runnable() {
722 public void run() {
723 synchronized (this) {
724 notifyAll();
725 mFlushingWorkerThread = false;
726 }
727 }
728 };
729
730 synchronized(waiter) {
731 runOnWorkerThread(waiter);
732 if (mLoaderTask != null) {
733 synchronized(mLoaderTask) {
734 mLoaderTask.notify();
735 }
736 }
737 boolean success = false;
738 while (!success) {
739 try {
740 waiter.wait();
741 success = true;
742 } catch (InterruptedException e) {
743 }
744 }
745 }
746 }
747
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800748 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400749 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700750 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700751 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700752 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400753 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 item.cellX = cellX;
755 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700756
Winson Chung3d503fb2011-07-13 17:25:49 -0700757 // We store hotseat items in canonical form which is this orientation invariant position
758 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700759 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700760 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700761 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700762 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700763 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700764 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400765
766 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700768 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
769 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400771
Michael Jurkac9d95c52011-08-29 14:03:34 -0700772 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700773 }
774
775 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700776 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
777 * cellX, cellY have already been updated on the ItemInfos.
778 */
779 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
780 final long container, final int screen) {
781
782 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
783 int count = items.size();
784
785 for (int i = 0; i < count; i++) {
786 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700787 item.container = container;
788
789 // We store hotseat items in canonical form which is this orientation invariant position
790 // in the hotseat
791 if (context instanceof Launcher && screen < 0 &&
792 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700793 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700794 item.cellY);
795 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700796 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700797 }
798
799 final ContentValues values = new ContentValues();
800 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
801 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
802 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700803 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700804
805 contentValues.add(values);
806 }
807 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
808 }
809
810 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700811 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800812 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700813 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700815 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800816 item.cellX = cellX;
817 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700818 item.spanX = spanX;
819 item.spanY = spanY;
820
821 // We store hotseat items in canonical form which is this orientation invariant position
822 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700823 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700824 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700825 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700826 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700828 }
Adam Cohend4844c32011-02-18 19:25:06 -0800829
Adam Cohend4844c32011-02-18 19:25:06 -0800830 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800831 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700832 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
833 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
834 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
835 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700836 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800837
Michael Jurka816474f2012-06-25 14:49:02 -0700838 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700839 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700840
841 /**
842 * Update an item to the database in a specified container.
843 */
844 static void updateItemInDatabase(Context context, final ItemInfo item) {
845 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100846 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700847 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
848 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800849 }
850
851 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852 * Returns true if the shortcuts already exists in the database.
853 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800854 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400855 static boolean shortcutExists(Context context, String title, Intent intent) {
856 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700857 final Intent intentWithPkg, intentWithoutPkg;
858
859 if (intent.getComponent() != null) {
860 // If component is not null, an intent with null package will produce
861 // the same result and should also be a match.
862 if (intent.getPackage() != null) {
863 intentWithPkg = intent;
864 intentWithoutPkg = new Intent(intent).setPackage(null);
865 } else {
866 intentWithPkg = new Intent(intent).setPackage(
867 intent.getComponent().getPackageName());
868 intentWithoutPkg = intent;
869 }
870 } else {
871 intentWithPkg = intent;
872 intentWithoutPkg = intent;
873 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400874 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700875 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
876 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400877 boolean result = false;
878 try {
879 result = c.moveToFirst();
880 } finally {
881 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800882 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400883 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700884 }
885
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500887 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100888 * we identify a shortcut by the component name of the intent
889 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500890 */
Kenny Guyed131872014-04-30 03:02:21 +0100891 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500892 final ContentResolver cr = context.getContentResolver();
893 final ComponentName component = intent.getComponent();
894 if (component == null) {
895 return false;
896 }
897 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400898 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100899 long serialNumber = UserManagerCompat.getInstance(context)
900 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400901 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
902 "intent glob \"*component=" + shortName + "*\")" +
903 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500904 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100905 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500906 boolean result = false;
907 try {
908 result = c.moveToFirst();
909 } finally {
910 c.close();
911 }
912 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
913 return result;
914 }
915
916 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700917 * Returns an ItemInfo array containing all the items in the LauncherModel.
918 * The ItemInfo.id is not set through this function.
919 */
920 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
921 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
922 final ContentResolver cr = context.getContentResolver();
923 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
924 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100925 LauncherSettings.Favorites.SCREEN,
926 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
927 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
928 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700929
930 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
931 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
932 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
933 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
934 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
935 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
936 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100937 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
938 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700939 try {
940 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700941 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700942 item.cellX = c.getInt(cellXIndex);
943 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700944 item.spanX = Math.max(1, c.getInt(spanXIndex));
945 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700946 item.container = c.getInt(containerIndex);
947 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100949 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100950 item.user = userManager.getUserForSerialNumber(serialNumber);
951 // Skip if user has been deleted.
952 if (item.user != null) {
953 items.add(item);
954 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700955 }
956 } catch (Exception e) {
957 items.clear();
958 } finally {
959 c.close();
960 }
961
962 return items;
963 }
964
965 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400966 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
967 */
968 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
969 final ContentResolver cr = context.getContentResolver();
970 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
971 "_id=? and (itemType=? or itemType=?)",
972 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700973 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700974
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975 try {
976 if (c.moveToFirst()) {
977 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
978 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
979 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
980 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
981 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
982 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800983
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 FolderInfo folderInfo = null;
985 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700986 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
987 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700989 }
990
Joe Onorato9c1289c2009-08-17 11:03:03 -0400991 folderInfo.title = c.getString(titleIndex);
992 folderInfo.id = id;
993 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700995 folderInfo.cellX = c.getInt(cellXIndex);
996 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997
998 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700999 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001000 } finally {
1001 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001002 }
1003
1004 return null;
1005 }
1006
Joe Onorato9c1289c2009-08-17 11:03:03 -04001007 /**
1008 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1009 * cellY fields of the item. Also assigns an ID to the item.
1010 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001011 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001014 item.cellX = cellX;
1015 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001016 // We store hotseat items in canonical form which is this orientation invariant position
1017 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001018 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001019 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001021 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001023 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001024
1025 final ContentValues values = new ContentValues();
1026 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001027 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001028
Michael Jurka414300a2013-08-27 15:42:35 +02001029 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001030 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001031 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001032
Jason Monk8e19cf22014-03-20 15:06:57 -04001033 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001034 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001035 public void run() {
1036 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1037 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001038
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001040 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001041 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 sBgItemsIdMap.put(item.id, item);
1043 switch (item.itemType) {
1044 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1045 sBgFolders.put(item.id, (FolderInfo) item);
1046 // Fall through
1047 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1048 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1049 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1050 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1051 sBgWorkspaceItems.add(item);
1052 } else {
1053 if (!sBgFolders.containsKey(item.container)) {
1054 // Adding an item to a folder that doesn't exist.
1055 String msg = "adding item: " + item + " to a folder that " +
1056 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001057 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001058 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001059 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001060 break;
1061 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1062 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1063 break;
1064 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001065 }
1066 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001067 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001068 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001069 }
1070
Joe Onorato9c1289c2009-08-17 11:03:03 -04001071 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001072 * Creates a new unique child id, for a given cell span across all layouts.
1073 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001074 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001076 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001077 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001078 }
1079
Winson Chungaafa03c2010-06-11 17:34:16 -07001080 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001081 * Removes the specified item from the database
1082 * @param context
1083 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001084 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001085 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001087 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001088
Michael Jurka83df1882011-08-31 20:59:26 -07001089 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001091 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001092
1093 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001094 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001095 switch (item.itemType) {
1096 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1097 sBgFolders.remove(item.id);
1098 for (ItemInfo info: sBgItemsIdMap.values()) {
1099 if (info.container == item.id) {
1100 // We are deleting a folder which still contains items that
1101 // think they are contained by that folder.
1102 String msg = "deleting a folder (" + item + ") which still " +
1103 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001104 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001105 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001106 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001107 sBgWorkspaceItems.remove(item);
1108 break;
1109 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1110 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1111 sBgWorkspaceItems.remove(item);
1112 break;
1113 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1114 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1115 break;
1116 }
1117 sBgItemsIdMap.remove(item.id);
1118 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001119 }
1120 }
Michael Jurka83df1882011-08-31 20:59:26 -07001121 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001122 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001123 }
1124
1125 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001126 * Update the order of the workspace screens in the database. The array list contains
1127 * a list of screen ids in the order that they should appear.
1128 */
Winson Chungc9168342013-06-26 14:54:55 -07001129 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001130 // Log to disk
1131 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1132 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1133
Winson Chung64359a52013-07-08 17:17:08 -07001134 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001135 final ContentResolver cr = context.getContentResolver();
1136 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1137
1138 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001139 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 while (iter.hasNext()) {
1141 long id = iter.next();
1142 if (id < 0) {
1143 iter.remove();
1144 }
1145 }
1146
1147 Runnable r = new Runnable() {
1148 @Override
1149 public void run() {
Yura085c8532014-02-11 15:15:29 +00001150 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001151 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001152 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001153 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 for (int i = 0; i < count; i++) {
1155 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001156 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001157 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1158 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001159 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 }
Yura085c8532014-02-11 15:15:29 +00001161
1162 try {
1163 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1164 } catch (Exception ex) {
1165 throw new RuntimeException(ex);
1166 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001167
Winson Chungba9c37f2013-08-30 14:11:37 -07001168 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001169 sBgWorkspaceScreens.clear();
1170 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001171 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 }
1173 };
1174 runOnWorkerThread(r);
1175 }
1176
1177 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001178 * Remove the contents of the specified folder from the database
1179 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001180 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001181 final ContentResolver cr = context.getContentResolver();
1182
Michael Jurkac9d95c52011-08-29 14:03:34 -07001183 Runnable r = new Runnable() {
1184 public void run() {
1185 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001186 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001187 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001188 sBgItemsIdMap.remove(info.id);
1189 sBgFolders.remove(info.id);
1190 sBgDbIconCache.remove(info);
1191 sBgWorkspaceItems.remove(info);
1192 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001193
Michael Jurkac9d95c52011-08-29 14:03:34 -07001194 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1195 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001196 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001197 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001198 for (ItemInfo childInfo : info.contents) {
1199 sBgItemsIdMap.remove(childInfo.id);
1200 sBgDbIconCache.remove(childInfo);
1201 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001202 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001203 }
1204 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001206 }
1207
1208 /**
1209 * Set this as the current Launcher activity object for the loader.
1210 */
1211 public void initialize(Callbacks callbacks) {
1212 synchronized (mLock) {
1213 mCallbacks = new WeakReference<Callbacks>(callbacks);
1214 }
1215 }
1216
Kenny Guyed131872014-04-30 03:02:21 +01001217 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001218 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001219 int op = PackageUpdatedTask.OP_UPDATE;
1220 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1221 user));
1222 }
1223
1224 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001225 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001226 int op = PackageUpdatedTask.OP_REMOVE;
1227 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1228 user));
1229 }
1230
1231 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001232 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001233 int op = PackageUpdatedTask.OP_ADD;
1234 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1235 user));
1236 }
1237
1238 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001239 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001240 boolean replacing) {
1241 if (!replacing) {
1242 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1243 user));
1244 if (mAppsCanBeOnRemoveableStorage) {
1245 // Only rebind if we support removable storage. It catches the
1246 // case where
1247 // apps on the external sd card need to be reloaded
1248 startLoaderFromBackground();
1249 }
1250 } else {
1251 // If we are replacing then just update the packages in the list
1252 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1253 packageNames, user));
1254 }
1255 }
1256
1257 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001258 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001259 boolean replacing) {
1260 if (!replacing) {
1261 enqueuePackageUpdated(new PackageUpdatedTask(
1262 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1263 user));
1264 }
1265
1266 }
1267
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001268 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001269 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1270 * ACTION_PACKAGE_CHANGED.
1271 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001272 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001273 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001274 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001275
Joe Onorato36115782010-06-17 13:28:48 -04001276 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001277 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001278 // If we have changed locale we need to clear out the labels in all apps/workspace.
1279 forceReload();
1280 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1281 // Check if configuration change was an mcc/mnc change which would affect app resources
1282 // and we would need to clear out the labels in all apps/workspace. Same handling as
1283 // above for ACTION_LOCALE_CHANGED
1284 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001285 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001286 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001287 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001288 forceReload();
1289 }
1290 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001291 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001292 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1293 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001294 if (mCallbacks != null) {
1295 Callbacks callbacks = mCallbacks.get();
1296 if (callbacks != null) {
1297 callbacks.bindSearchablesChanged();
1298 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001299 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001300 }
1301 }
1302
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001303 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001304 resetLoadedState(true, true);
1305
Reena Lee93f824a2011-09-23 17:20:28 -07001306 // Do this here because if the launcher activity is running it will be restarted.
1307 // If it's not running startLoaderFromBackground will merely tell it that it needs
1308 // to reload.
1309 startLoaderFromBackground();
1310 }
1311
Winson Chungf0c6ae02012-03-21 16:10:31 -07001312 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1313 synchronized (mLock) {
1314 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1315 // mWorkspaceLoaded to true later
1316 stopLoaderLocked();
1317 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1318 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1319 }
1320 }
1321
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001322 /**
1323 * When the launcher is in the background, it's possible for it to miss paired
1324 * configuration changes. So whenever we trigger the loader from the background
1325 * tell the launcher that it needs to re-run the loader when it comes back instead
1326 * of doing it now.
1327 */
1328 public void startLoaderFromBackground() {
1329 boolean runLoader = false;
1330 if (mCallbacks != null) {
1331 Callbacks callbacks = mCallbacks.get();
1332 if (callbacks != null) {
1333 // Only actually run the loader if they're not paused.
1334 if (!callbacks.setLoadOnResume()) {
1335 runLoader = true;
1336 }
1337 }
1338 }
1339 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001340 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001341 }
Joe Onorato36115782010-06-17 13:28:48 -04001342 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001343
Reena Lee93f824a2011-09-23 17:20:28 -07001344 // If there is already a loader task running, tell it to stop.
1345 // returns true if isLaunching() was true on the old task
1346 private boolean stopLoaderLocked() {
1347 boolean isLaunching = false;
1348 LoaderTask oldTask = mLoaderTask;
1349 if (oldTask != null) {
1350 if (oldTask.isLaunching()) {
1351 isLaunching = true;
1352 }
1353 oldTask.stopLocked();
1354 }
1355 return isLaunching;
1356 }
1357
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001358 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001359 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1360 }
1361
1362 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001363 synchronized (mLock) {
1364 if (DEBUG_LOADERS) {
1365 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1366 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001367
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001368 // Clear any deferred bind-runnables from the synchronized load process
1369 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001370 synchronized (mDeferredBindRunnables) {
1371 mDeferredBindRunnables.clear();
1372 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373
Joe Onorato36115782010-06-17 13:28:48 -04001374 // Don't bother to start the thread if we know it's not going to do anything
1375 if (mCallbacks != null && mCallbacks.get() != null) {
1376 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001377 // also, don't downgrade isLaunching if we're already running
1378 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001379 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001380 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1381 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001382 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1383 } else {
1384 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1385 sWorker.post(mLoaderTask);
1386 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001387 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001388 }
1389 }
1390
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001391 void bindRemainingSynchronousPages() {
1392 // Post the remaining side pages to be loaded
1393 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001394 Runnable[] deferredBindRunnables = null;
1395 synchronized (mDeferredBindRunnables) {
1396 deferredBindRunnables = mDeferredBindRunnables.toArray(
1397 new Runnable[mDeferredBindRunnables.size()]);
1398 mDeferredBindRunnables.clear();
1399 }
1400 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001401 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 }
1404 }
1405
Joe Onorato36115782010-06-17 13:28:48 -04001406 public void stopLoader() {
1407 synchronized (mLock) {
1408 if (mLoaderTask != null) {
1409 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001410 }
1411 }
Joe Onorato36115782010-06-17 13:28:48 -04001412 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001413
Winson Chung76828c82013-08-19 15:43:29 -07001414 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1415 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1416 final ContentResolver contentResolver = context.getContentResolver();
1417 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1418 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1419 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1420
1421 try {
1422 final int idIndex = sc.getColumnIndexOrThrow(
1423 LauncherSettings.WorkspaceScreens._ID);
1424 final int rankIndex = sc.getColumnIndexOrThrow(
1425 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1426 while (sc.moveToNext()) {
1427 try {
1428 long screenId = sc.getLong(idIndex);
1429 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001430 orderedScreens.put(rank, screenId);
1431 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001432 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001433 }
1434 }
1435 } finally {
1436 sc.close();
1437 }
Winson Chunga90303b2013-11-15 13:05:06 -08001438
1439 // Log to disk
1440 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1441 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1442 for (Integer i : orderedScreens.keySet()) {
1443 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1444 }
1445 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1446 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001447 return orderedScreens;
1448 }
1449
Michael Jurkac57b7a82011-08-09 22:02:20 -07001450 public boolean isAllAppsLoaded() {
1451 return mAllAppsLoaded;
1452 }
1453
Winson Chung36a62fe2012-05-06 18:04:42 -07001454 boolean isLoadingWorkspace() {
1455 synchronized (mLock) {
1456 if (mLoaderTask != null) {
1457 return mLoaderTask.isLoadingWorkspace();
1458 }
1459 }
1460 return false;
1461 }
1462
Joe Onorato36115782010-06-17 13:28:48 -04001463 /**
1464 * Runnable for the thread that loads the contents of the launcher:
1465 * - workspace icons
1466 * - widgets
1467 * - all apps icons
1468 */
1469 private class LoaderTask implements Runnable {
1470 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001471 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001472 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mStopped;
1474 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001475 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001476
Winson Chungc3eecff2011-07-11 17:44:15 -07001477 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001478
Dan Sandlerd5024042014-01-09 15:01:33 -05001479 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001480 mContext = context;
1481 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001482 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001483 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001484 }
1485
Joe Onorato36115782010-06-17 13:28:48 -04001486 boolean isLaunching() {
1487 return mIsLaunching;
1488 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Winson Chung36a62fe2012-05-06 18:04:42 -07001490 boolean isLoadingWorkspace() {
1491 return mIsLoadingAndBindingWorkspace;
1492 }
1493
Winson Chungc763c4e2013-07-19 13:49:06 -07001494 /** Returns whether this is an upgrade path */
1495 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001496 mIsLoadingAndBindingWorkspace = true;
1497
Joe Onorato36115782010-06-17 13:28:48 -04001498 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001499 if (DEBUG_LOADERS) {
1500 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001501 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001502
Winson Chungc763c4e2013-07-19 13:49:06 -07001503 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001504 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001505 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001506 synchronized (LoaderTask.this) {
1507 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001508 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001509 }
1510 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001511 }
1512 }
1513
Joe Onorato36115782010-06-17 13:28:48 -04001514 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001515 bindWorkspace(-1, isUpgradePath);
1516 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001517 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001518
Joe Onorato36115782010-06-17 13:28:48 -04001519 private void waitForIdle() {
1520 // Wait until the either we're stopped or the other threads are done.
1521 // This way we don't start loading all apps until the workspace has settled
1522 // down.
1523 synchronized (LoaderTask.this) {
1524 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001525
Joe Onorato36115782010-06-17 13:28:48 -04001526 mHandler.postIdle(new Runnable() {
1527 public void run() {
1528 synchronized (LoaderTask.this) {
1529 mLoadAndBindStepFinished = true;
1530 if (DEBUG_LOADERS) {
1531 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001532 }
Joe Onorato36115782010-06-17 13:28:48 -04001533 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001534 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001535 }
Joe Onorato36115782010-06-17 13:28:48 -04001536 });
1537
Michael Jurkac7700af2013-05-14 20:17:58 +02001538 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001539 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001540 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1541 // wait no longer than 1sec at a time
1542 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001543 } catch (InterruptedException ex) {
1544 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001545 }
1546 }
Joe Onorato36115782010-06-17 13:28:48 -04001547 if (DEBUG_LOADERS) {
1548 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001549 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001550 + "ms for previous step to finish binding");
1551 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001552 }
Joe Onorato36115782010-06-17 13:28:48 -04001553 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001554
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001555 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001556 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001557 // Ensure that we have a valid page index to load synchronously
1558 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1559 "valid page index");
1560 }
1561 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1562 // Ensure that we don't try and bind a specified page when the pages have not been
1563 // loaded already (we should load everything asynchronously in that case)
1564 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1565 }
1566 synchronized (mLock) {
1567 if (mIsLoaderTaskRunning) {
1568 // Ensure that we are never running the background loading at this point since
1569 // we also touch the background collections
1570 throw new RuntimeException("Error! Background loading is already running");
1571 }
1572 }
1573
1574 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1575 // data structures, we can't allow any other thread to touch that data, but because
1576 // this call is synchronous, we can get away with not locking).
1577
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001578 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001579 // operations from the previous activity. We need to ensure that all queued operations
1580 // are executed before any synchronous binding work is done.
1581 mHandler.flush();
1582
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 // Divide the set of loaded items into those that we are binding synchronously, and
1584 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001585 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1587 // arise from that.
1588 onlyBindAllApps();
1589 }
1590
Joe Onorato36115782010-06-17 13:28:48 -04001591 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001592 boolean isUpgrade = false;
1593
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001594 synchronized (mLock) {
1595 mIsLoaderTaskRunning = true;
1596 }
Joe Onorato36115782010-06-17 13:28:48 -04001597 // Optimize for end-user experience: if the Launcher is up and // running with the
1598 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1599 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001600 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001601 // Elevate priority when Home launches for the first time to avoid
1602 // starving at boot time. Staring at a blank home is not cool.
1603 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001604 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1605 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001606 android.os.Process.setThreadPriority(mIsLaunching
1607 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1608 }
Winson Chung64359a52013-07-08 17:17:08 -07001609 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001610 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001611
Joe Onorato36115782010-06-17 13:28:48 -04001612 if (mStopped) {
1613 break keep_running;
1614 }
1615
1616 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1617 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001618 synchronized (mLock) {
1619 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001620 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001621 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1622 }
1623 }
Joe Onorato36115782010-06-17 13:28:48 -04001624 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001625
1626 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001627 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1628 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001629
1630 // Restore the default thread priority after we are done loading items
1631 synchronized (mLock) {
1632 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1633 }
Joe Onorato36115782010-06-17 13:28:48 -04001634 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001635
Winson Chungaac01e12011-08-17 10:37:13 -07001636 // Update the saved icons if necessary
1637 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001638 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001639 for (Object key : sBgDbIconCache.keySet()) {
1640 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1641 }
1642 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001643 }
Winson Chungaac01e12011-08-17 10:37:13 -07001644
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001645 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001646 // Ensure that all the applications that are in the system are
1647 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001648 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001649 verifyApplications();
1650 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001651 }
1652
Joe Onorato36115782010-06-17 13:28:48 -04001653 // Clear out this reference, otherwise we end up holding it until all of the
1654 // callback runnables are done.
1655 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001656
Joe Onorato36115782010-06-17 13:28:48 -04001657 synchronized (mLock) {
1658 // If we are still the last one to be scheduled, remove ourselves.
1659 if (mLoaderTask == this) {
1660 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001661 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001662 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001663 }
Joe Onorato36115782010-06-17 13:28:48 -04001664 }
1665
1666 public void stopLocked() {
1667 synchronized (LoaderTask.this) {
1668 mStopped = true;
1669 this.notify();
1670 }
1671 }
1672
1673 /**
1674 * Gets the callbacks object. If we've been stopped, or if the launcher object
1675 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1676 * object that was around when the deferred message was scheduled, and if there's
1677 * a new Callbacks object around then also return null. This will save us from
1678 * calling onto it with data that will be ignored.
1679 */
1680 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1681 synchronized (mLock) {
1682 if (mStopped) {
1683 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001684 }
Joe Onorato36115782010-06-17 13:28:48 -04001685
1686 if (mCallbacks == null) {
1687 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001688 }
Joe Onorato36115782010-06-17 13:28:48 -04001689
1690 final Callbacks callbacks = mCallbacks.get();
1691 if (callbacks != oldCallbacks) {
1692 return null;
1693 }
1694 if (callbacks == null) {
1695 Log.w(TAG, "no mCallbacks");
1696 return null;
1697 }
1698
1699 return callbacks;
1700 }
1701 }
1702
Winson Chungc763c4e2013-07-19 13:49:06 -07001703 private void verifyApplications() {
1704 final Context context = mApp.getContext();
1705
1706 // Cross reference all the applications in our apps list with items in the workspace
1707 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001708 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001709 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001710 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001711 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001712 if (tmpInfos.isEmpty()) {
1713 // We are missing an application icon, so add this to the workspace
1714 added.add(app);
1715 // This is a rare event, so lets log it
1716 Log.e(TAG, "Missing Application on load: " + app);
1717 }
1718 }
1719 }
1720 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001721 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001722 }
1723 }
1724
Joe Onorato36115782010-06-17 13:28:48 -04001725 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001726 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001727 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001728 LauncherAppState app = LauncherAppState.getInstance();
1729 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001730 final int countX = (int) grid.numColumns;
1731 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001732
Adam Cohendcd297f2013-06-18 13:13:40 -07001733 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001734 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001735 // Return early if we detect that an item is under the hotseat button
1736 if (mCallbacks == null ||
1737 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001738 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001739 Log.e(TAG, "Error loading shortcut into hotseat " + item
1740 + " into position (" + item.screenId + ":" + item.cellX + ","
1741 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001742 return false;
1743 }
1744
Dan Sandler295ae182013-12-10 16:05:47 -05001745 final ItemInfo[][] hotseatItems =
1746 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1747
Adam Cohenae4409d2013-11-26 10:34:59 -08001748 if (item.screenId >= grid.numHotseatIcons) {
1749 Log.e(TAG, "Error loading shortcut " + item
1750 + " into hotseat position " + item.screenId
1751 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1752 + ")");
1753 return false;
1754 }
1755
Dan Sandler295ae182013-12-10 16:05:47 -05001756 if (hotseatItems != null) {
1757 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001758 Log.e(TAG, "Error loading shortcut into hotseat " + item
1759 + " into position (" + item.screenId + ":" + item.cellX + ","
1760 + item.cellY + ") occupied by "
1761 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1762 [(int) item.screenId][0]);
1763 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001764 } else {
1765 hotseatItems[(int) item.screenId][0] = item;
1766 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001768 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001769 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001770 items[(int) item.screenId][0] = item;
1771 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001772 return true;
1773 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001774 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1775 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001776 return true;
1777 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001778
Adam Cohendcd297f2013-06-18 13:13:40 -07001779 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001780 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001781 occupied.put(item.screenId, items);
1782 }
1783
Dan Sandler295ae182013-12-10 16:05:47 -05001784 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001785 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1786 item.cellX < 0 || item.cellY < 0 ||
1787 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1788 Log.e(TAG, "Error loading shortcut " + item
1789 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1790 + item.cellX + "," + item.cellY
1791 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1792 return false;
1793 }
1794
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001795 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001796 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1797 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001798 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001799 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001801 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001802 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001804 return false;
1805 }
1806 }
1807 }
1808 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1809 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001811 }
1812 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001813
Joe Onorato36115782010-06-17 13:28:48 -04001814 return true;
1815 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001816
Winson Chungba9c37f2013-08-30 14:11:37 -07001817 /** Clears all the sBg data structures */
1818 private void clearSBgDataStructures() {
1819 synchronized (sBgLock) {
1820 sBgWorkspaceItems.clear();
1821 sBgAppWidgets.clear();
1822 sBgFolders.clear();
1823 sBgItemsIdMap.clear();
1824 sBgDbIconCache.clear();
1825 sBgWorkspaceScreens.clear();
1826 }
1827 }
1828
Dan Sandlerd5024042014-01-09 15:01:33 -05001829 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001830 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001831 // Log to disk
1832 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1833
Joe Onorato36115782010-06-17 13:28:48 -04001834 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001835
Joe Onorato36115782010-06-17 13:28:48 -04001836 final Context context = mContext;
1837 final ContentResolver contentResolver = context.getContentResolver();
1838 final PackageManager manager = context.getPackageManager();
1839 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1840 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001841 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1842 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001843 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001844
Winson Chung892c74d2013-08-22 16:15:50 -07001845 LauncherAppState app = LauncherAppState.getInstance();
1846 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1847 int countX = (int) grid.numColumns;
1848 int countY = (int) grid.numRows;
1849
Dan Sandlerd5024042014-01-09 15:01:33 -05001850 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1851 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1852 LauncherAppState.getLauncherProvider().deleteDatabase();
1853 }
1854
1855 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1856 // append the user's Launcher2 shortcuts
1857 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1858 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1859 } else {
1860 // Make sure the default workspace is loaded
1861 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001862 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001863 }
Adam Cohene25af792013-06-06 23:08:25 -07001864
Adam Cohen71483f42014-05-15 14:04:01 -07001865 // This code path is for our old migration code and should no longer be exercised
1866 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001867
Winson Chung9f9f00b2013-11-15 13:27:00 -08001868 // Log to disk
1869 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001870
Winson Chung2abf94d2012-07-18 18:16:38 -07001871 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001872 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001873
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001874 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001875 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001876 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001877 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001878 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001879
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001880 // +1 for the hotseat (it can be larger than the workspace)
1881 // Load workspace in reverse order to ensure that latest items are loaded first (and
1882 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001883 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001884
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001885 try {
1886 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1887 final int intentIndex = c.getColumnIndexOrThrow
1888 (LauncherSettings.Favorites.INTENT);
1889 final int titleIndex = c.getColumnIndexOrThrow
1890 (LauncherSettings.Favorites.TITLE);
1891 final int iconTypeIndex = c.getColumnIndexOrThrow(
1892 LauncherSettings.Favorites.ICON_TYPE);
1893 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1894 final int iconPackageIndex = c.getColumnIndexOrThrow(
1895 LauncherSettings.Favorites.ICON_PACKAGE);
1896 final int iconResourceIndex = c.getColumnIndexOrThrow(
1897 LauncherSettings.Favorites.ICON_RESOURCE);
1898 final int containerIndex = c.getColumnIndexOrThrow(
1899 LauncherSettings.Favorites.CONTAINER);
1900 final int itemTypeIndex = c.getColumnIndexOrThrow(
1901 LauncherSettings.Favorites.ITEM_TYPE);
1902 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1903 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001904 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1905 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 final int screenIndex = c.getColumnIndexOrThrow(
1907 LauncherSettings.Favorites.SCREEN);
1908 final int cellXIndex = c.getColumnIndexOrThrow
1909 (LauncherSettings.Favorites.CELLX);
1910 final int cellYIndex = c.getColumnIndexOrThrow
1911 (LauncherSettings.Favorites.CELLY);
1912 final int spanXIndex = c.getColumnIndexOrThrow
1913 (LauncherSettings.Favorites.SPANX);
1914 final int spanYIndex = c.getColumnIndexOrThrow(
1915 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001916 final int restoredIndex = c.getColumnIndexOrThrow(
1917 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001918 final int profileIdIndex = c.getColumnIndexOrThrow(
1919 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1921 //final int displayModeIndex = c.getColumnIndexOrThrow(
1922 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001923
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001924 ShortcutInfo info;
1925 String intentDescription;
1926 LauncherAppWidgetInfo appWidgetInfo;
1927 int container;
1928 long id;
1929 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001930 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001931
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001932 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001933 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001934 try {
1935 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001936 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001937 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001938
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001939 switch (itemType) {
1940 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1941 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001942 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001944 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001945 user = mUserManager.getUserForSerialNumber(serialNumber);
1946 if (user == null) {
1947 // User has been deleted remove the item.
1948 itemsToRemove.add(id);
1949 continue;
1950 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001951 try {
1952 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001953 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001954 if (cn != null && cn.getPackageName() != null) {
1955 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1956 cn.getPackageName(), user);
1957 boolean validComponent = validPkg &&
1958 launcherApps.isActivityEnabledForProfile(cn, user);
1959
1960 if (validComponent) {
1961 if (restored) {
1962 // no special handling necessary for this item
1963 restoredRows.add(id);
1964 restored = false;
1965 }
1966 } else if (validPkg) {
1967 // The app is installed but the component is no
1968 // longer available.
1969 Launcher.addDumpLog(TAG,
1970 "Invalid component removed: " + cn, true);
1971 itemsToRemove.add(id);
1972 continue;
1973 } else if (restored) {
1974 // Package is not yet available but might be
1975 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001976 Launcher.addDumpLog(TAG,
1977 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001978 } else if (isSdCardReady) {
1979 // Do not wait for external media load anymore.
1980 // Log the invalid package, and remove it
1981 Launcher.addDumpLog(TAG,
1982 "Invalid package removed: " + cn, true);
1983 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05001984 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001985 } else {
1986 // SdCard is not ready yet. Package might get available,
1987 // once it is ready.
1988 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1989 + " (check again later)", true);
1990 HashSet<String> pkgs = sPendingPackages.get(user);
1991 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001992 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001993 sPendingPackages.put(user, pkgs);
1994 }
1995 pkgs.add(cn.getPackageName());
1996 allowMissingTarget = true;
1997 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07001998 }
Winson Chungee055712013-07-30 14:46:24 -07001999 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002000 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002001 Launcher.addDumpLog(TAG,
2002 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002003 continue;
2004 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002005
Chris Wrenf4d08112014-01-16 18:13:56 -05002006 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002007 if (user.equals(UserHandleCompat.myUserHandle())) {
2008 Launcher.addDumpLog(TAG,
2009 "constructing info for partially restored package",
2010 true);
2011 info = getRestoredItemInfo(c, titleIndex, intent);
2012 intent = getRestoredItemIntent(c, context, intent);
2013 } else {
2014 // Don't restore items for other profiles.
2015 itemsToRemove.add(id);
2016 continue;
2017 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002018 } else if (itemType ==
2019 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002020 info = getShortcutInfo(manager, intent, user, context, c,
2021 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002022 } else {
2023 info = getShortcutInfo(c, context, iconTypeIndex,
2024 iconPackageIndex, iconResourceIndex, iconIndex,
2025 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002026
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002027 // App shortcuts that used to be automatically added to Launcher
2028 // didn't always have the correct intent flags set, so do that
2029 // here
2030 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002031 intent.getCategories() != null &&
2032 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002033 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002034 intent.addFlags(
2035 Intent.FLAG_ACTIVITY_NEW_TASK |
2036 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2037 }
Michael Jurka96879562012-03-22 05:54:33 -07002038 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002039
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002040 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002041 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002043 container = c.getInt(containerIndex);
2044 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002045 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002046 info.cellX = c.getInt(cellXIndex);
2047 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002048 info.spanX = 1;
2049 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002050 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002051 info.isDisabled = isSafeMode
2052 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002053
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002055 deleteOnInvalidPlacement.set(false);
2056 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2057 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002058 itemsToRemove.add(id);
2059 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002060 break;
2061 }
2062
2063 switch (container) {
2064 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2065 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2066 sBgWorkspaceItems.add(info);
2067 break;
2068 default:
2069 // Item is in a user folder
2070 FolderInfo folderInfo =
2071 findOrMakeFolder(sBgFolders, container);
2072 folderInfo.add(info);
2073 break;
2074 }
2075 sBgItemsIdMap.put(info.id, info);
2076
2077 // now that we've loaded everthing re-save it with the
2078 // icon in case it disappears somehow.
2079 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002080 } else {
2081 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 }
2083 break;
2084
2085 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2086 id = c.getLong(idIndex);
2087 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2088
2089 folderInfo.title = c.getString(titleIndex);
2090 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002091 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002092 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002093 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002094 folderInfo.cellX = c.getInt(cellXIndex);
2095 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002096 folderInfo.spanX = 1;
2097 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002098
Daniel Sandler8802e962010-05-26 16:28:16 -04002099 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002100 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002101 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002102 deleteOnInvalidPlacement)) {
2103 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002104 itemsToRemove.add(id);
2105 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002106 break;
2107 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002108
Joe Onorato9c1289c2009-08-17 11:03:03 -04002109 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2111 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2112 sBgWorkspaceItems.add(folderInfo);
2113 break;
Joe Onorato36115782010-06-17 13:28:48 -04002114 }
Joe Onorato17a89222011-02-08 17:26:11 -08002115
Chris Wrenf4d08112014-01-16 18:13:56 -05002116 if (restored) {
2117 // no special handling required for restored folders
2118 restoredRows.add(id);
2119 }
2120
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2122 sBgFolders.put(folderInfo.id, folderInfo);
2123 break;
2124
2125 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2126 // Read all Launcher-specific widget details
2127 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002128 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002129 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002130 final ComponentName component =
2131 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002132
Sunny Goyal651077b2014-06-30 14:15:31 -07002133 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002134 final boolean isIdValid = (restoreStatus &
2135 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002136
Sunny Goyalff572272014-07-23 13:58:07 -07002137 final boolean wasProviderReady = (restoreStatus &
2138 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002139
Sunny Goyalff572272014-07-23 13:58:07 -07002140 final AppWidgetProviderInfo provider = isIdValid
2141 ? widgets.getAppWidgetInfo(appWidgetId)
2142 : findAppWidgetProviderInfoWithComponent(context, component);
2143
2144 final boolean isProviderReady = isValidProvider(provider);
2145 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002146 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002147 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002149 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002150 itemsToRemove.add(id);
2151 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002152 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002153 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2154 provider.provider);
2155 int[] minSpan =
2156 Launcher.getMinSpanForWidget(context, provider);
2157 appWidgetInfo.minSpanX = minSpan[0];
2158 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002159
2160 int status = restoreStatus;
2161 if (!wasProviderReady) {
2162 // If provider was not previously ready, update the
2163 // status and UI flag.
2164
2165 // Id would be valid only if the widget restore broadcast was received.
2166 if (isIdValid) {
2167 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2168 } else {
2169 status &= ~LauncherAppWidgetInfo
2170 .FLAG_PROVIDER_NOT_READY;
2171 }
2172 }
2173 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002174 } else {
2175 Log.v(TAG, "Widget restore pending id=" + id
2176 + " appWidgetId=" + appWidgetId
2177 + " status =" + restoreStatus);
2178 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002179 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002180 appWidgetInfo.restoreStatus = restoreStatus;
2181 }
Sunny Goyalff572272014-07-23 13:58:07 -07002182
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002183 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002184 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002185 appWidgetInfo.cellX = c.getInt(cellXIndex);
2186 appWidgetInfo.cellY = c.getInt(cellYIndex);
2187 appWidgetInfo.spanX = c.getInt(spanXIndex);
2188 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002189
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002190 container = c.getInt(containerIndex);
2191 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2192 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2193 Log.e(TAG, "Widget found where container != " +
2194 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2195 continue;
2196 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002197
Adam Cohene25af792013-06-06 23:08:25 -07002198 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002199 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002200 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002201 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002202 deleteOnInvalidPlacement)) {
2203 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002204 itemsToRemove.add(id);
2205 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002206 break;
2207 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002208
Sunny Goyalff572272014-07-23 13:58:07 -07002209 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002210 String providerName = provider.provider.flattenToString();
Sunny Goyalff572272014-07-23 13:58:07 -07002211 if (!providerName.equals(savedProvider) ||
2212 (appWidgetInfo.restoreStatus != restoreStatus)) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002213 ContentValues values = new ContentValues();
2214 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2215 providerName);
2216 values.put(LauncherSettings.Favorites.RESTORED,
Sunny Goyalff572272014-07-23 13:58:07 -07002217 appWidgetInfo.restoreStatus);
Sunny Goyal651077b2014-06-30 14:15:31 -07002218 String where = BaseColumns._ID + "= ?";
2219 String[] args = {Long.toString(id)};
2220 contentResolver.update(contentUri, values, where, args);
2221 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002222 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2224 sBgAppWidgets.add(appWidgetInfo);
2225 }
Joe Onorato36115782010-06-17 13:28:48 -04002226 break;
2227 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002229 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002230 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002231 }
2232 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002233 if (c != null) {
2234 c.close();
2235 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002236 }
2237
Winson Chungba9c37f2013-08-30 14:11:37 -07002238 // Break early if we've stopped loading
2239 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002240 clearSBgDataStructures();
2241 return false;
2242 }
2243
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002244 if (itemsToRemove.size() > 0) {
2245 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002246 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247 // Remove dead items
2248 for (long id : itemsToRemove) {
2249 if (DEBUG_LOADERS) {
2250 Log.d(TAG, "Removed id = " + id);
2251 }
2252 // Don't notify content observers
2253 try {
2254 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2255 null, null);
2256 } catch (RemoteException e) {
2257 Log.w(TAG, "Could not remove id = " + id);
2258 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002259 }
2260 }
2261
Chris Wrenf4d08112014-01-16 18:13:56 -05002262 if (restoredRows.size() > 0) {
2263 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2264 LauncherSettings.Favorites.CONTENT_URI);
2265 // Update restored items that no longer require special handling
2266 try {
2267 StringBuilder selectionBuilder = new StringBuilder();
2268 selectionBuilder.append(LauncherSettings.Favorites._ID);
2269 selectionBuilder.append(" IN (");
2270 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2271 selectionBuilder.append(")");
2272 ContentValues values = new ContentValues();
2273 values.put(LauncherSettings.Favorites.RESTORED, 0);
2274 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2275 values, selectionBuilder.toString(), null);
2276 } catch (RemoteException e) {
2277 Log.w(TAG, "Could not update restored rows");
2278 }
2279 }
2280
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002281 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2282 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002283 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002284 null, sWorker);
2285 }
2286
Winson Chungc763c4e2013-07-19 13:49:06 -07002287 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002288 long maxScreenId = 0;
2289 // If we're importing we use the old screen order.
2290 for (ItemInfo item: sBgItemsIdMap.values()) {
2291 long screenId = item.screenId;
2292 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2293 !sBgWorkspaceScreens.contains(screenId)) {
2294 sBgWorkspaceScreens.add(screenId);
2295 if (screenId > maxScreenId) {
2296 maxScreenId = screenId;
2297 }
2298 }
2299 }
2300 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002301 // Log to disk
2302 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2303 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2304 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002305
Michael Jurka414300a2013-08-27 15:42:35 +02002306 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002307 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002308
2309 // Update the max item id after we load an old db
2310 long maxItemId = 0;
2311 // If we're importing we use the old screen order.
2312 for (ItemInfo item: sBgItemsIdMap.values()) {
2313 maxItemId = Math.max(maxItemId, item.id);
2314 }
Michael Jurka414300a2013-08-27 15:42:35 +02002315 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002316 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002317 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2318 for (Integer i : orderedScreens.keySet()) {
2319 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002320 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002321 // Log to disk
2322 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2323 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002324
2325 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002326 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002327 for (ItemInfo item: sBgItemsIdMap.values()) {
2328 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002329 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2330 unusedScreens.contains(screenId)) {
2331 unusedScreens.remove(screenId);
2332 }
2333 }
2334
2335 // If there are any empty screens remove them, and update.
2336 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002337 // Log to disk
2338 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2339 TextUtils.join(", ", unusedScreens), true);
2340
Winson Chung933bae62013-08-29 11:42:30 -07002341 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002342 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2343 }
2344 }
2345
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002346 if (DEBUG_LOADERS) {
2347 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2348 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002349 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002350 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002351 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002352
Daniel Sandler566da102013-06-25 23:43:45 -04002353 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002354 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002356 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 line += " | ";
2358 }
Winson Chung892c74d2013-08-22 16:15:50 -07002359 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002360 ItemInfo[][] screen = occupied.get(screenId);
2361 if (x < screen.length && y < screen[x].length) {
2362 line += (screen[x][y] != null) ? "#" : ".";
2363 } else {
2364 line += "!";
2365 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002366 }
Joe Onorato36115782010-06-17 13:28:48 -04002367 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002368 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002369 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002370 }
Joe Onorato36115782010-06-17 13:28:48 -04002371 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002372 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002373 }
2374
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002375 /** Filters the set of items who are directly or indirectly (via another container) on the
2376 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002377 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002378 ArrayList<ItemInfo> allWorkspaceItems,
2379 ArrayList<ItemInfo> currentScreenItems,
2380 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002381 // Purge any null ItemInfos
2382 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2383 while (iter.hasNext()) {
2384 ItemInfo i = iter.next();
2385 if (i == null) {
2386 iter.remove();
2387 }
2388 }
2389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002390 // Order the set of items by their containers first, this allows use to walk through the
2391 // list sequentially, build up a list of containers that are in the specified screen,
2392 // as well as all items in those containers.
2393 Set<Long> itemsOnScreen = new HashSet<Long>();
2394 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2395 @Override
2396 public int compare(ItemInfo lhs, ItemInfo rhs) {
2397 return (int) (lhs.container - rhs.container);
2398 }
2399 });
2400 for (ItemInfo info : allWorkspaceItems) {
2401 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002402 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 currentScreenItems.add(info);
2404 itemsOnScreen.add(info.id);
2405 } else {
2406 otherScreenItems.add(info);
2407 }
2408 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2409 currentScreenItems.add(info);
2410 itemsOnScreen.add(info.id);
2411 } else {
2412 if (itemsOnScreen.contains(info.container)) {
2413 currentScreenItems.add(info);
2414 itemsOnScreen.add(info.id);
2415 } else {
2416 otherScreenItems.add(info);
2417 }
2418 }
2419 }
2420 }
2421
2422 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002423 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002424 ArrayList<LauncherAppWidgetInfo> appWidgets,
2425 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2426 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002427
2428 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002429 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002430 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002431 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432 currentScreenWidgets.add(widget);
2433 } else {
2434 otherScreenWidgets.add(widget);
2435 }
2436 }
2437 }
2438
2439 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002440 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002441 HashMap<Long, ItemInfo> itemsIdMap,
2442 HashMap<Long, FolderInfo> folders,
2443 HashMap<Long, FolderInfo> currentScreenFolders,
2444 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002445
2446 for (long id : folders.keySet()) {
2447 ItemInfo info = itemsIdMap.get(id);
2448 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002449 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002450 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002451 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 currentScreenFolders.put(id, folder);
2453 } else {
2454 otherScreenFolders.put(id, folder);
2455 }
2456 }
2457 }
2458
2459 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2460 * right) */
2461 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002462 final LauncherAppState app = LauncherAppState.getInstance();
2463 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002464 // XXX: review this
2465 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002466 @Override
2467 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002468 int cellCountX = (int) grid.numColumns;
2469 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002470 int screenOffset = cellCountX * cellCountY;
2471 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002472 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002473 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002474 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002475 rhs.cellY * cellCountX + rhs.cellX);
2476 return (int) (lr - rr);
2477 }
2478 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002479 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002480
Adam Cohendcd297f2013-06-18 13:13:40 -07002481 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2482 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002483 final Runnable r = new Runnable() {
2484 @Override
2485 public void run() {
2486 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2487 if (callbacks != null) {
2488 callbacks.bindScreens(orderedScreens);
2489 }
2490 }
2491 };
2492 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2493 }
2494
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002495 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2496 final ArrayList<ItemInfo> workspaceItems,
2497 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2498 final HashMap<Long, FolderInfo> folders,
2499 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002500
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002501 final boolean postOnMainThread = (deferredBindRunnables != null);
2502
2503 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002504 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002505 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002506 final int start = i;
2507 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 final Runnable r = new Runnable() {
2509 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002510 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002511 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002512 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002513 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2514 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002515 }
2516 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002517 };
2518 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002519 synchronized (deferredBindRunnables) {
2520 deferredBindRunnables.add(r);
2521 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002523 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002524 }
Joe Onorato36115782010-06-17 13:28:48 -04002525 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526
2527 // Bind the folders
2528 if (!folders.isEmpty()) {
2529 final Runnable r = new Runnable() {
2530 public void run() {
2531 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2532 if (callbacks != null) {
2533 callbacks.bindFolders(folders);
2534 }
2535 }
2536 };
2537 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002538 synchronized (deferredBindRunnables) {
2539 deferredBindRunnables.add(r);
2540 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002541 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002542 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002543 }
2544 }
2545
2546 // Bind the widgets, one at a time
2547 N = appWidgets.size();
2548 for (int i = 0; i < N; i++) {
2549 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2550 final Runnable r = new Runnable() {
2551 public void run() {
2552 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2553 if (callbacks != null) {
2554 callbacks.bindAppWidget(widget);
2555 }
2556 }
2557 };
2558 if (postOnMainThread) {
2559 deferredBindRunnables.add(r);
2560 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002561 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 }
2563 }
2564 }
2565
2566 /**
2567 * Binds all loaded data to actual views on the main thread.
2568 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002569 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570 final long t = SystemClock.uptimeMillis();
2571 Runnable r;
2572
2573 // Don't use these two variables in any of the callback runnables.
2574 // Otherwise we hold a reference to them.
2575 final Callbacks oldCallbacks = mCallbacks.get();
2576 if (oldCallbacks == null) {
2577 // This launcher has exited and nobody bothered to tell us. Just bail.
2578 Log.w(TAG, "LoaderTask running with no launcher");
2579 return;
2580 }
2581
Winson Chung9b9fb962013-11-15 15:39:34 -08002582 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2584 ArrayList<LauncherAppWidgetInfo> appWidgets =
2585 new ArrayList<LauncherAppWidgetInfo>();
2586 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2587 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002588 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002589 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002590 workspaceItems.addAll(sBgWorkspaceItems);
2591 appWidgets.addAll(sBgAppWidgets);
2592 folders.putAll(sBgFolders);
2593 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002594 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002595 }
2596
Derek Prothro7aff3992013-12-10 14:00:37 -05002597 final boolean isLoadingSynchronously =
2598 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002599 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002600 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002601 if (currScreen >= orderedScreenIds.size()) {
2602 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002603 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002604 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002605 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002606 final long currentScreenId = currentScreen < 0
2607 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002608
2609 // Load all the items that are on the current page first (and in the process, unbind
2610 // all the existing workspace items before we call startBinding() below.
2611 unbindWorkspaceItemsOnMainThread();
2612
2613 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002614 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2615 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2616 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2617 new ArrayList<LauncherAppWidgetInfo>();
2618 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2619 new ArrayList<LauncherAppWidgetInfo>();
2620 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2621 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2622
Winson Chung9b9fb962013-11-15 15:39:34 -08002623 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002624 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002625 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002626 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002627 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002628 otherFolders);
2629 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2630 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2631
2632 // Tell the workspace that we're about to start binding items
2633 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002634 public void run() {
2635 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2636 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002637 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002638 }
2639 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 };
Winson Chung81b52252012-08-27 15:34:29 -07002641 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002642
Adam Cohendcd297f2013-06-18 13:13:40 -07002643 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2644
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002645 // Load items on the current page
2646 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2647 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002648 if (isLoadingSynchronously) {
2649 r = new Runnable() {
2650 public void run() {
2651 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002652 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002653 callbacks.onPageBoundSynchronously(currentScreen);
2654 }
2655 }
2656 };
Winson Chung81b52252012-08-27 15:34:29 -07002657 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002658 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002659
Winson Chung4a2afa32012-07-19 14:53:05 -07002660 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2661 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002662 synchronized (mDeferredBindRunnables) {
2663 mDeferredBindRunnables.clear();
2664 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002665 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002666 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667
2668 // Tell the workspace that we're done binding items
2669 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002670 public void run() {
2671 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2672 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002673 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002674 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002675
Winson Chung98e030b2012-05-07 16:01:11 -07002676 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002677 if (DEBUG_LOADERS) {
2678 Log.d(TAG, "bound workspace in "
2679 + (SystemClock.uptimeMillis()-t) + "ms");
2680 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002681
2682 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002683 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002685 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002686 synchronized (mDeferredBindRunnables) {
2687 mDeferredBindRunnables.add(r);
2688 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002689 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002690 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002691 }
Joe Onorato36115782010-06-17 13:28:48 -04002692 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002693
Joe Onorato36115782010-06-17 13:28:48 -04002694 private void loadAndBindAllApps() {
2695 if (DEBUG_LOADERS) {
2696 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2697 }
2698 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002699 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002700 synchronized (LoaderTask.this) {
2701 if (mStopped) {
2702 return;
2703 }
2704 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002705 }
Joe Onorato36115782010-06-17 13:28:48 -04002706 } else {
2707 onlyBindAllApps();
2708 }
2709 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002710
Joe Onorato36115782010-06-17 13:28:48 -04002711 private void onlyBindAllApps() {
2712 final Callbacks oldCallbacks = mCallbacks.get();
2713 if (oldCallbacks == null) {
2714 // This launcher has exited and nobody bothered to tell us. Just bail.
2715 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2716 return;
2717 }
2718
2719 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002720 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002721 final ArrayList<AppInfo> list
2722 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002723 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002724 public void run() {
2725 final long t = SystemClock.uptimeMillis();
2726 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2727 if (callbacks != null) {
2728 callbacks.bindAllApplications(list);
2729 }
2730 if (DEBUG_LOADERS) {
2731 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2732 + (SystemClock.uptimeMillis()-t) + "ms");
2733 }
2734 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002735 };
2736 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002737 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002738 r.run();
2739 } else {
2740 mHandler.post(r);
2741 }
Joe Onorato36115782010-06-17 13:28:48 -04002742 }
2743
Winson Chung64359a52013-07-08 17:17:08 -07002744 private void loadAllApps() {
2745 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002746
Joe Onorato36115782010-06-17 13:28:48 -04002747 final Callbacks oldCallbacks = mCallbacks.get();
2748 if (oldCallbacks == null) {
2749 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002750 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002751 return;
2752 }
2753
2754 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2755 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2756
Kenny Guyed131872014-04-30 03:02:21 +01002757 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2758
Winson Chung64359a52013-07-08 17:17:08 -07002759 // Clear the list of apps
2760 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002761 for (UserHandleCompat user : profiles) {
2762 // Query for the set of apps
2763 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2764 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2765 if (DEBUG_LOADERS) {
2766 Log.d(TAG, "getActivityList took "
2767 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2768 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2769 }
2770 // Fail if we don't have any apps
2771 if (apps == null || apps.isEmpty()) {
2772 return;
2773 }
2774 // Sort the applications by name
2775 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2776 Collections.sort(apps,
2777 new LauncherModel.ShortcutNameComparator(mLabelCache));
2778 if (DEBUG_LOADERS) {
2779 Log.d(TAG, "sort took "
2780 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2781 }
Joe Onorato36115782010-06-17 13:28:48 -04002782
Kenny Guyed131872014-04-30 03:02:21 +01002783 // Create the ApplicationInfos
2784 for (int i = 0; i < apps.size(); i++) {
2785 LauncherActivityInfoCompat app = apps.get(i);
2786 // This builds the icon bitmaps.
2787 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2788 }
Winson Chung64359a52013-07-08 17:17:08 -07002789 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002790 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002791 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2792 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002793
2794 // Post callback on main thread
2795 mHandler.post(new Runnable() {
2796 public void run() {
2797 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002798 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002799 if (callbacks != null) {
2800 callbacks.bindAllApplications(added);
2801 if (DEBUG_LOADERS) {
2802 Log.d(TAG, "bound " + added.size() + " apps in "
2803 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2804 }
2805 } else {
2806 Log.i(TAG, "not binding apps: no Launcher activity");
2807 }
2808 }
2809 });
2810
Joe Onorato36115782010-06-17 13:28:48 -04002811 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002812 Log.d(TAG, "Icons processed in "
2813 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002814 }
2815 }
2816
2817 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002818 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002819 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2820 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2821 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2822 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2823 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2824 }
Joe Onorato36115782010-06-17 13:28:48 -04002825 }
2826 }
2827
2828 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002829 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002830 }
2831
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002832 private class AppsAvailabilityCheck extends BroadcastReceiver {
2833
2834 @Override
2835 public void onReceive(Context context, Intent intent) {
2836 synchronized (sBgLock) {
2837 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2838 .getInstance(mApp.getContext());
2839 ArrayList<String> packagesRemoved;
2840 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2841 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002842 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002843 for (String pkg : entry.getValue()) {
2844 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2845 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2846 packagesRemoved.add(pkg);
2847 }
2848 }
2849 if (!packagesRemoved.isEmpty()) {
2850 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2851 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2852 }
2853 }
2854 sPendingPackages.clear();
2855 }
2856 }
2857 }
2858
Joe Onorato36115782010-06-17 13:28:48 -04002859 private class PackageUpdatedTask implements Runnable {
2860 int mOp;
2861 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002862 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002863
2864 public static final int OP_NONE = 0;
2865 public static final int OP_ADD = 1;
2866 public static final int OP_UPDATE = 2;
2867 public static final int OP_REMOVE = 3; // uninstlled
2868 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2869
2870
Kenny Guyed131872014-04-30 03:02:21 +01002871 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002872 mOp = op;
2873 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002874 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002875 }
2876
2877 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002878 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002879
2880 final String[] packages = mPackages;
2881 final int N = packages.length;
2882 switch (mOp) {
2883 case OP_ADD:
2884 for (int i=0; i<N; i++) {
2885 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002886 mIconCache.remove(packages[i], mUser);
2887 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002888 }
2889 break;
2890 case OP_UPDATE:
2891 for (int i=0; i<N; i++) {
2892 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002893 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002894 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002895 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002896 }
2897 break;
2898 case OP_REMOVE:
2899 case OP_UNAVAILABLE:
2900 for (int i=0; i<N; i++) {
2901 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002902 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002903 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002904 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002905 }
2906 break;
2907 }
2908
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002909 ArrayList<AppInfo> added = null;
2910 ArrayList<AppInfo> modified = null;
2911 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002912
Adam Cohen487f7dd2012-06-28 18:12:10 -07002913 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002914 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002915 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002916 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002917 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002918 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002919 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002920 }
Winson Chung5d55f332012-07-16 20:45:03 -07002921 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002922 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002923 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002924 }
2925
Joe Onorato36115782010-06-17 13:28:48 -04002926 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2927 if (callbacks == null) {
2928 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2929 return;
2930 }
2931
2932 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002933 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002934 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002935 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002936 addAndBindAddedWorkspaceApps(context, addedInfos);
2937 } else {
2938 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002939 }
Joe Onorato36115782010-06-17 13:28:48 -04002940 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002941
Joe Onorato36115782010-06-17 13:28:48 -04002942 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002943 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002944
2945 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002946 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002947 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002948 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002949 for (ItemInfo i : infos) {
2950 if (isShortcutInfoUpdateable(i)) {
2951 ShortcutInfo info = (ShortcutInfo) i;
2952 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002953 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002954 updateItemInDatabase(context, info);
2955 }
2956 }
2957 }
2958
Joe Onorato36115782010-06-17 13:28:48 -04002959 mHandler.post(new Runnable() {
2960 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002961 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2962 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002963 callbacks.bindAppsUpdated(modifiedFinal);
2964 }
2965 }
2966 });
2967 }
Winson Chung83892cc2013-05-01 16:53:33 -07002968
Winson Chungdf95eb12013-10-16 14:57:07 -07002969 final ArrayList<String> removedPackageNames =
2970 new ArrayList<String>();
2971 if (mOp == OP_REMOVE) {
2972 // Mark all packages in the broadcast to be removed
2973 removedPackageNames.addAll(Arrays.asList(packages));
2974 } else if (mOp == OP_UPDATE) {
2975 // Mark disabled packages in the broadcast to be removed
2976 final PackageManager pm = context.getPackageManager();
2977 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002978 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002979 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002980 }
2981 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002982 }
2983 // Remove all the components associated with this package
2984 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002985 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002986 for (ItemInfo i : infos) {
2987 deleteItemFromDatabase(context, i);
2988 }
2989 }
2990 // Remove all the specific components
2991 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002992 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002993 for (ItemInfo i : infos) {
2994 deleteItemFromDatabase(context, i);
2995 }
2996 }
2997 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2998 // Remove any queued items from the install queue
2999 String spKey = LauncherAppState.getSharedPreferencesKey();
3000 SharedPreferences sp =
3001 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3002 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3003 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003004 mHandler.post(new Runnable() {
3005 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003006 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3007 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003008 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003009 }
3010 }
3011 });
Joe Onoratobe386092009-11-17 17:32:16 -08003012 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003013
Michael Jurkac402cd92013-05-20 15:49:32 +02003014 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003015 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003016 mHandler.post(new Runnable() {
3017 @Override
3018 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003019 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3020 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003021 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003022 }
3023 }
3024 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003025
3026 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003027 mHandler.post(new Runnable() {
3028 public void run() {
3029 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3030 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003031 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003032 }
3033 }
3034 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003035 }
3036 }
3037
Michael Jurkac402cd92013-05-20 15:49:32 +02003038 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3039 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3040 PackageManager packageManager = context.getPackageManager();
3041 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003042 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3043
Michael Jurkac402cd92013-05-20 15:49:32 +02003044 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3045 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003046 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003047 return widgetsAndShortcuts;
3048 }
3049
Kenny Guyed131872014-04-30 03:02:21 +01003050 private static boolean isPackageDisabled(Context context, String packageName,
3051 UserHandleCompat user) {
3052 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3053 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003054 }
Adam Cohen556f6132014-01-15 15:18:08 -08003055
Kenny Guyed131872014-04-30 03:02:21 +01003056 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3057 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003058 if (cn == null) {
3059 return false;
3060 }
Kenny Guyed131872014-04-30 03:02:21 +01003061 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3062 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003063 return false;
3064 }
Kenny Guyed131872014-04-30 03:02:21 +01003065 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003066 }
3067
Adam Cohena28b78e2014-05-20 17:03:04 -07003068 public static boolean isValidPackage(Context context, String packageName,
3069 UserHandleCompat user) {
3070 if (packageName == null) {
3071 return false;
3072 }
3073 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3074 return launcherApps.isPackageEnabledForProfile(packageName, user);
3075 }
3076
Joe Onorato9c1289c2009-08-17 11:03:03 -04003077 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003078 * Make an ShortcutInfo object for a restored application or shortcut item that points
3079 * to a package that is not yet installed on the system.
3080 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003081 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003082 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003083 if (cursor != null) {
3084 info.title = cursor.getString(titleIndex);
3085 } else {
3086 info.title = "";
3087 }
Kenny Guyed131872014-04-30 03:02:21 +01003088 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003089 info.contentDescription = mUserManager.getBadgedLabelForUser(
3090 info.title.toString(), info.user);
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003091 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user, false));
Chris Wrenf4d08112014-01-16 18:13:56 -05003092 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003093 info.restoredIntent = intent;
Sunny Goyal34846382014-07-09 00:09:28 -07003094 info.wasPromise = true;
Chris Wren40c5ed32014-06-24 18:24:23 -04003095 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003096 return info;
3097 }
3098
3099 /**
3100 * Make an Intent object for a restored application or shortcut item that points
3101 * to the market page for the item.
3102 */
3103 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003104 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05003105 ComponentName componentName = intent.getComponent();
3106 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
3107 Uri marketUri = new Uri.Builder()
3108 .scheme("market")
3109 .authority("details")
3110 .appendQueryParameter("id", componentName.getPackageName())
3111 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05003112 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05003113 marketIntent.setData(marketUri);
3114 return marketIntent;
3115 }
3116
3117 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003118 * This is called from the code that adds shortcuts from the intent receiver. This
3119 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003120 */
Kenny Guyed131872014-04-30 03:02:21 +01003121 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3122 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003123 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003124 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003125
Joe Onorato56d82912010-03-07 14:32:10 -05003126 /**
3127 * Make an ShortcutInfo object for a shortcut that is an application.
3128 *
3129 * If c is not null, then it will be used to fill in missing data like the title and icon.
3130 */
Kenny Guyed131872014-04-30 03:02:21 +01003131 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3132 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003133 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003134 if (user == null) {
3135 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003136 return null;
3137 }
3138
Kenny Guyed131872014-04-30 03:02:21 +01003139 ComponentName componentName = intent.getComponent();
3140 if (componentName == null) {
3141 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3142 return null;
3143 }
3144
3145 Intent newIntent = new Intent(intent.getAction(), null);
3146 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3147 newIntent.setComponent(componentName);
3148 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003149 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003150 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3151 return null;
3152 }
3153
3154 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003155
Joe Onorato56d82912010-03-07 14:32:10 -05003156 // the resource -- This may implicitly give us back the fallback icon,
3157 // but don't worry about that. All we're doing with usingFallbackIcon is
3158 // to avoid saving lots of copies of that in the database, and most apps
3159 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003160 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003161
Joe Onorato56d82912010-03-07 14:32:10 -05003162 // the db
3163 if (icon == null) {
3164 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003165 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003166 }
3167 }
3168 // the fallback icon
3169 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003170 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003171 info.usingFallbackIcon = true;
3172 }
3173 info.setIcon(icon);
3174
Kenny Guyed131872014-04-30 03:02:21 +01003175 // From the cache.
3176 if (labelCache != null) {
3177 info.title = labelCache.get(componentName);
3178 }
3179
Joe Onorato56d82912010-03-07 14:32:10 -05003180 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003181 if (info.title == null && lai != null) {
3182 info.title = lai.getLabel();
3183 if (labelCache != null) {
3184 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003185 }
Joe Onorato56d82912010-03-07 14:32:10 -05003186 }
3187 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003188 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003189 if (c != null) {
3190 info.title = c.getString(titleIndex);
3191 }
3192 }
3193 // fall back to the class name of the activity
3194 if (info.title == null) {
3195 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003196 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003197 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003198 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003199 info.contentDescription = mUserManager.getBadgedLabelForUser(
3200 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003201 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003202 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003203
Winson Chung64359a52013-07-08 17:17:08 -07003204 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3205 ItemInfoFilter f) {
3206 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3207 for (ItemInfo i : infos) {
3208 if (i instanceof ShortcutInfo) {
3209 ShortcutInfo info = (ShortcutInfo) i;
3210 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003211 if (info.restoredIntent != null) {
3212 cn = info.restoredIntent.getComponent();
3213 }
Winson Chung64359a52013-07-08 17:17:08 -07003214 if (cn != null && f.filterItem(null, info, cn)) {
3215 filtered.add(info);
3216 }
3217 } else if (i instanceof FolderInfo) {
3218 FolderInfo info = (FolderInfo) i;
3219 for (ShortcutInfo s : info.contents) {
3220 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003221 if (s.restoredIntent != null) {
3222 cn = s.restoredIntent.getComponent();
3223 }
Winson Chung64359a52013-07-08 17:17:08 -07003224 if (cn != null && f.filterItem(info, s, cn)) {
3225 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003226 }
3227 }
Winson Chung64359a52013-07-08 17:17:08 -07003228 } else if (i instanceof LauncherAppWidgetInfo) {
3229 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3230 ComponentName cn = info.providerName;
3231 if (cn != null && f.filterItem(null, info, cn)) {
3232 filtered.add(info);
3233 }
Winson Chung8a435102012-08-30 17:16:53 -07003234 }
3235 }
Winson Chung64359a52013-07-08 17:17:08 -07003236 return new ArrayList<ItemInfo>(filtered);
3237 }
3238
Kenny Guyed131872014-04-30 03:02:21 +01003239 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3240 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003241 ItemInfoFilter filter = new ItemInfoFilter() {
3242 @Override
3243 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003244 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003245 }
3246 };
3247 return filterItemInfos(sBgItemsIdMap.values(), filter);
3248 }
3249
Kenny Guyed131872014-04-30 03:02:21 +01003250 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3251 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003252 ItemInfoFilter filter = new ItemInfoFilter() {
3253 @Override
3254 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003255 if (info.user == null) {
3256 return cn.equals(cname);
3257 } else {
3258 return cn.equals(cname) && info.user.equals(user);
3259 }
Winson Chung64359a52013-07-08 17:17:08 -07003260 }
3261 };
3262 return filterItemInfos(sBgItemsIdMap.values(), filter);
3263 }
3264
3265 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3266 if (i instanceof ShortcutInfo) {
3267 ShortcutInfo info = (ShortcutInfo) i;
3268 // We need to check for ACTION_MAIN otherwise getComponent() might
3269 // return null for some shortcuts (for instance, for shortcuts to
3270 // web pages.)
3271 Intent intent = info.intent;
3272 ComponentName name = intent.getComponent();
3273 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3274 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3275 return true;
3276 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003277 // placeholder shortcuts get special treatment, let them through too.
3278 if (info.getRestoredIntent() != null) {
3279 return true;
3280 }
Winson Chung64359a52013-07-08 17:17:08 -07003281 }
3282 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003283 }
3284
3285 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003286 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003287 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003288 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003289 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3290 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003291
Joe Onorato56d82912010-03-07 14:32:10 -05003292 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003293 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003294 // Non-app shortcuts are only supported for current user.
3295 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003296 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003297
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003298 // TODO: If there's an explicit component and we can't install that, delete it.
3299
Joe Onorato56d82912010-03-07 14:32:10 -05003300 info.title = c.getString(titleIndex);
3301
Joe Onorato9c1289c2009-08-17 11:03:03 -04003302 int iconType = c.getInt(iconTypeIndex);
3303 switch (iconType) {
3304 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3305 String packageName = c.getString(iconPackageIndex);
3306 String resourceName = c.getString(iconResourceIndex);
3307 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003308 info.customIcon = false;
3309 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003310 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003311 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003312 if (resources != null) {
3313 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003314 icon = Utilities.createIconBitmap(
3315 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003316 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003317 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003318 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003319 }
Joe Onorato56d82912010-03-07 14:32:10 -05003320 // the db
3321 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003322 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003323 }
3324 // the fallback icon
3325 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003326 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003327 info.usingFallbackIcon = true;
3328 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003329 break;
3330 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003331 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003332 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003333 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003334 info.customIcon = false;
3335 info.usingFallbackIcon = true;
3336 } else {
3337 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003338 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003339 break;
3340 default:
Kenny Guyed131872014-04-30 03:02:21 +01003341 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003342 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003343 info.customIcon = false;
3344 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003345 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003346 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003347 return info;
3348 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003349
Michael Jurka931dc972011-08-05 15:08:15 -07003350 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003351 @SuppressWarnings("all") // suppress dead code warning
3352 final boolean debug = false;
3353 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003354 Log.d(TAG, "getIconFromCursor app="
3355 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3356 }
3357 byte[] data = c.getBlob(iconIndex);
3358 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003359 return Utilities.createIconBitmap(
3360 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003361 } catch (Exception e) {
3362 return null;
3363 }
3364 }
3365
Winson Chung3d503fb2011-07-13 17:25:49 -07003366 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3367 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003368 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003369 if (info == null) {
3370 return null;
3371 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003372 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003373
3374 return info;
3375 }
3376
Winson Chunga9abd0e2010-10-27 17:18:37 -07003377 /**
Winson Chung55cef262010-10-28 14:14:18 -07003378 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3379 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003380 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003381 ComponentName component) {
3382 List<AppWidgetProviderInfo> widgets =
3383 AppWidgetManager.getInstance(context).getInstalledProviders();
3384 for (AppWidgetProviderInfo info : widgets) {
3385 if (info.provider.equals(component)) {
3386 return info;
3387 }
3388 }
3389 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003390 }
3391
3392 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003393 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3394 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3395 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3396
Adam Cohend9198822011-11-22 16:42:47 -08003397 if (intent == null) {
3398 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3399 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3400 return null;
3401 }
3402
Joe Onorato0589f0f2010-02-08 13:44:00 -08003403 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003404 boolean customIcon = false;
3405 ShortcutIconResource iconResource = null;
3406
3407 if (bitmap != null && bitmap instanceof Bitmap) {
3408 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003409 customIcon = true;
3410 } else {
3411 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3412 if (extra != null && extra instanceof ShortcutIconResource) {
3413 try {
3414 iconResource = (ShortcutIconResource) extra;
3415 final PackageManager packageManager = context.getPackageManager();
3416 Resources resources = packageManager.getResourcesForApplication(
3417 iconResource.packageName);
3418 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003419 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003420 mIconCache.getFullResIcon(resources, id),
3421 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003422 } catch (Exception e) {
3423 Log.w(TAG, "Could not load shortcut icon: " + extra);
3424 }
3425 }
3426 }
3427
Michael Jurkac9d95c52011-08-29 14:03:34 -07003428 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003429
Kenny Guyed131872014-04-30 03:02:21 +01003430 // Only support intents for current user for now. Intents sent from other
3431 // users wouldn't get here without intent forwarding anyway.
3432 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003433 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003434 if (fallbackIcon != null) {
3435 icon = fallbackIcon;
3436 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003437 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003438 info.usingFallbackIcon = true;
3439 }
Joe Onorato56d82912010-03-07 14:32:10 -05003440 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003441 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003442
Joe Onorato0589f0f2010-02-08 13:44:00 -08003443 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003444 info.contentDescription = mUserManager.getBadgedLabelForUser(
3445 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003446 info.intent = intent;
3447 info.customIcon = customIcon;
3448 info.iconResource = iconResource;
3449
3450 return info;
3451 }
3452
Winson Chungaac01e12011-08-17 10:37:13 -07003453 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3454 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003455 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003456 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003457 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003458 }
Joe Onorato56d82912010-03-07 14:32:10 -05003459 // If this icon doesn't have a custom icon, check to see
3460 // what's stored in the DB, and if it doesn't match what
3461 // we're going to show, store what we are going to show back
3462 // into the DB. We do this so when we're loading, if the
3463 // package manager can't find an icon (for example because
3464 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003465 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003466 cache.put(info, c.getBlob(iconIndex));
3467 return true;
3468 }
3469 return false;
3470 }
3471 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3472 boolean needSave = false;
3473 try {
3474 if (data != null) {
3475 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3476 Bitmap loaded = info.getIcon(mIconCache);
3477 needSave = !saved.sameAs(loaded);
3478 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003479 needSave = true;
3480 }
Winson Chungaac01e12011-08-17 10:37:13 -07003481 } catch (Exception e) {
3482 needSave = true;
3483 }
3484 if (needSave) {
3485 Log.d(TAG, "going to save icon bitmap for info=" + info);
3486 // This is slower than is ideal, but this only happens once
3487 // or when the app is updated with a new icon.
3488 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003489 }
3490 }
3491
Joe Onorato9c1289c2009-08-17 11:03:03 -04003492 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003493 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003494 * or make a new one.
3495 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003496 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003497 // See if a placeholder was created for us already
3498 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003499 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003500 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003501 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003502 folders.put(id, folderInfo);
3503 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003504 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003505 }
3506
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003507 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003508 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003509 return new Comparator<AppInfo>() {
3510 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003511 if (a.user.equals(b.user)) {
3512 int result = collator.compare(a.title.toString().trim(),
3513 b.title.toString().trim());
3514 if (result == 0) {
3515 result = a.componentName.compareTo(b.componentName);
3516 }
3517 return result;
3518 } else {
3519 // TODO Need to figure out rules for sorting
3520 // profiles, this puts work second.
3521 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003522 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003523 }
Winson Chung11904872012-09-17 16:58:46 -07003524 };
3525 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003526 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3527 = new Comparator<AppInfo>() {
3528 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003529 if (a.firstInstallTime < b.firstInstallTime) return 1;
3530 if (a.firstInstallTime > b.firstInstallTime) return -1;
3531 return 0;
3532 }
3533 };
Winson Chung5308f242011-08-18 12:12:41 -07003534 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3535 if (info.activityInfo != null) {
3536 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3537 } else {
3538 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3539 }
3540 }
Kenny Guyed131872014-04-30 03:02:21 +01003541 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003542 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003543 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003544 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003545 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003546 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003547 }
Kenny Guyed131872014-04-30 03:02:21 +01003548 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003549 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003550 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003551 }
Kenny Guyed131872014-04-30 03:02:21 +01003552 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003553 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003554 ComponentName keyA = a.getComponentName();
3555 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003556 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003557 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003558 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003559 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003560
Winson Chung5308f242011-08-18 12:12:41 -07003561 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003562 }
Winson Chung5308f242011-08-18 12:12:41 -07003563 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003564 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003565 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003566 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003567
Winson Chung5308f242011-08-18 12:12:41 -07003568 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003569 }
Winson Chung11904872012-09-17 16:58:46 -07003570 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003571 }
3572 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003573 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003574 private final AppWidgetManagerCompat mManager;
3575 private final PackageManager mPackageManager;
3576 private final HashMap<Object, String> mLabelCache;
3577 private final Collator mCollator;
3578
3579 WidgetAndShortcutNameComparator(Context context) {
3580 mManager = AppWidgetManagerCompat.getInstance(context);
3581 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003582 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003583 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003584 }
3585 public final int compare(Object a, Object b) {
3586 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003587 if (mLabelCache.containsKey(a)) {
3588 labelA = mLabelCache.get(a);
3589 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003590 labelA = (a instanceof AppWidgetProviderInfo)
3591 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3592 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003593 mLabelCache.put(a, labelA);
3594 }
3595 if (mLabelCache.containsKey(b)) {
3596 labelB = mLabelCache.get(b);
3597 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003598 labelB = (b instanceof AppWidgetProviderInfo)
3599 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3600 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003601 mLabelCache.put(b, labelB);
3602 }
Winson Chung11904872012-09-17 16:58:46 -07003603 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003604 }
3605 };
Joe Onoratobe386092009-11-17 17:32:16 -08003606
Sunny Goyal651077b2014-06-30 14:15:31 -07003607 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3608 return (provider != null) && (provider.provider != null)
3609 && (provider.provider.getPackageName() != null);
3610 }
3611
Joe Onoratobe386092009-11-17 17:32:16 -08003612 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003613 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003614 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3615 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3616 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3617 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003618 if (mLoaderTask != null) {
3619 mLoaderTask.dumpState();
3620 } else {
3621 Log.d(TAG, "mLoaderTask=null");
3622 }
Joe Onoratobe386092009-11-17 17:32:16 -08003623 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003624}