blob: 5e8e2ad0e5accedbccbfd7831e987be942aa475c [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 /**
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001081 * Removes all the items from the database corresponding to the specified package.
1082 */
1083 static void deletePackageFromDatabase(Context context, final String pn,
1084 final UserHandleCompat user) {
1085 ItemInfoFilter filter = new ItemInfoFilter() {
1086 @Override
1087 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1088 return cn.getPackageName().equals(pn) && info.user.equals(user);
1089 }
1090 };
1091 ArrayList<ItemInfo> infos = filterItemInfos(sBgItemsIdMap.values(), filter);
1092 deleteItemsFromDatabase(context, infos);
1093 }
1094
1095 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001096 * Removes the specified item from the database
1097 * @param context
1098 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001100 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001101 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1102 items.add(item);
1103 deleteItemsFromDatabase(context, items);
1104 }
1105
1106 /**
1107 * Removes the specified items from the database
1108 * @param context
1109 * @param item
1110 */
1111 static void deleteItemsFromDatabase(Context context, final ArrayList<ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001112 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001113
Michael Jurka83df1882011-08-31 20:59:26 -07001114 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001115 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001116 for (ItemInfo item : items) {
1117 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1118 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001119
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001120 // Lock on mBgLock *after* the db operation
1121 synchronized (sBgLock) {
1122 switch (item.itemType) {
1123 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1124 sBgFolders.remove(item.id);
1125 for (ItemInfo info: sBgItemsIdMap.values()) {
1126 if (info.container == item.id) {
1127 // We are deleting a folder which still contains items that
1128 // think they are contained by that folder.
1129 String msg = "deleting a folder (" + item + ") which still " +
1130 "contains items (" + info + ")";
1131 Log.e(TAG, msg);
1132 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001133 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001134 sBgWorkspaceItems.remove(item);
1135 break;
1136 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1137 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1138 sBgWorkspaceItems.remove(item);
1139 break;
1140 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1141 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1142 break;
1143 }
1144 sBgItemsIdMap.remove(item.id);
1145 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001146 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001147 }
1148 }
Michael Jurka83df1882011-08-31 20:59:26 -07001149 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001150 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001151 }
1152
1153 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 * Update the order of the workspace screens in the database. The array list contains
1155 * a list of screen ids in the order that they should appear.
1156 */
Winson Chungc9168342013-06-26 14:54:55 -07001157 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001158 // Log to disk
1159 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1160 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1161
Winson Chung64359a52013-07-08 17:17:08 -07001162 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 final ContentResolver cr = context.getContentResolver();
1164 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1165
1166 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001167 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 while (iter.hasNext()) {
1169 long id = iter.next();
1170 if (id < 0) {
1171 iter.remove();
1172 }
1173 }
1174
1175 Runnable r = new Runnable() {
1176 @Override
1177 public void run() {
Yura085c8532014-02-11 15:15:29 +00001178 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001179 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001180 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001181 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001182 for (int i = 0; i < count; i++) {
1183 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001184 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001185 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1186 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001187 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001188 }
Yura085c8532014-02-11 15:15:29 +00001189
1190 try {
1191 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1192 } catch (Exception ex) {
1193 throw new RuntimeException(ex);
1194 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001195
Winson Chungba9c37f2013-08-30 14:11:37 -07001196 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001197 sBgWorkspaceScreens.clear();
1198 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001199 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001200 }
1201 };
1202 runOnWorkerThread(r);
1203 }
1204
1205 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001206 * Remove the contents of the specified folder from the database
1207 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001208 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001209 final ContentResolver cr = context.getContentResolver();
1210
Michael Jurkac9d95c52011-08-29 14:03:34 -07001211 Runnable r = new Runnable() {
1212 public void run() {
1213 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001215 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001216 sBgItemsIdMap.remove(info.id);
1217 sBgFolders.remove(info.id);
1218 sBgDbIconCache.remove(info);
1219 sBgWorkspaceItems.remove(info);
1220 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001221
Michael Jurkac9d95c52011-08-29 14:03:34 -07001222 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1223 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001224 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001225 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001226 for (ItemInfo childInfo : info.contents) {
1227 sBgItemsIdMap.remove(childInfo.id);
1228 sBgDbIconCache.remove(childInfo);
1229 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001230 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001231 }
1232 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001233 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001234 }
1235
1236 /**
1237 * Set this as the current Launcher activity object for the loader.
1238 */
1239 public void initialize(Callbacks callbacks) {
1240 synchronized (mLock) {
1241 mCallbacks = new WeakReference<Callbacks>(callbacks);
1242 }
1243 }
1244
Kenny Guyed131872014-04-30 03:02:21 +01001245 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001246 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001247 int op = PackageUpdatedTask.OP_UPDATE;
1248 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1249 user));
1250 }
1251
1252 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001253 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001254 int op = PackageUpdatedTask.OP_REMOVE;
1255 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1256 user));
1257 }
1258
1259 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001260 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001261 int op = PackageUpdatedTask.OP_ADD;
1262 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1263 user));
1264 }
1265
1266 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001267 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001268 boolean replacing) {
1269 if (!replacing) {
1270 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1271 user));
1272 if (mAppsCanBeOnRemoveableStorage) {
1273 // Only rebind if we support removable storage. It catches the
1274 // case where
1275 // apps on the external sd card need to be reloaded
1276 startLoaderFromBackground();
1277 }
1278 } else {
1279 // If we are replacing then just update the packages in the list
1280 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1281 packageNames, user));
1282 }
1283 }
1284
1285 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001286 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001287 boolean replacing) {
1288 if (!replacing) {
1289 enqueuePackageUpdated(new PackageUpdatedTask(
1290 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1291 user));
1292 }
1293
1294 }
1295
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001296 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001297 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1298 * ACTION_PACKAGE_CHANGED.
1299 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001300 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001301 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001302 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001303
Joe Onorato36115782010-06-17 13:28:48 -04001304 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001305 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001306 // If we have changed locale we need to clear out the labels in all apps/workspace.
1307 forceReload();
1308 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1309 // Check if configuration change was an mcc/mnc change which would affect app resources
1310 // and we would need to clear out the labels in all apps/workspace. Same handling as
1311 // above for ACTION_LOCALE_CHANGED
1312 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001313 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001314 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001315 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001316 forceReload();
1317 }
1318 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001319 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001320 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1321 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001322 if (mCallbacks != null) {
1323 Callbacks callbacks = mCallbacks.get();
1324 if (callbacks != null) {
1325 callbacks.bindSearchablesChanged();
1326 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001327 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001328 }
1329 }
1330
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001331 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001332 resetLoadedState(true, true);
1333
Reena Lee93f824a2011-09-23 17:20:28 -07001334 // Do this here because if the launcher activity is running it will be restarted.
1335 // If it's not running startLoaderFromBackground will merely tell it that it needs
1336 // to reload.
1337 startLoaderFromBackground();
1338 }
1339
Winson Chungf0c6ae02012-03-21 16:10:31 -07001340 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1341 synchronized (mLock) {
1342 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1343 // mWorkspaceLoaded to true later
1344 stopLoaderLocked();
1345 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1346 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1347 }
1348 }
1349
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001350 /**
1351 * When the launcher is in the background, it's possible for it to miss paired
1352 * configuration changes. So whenever we trigger the loader from the background
1353 * tell the launcher that it needs to re-run the loader when it comes back instead
1354 * of doing it now.
1355 */
1356 public void startLoaderFromBackground() {
1357 boolean runLoader = false;
1358 if (mCallbacks != null) {
1359 Callbacks callbacks = mCallbacks.get();
1360 if (callbacks != null) {
1361 // Only actually run the loader if they're not paused.
1362 if (!callbacks.setLoadOnResume()) {
1363 runLoader = true;
1364 }
1365 }
1366 }
1367 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001368 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001369 }
Joe Onorato36115782010-06-17 13:28:48 -04001370 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001371
Reena Lee93f824a2011-09-23 17:20:28 -07001372 // If there is already a loader task running, tell it to stop.
1373 // returns true if isLaunching() was true on the old task
1374 private boolean stopLoaderLocked() {
1375 boolean isLaunching = false;
1376 LoaderTask oldTask = mLoaderTask;
1377 if (oldTask != null) {
1378 if (oldTask.isLaunching()) {
1379 isLaunching = true;
1380 }
1381 oldTask.stopLocked();
1382 }
1383 return isLaunching;
1384 }
1385
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001386 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001387 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1388 }
1389
1390 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001391 synchronized (mLock) {
1392 if (DEBUG_LOADERS) {
1393 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1394 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001395
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001396 // Clear any deferred bind-runnables from the synchronized load process
1397 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001398 synchronized (mDeferredBindRunnables) {
1399 mDeferredBindRunnables.clear();
1400 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401
Joe Onorato36115782010-06-17 13:28:48 -04001402 // Don't bother to start the thread if we know it's not going to do anything
1403 if (mCallbacks != null && mCallbacks.get() != null) {
1404 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001405 // also, don't downgrade isLaunching if we're already running
1406 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001407 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001408 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1409 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001410 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1411 } else {
1412 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1413 sWorker.post(mLoaderTask);
1414 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001415 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001416 }
1417 }
1418
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001419 void bindRemainingSynchronousPages() {
1420 // Post the remaining side pages to be loaded
1421 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001422 Runnable[] deferredBindRunnables = null;
1423 synchronized (mDeferredBindRunnables) {
1424 deferredBindRunnables = mDeferredBindRunnables.toArray(
1425 new Runnable[mDeferredBindRunnables.size()]);
1426 mDeferredBindRunnables.clear();
1427 }
1428 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001429 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001430 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001431 }
1432 }
1433
Joe Onorato36115782010-06-17 13:28:48 -04001434 public void stopLoader() {
1435 synchronized (mLock) {
1436 if (mLoaderTask != null) {
1437 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001438 }
1439 }
Joe Onorato36115782010-06-17 13:28:48 -04001440 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001441
Winson Chung76828c82013-08-19 15:43:29 -07001442 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1443 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1444 final ContentResolver contentResolver = context.getContentResolver();
1445 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1446 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1447 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1448
1449 try {
1450 final int idIndex = sc.getColumnIndexOrThrow(
1451 LauncherSettings.WorkspaceScreens._ID);
1452 final int rankIndex = sc.getColumnIndexOrThrow(
1453 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1454 while (sc.moveToNext()) {
1455 try {
1456 long screenId = sc.getLong(idIndex);
1457 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001458 orderedScreens.put(rank, screenId);
1459 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001460 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001461 }
1462 }
1463 } finally {
1464 sc.close();
1465 }
Winson Chunga90303b2013-11-15 13:05:06 -08001466
1467 // Log to disk
1468 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1469 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1470 for (Integer i : orderedScreens.keySet()) {
1471 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1472 }
1473 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1474 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001475 return orderedScreens;
1476 }
1477
Michael Jurkac57b7a82011-08-09 22:02:20 -07001478 public boolean isAllAppsLoaded() {
1479 return mAllAppsLoaded;
1480 }
1481
Winson Chung36a62fe2012-05-06 18:04:42 -07001482 boolean isLoadingWorkspace() {
1483 synchronized (mLock) {
1484 if (mLoaderTask != null) {
1485 return mLoaderTask.isLoadingWorkspace();
1486 }
1487 }
1488 return false;
1489 }
1490
Joe Onorato36115782010-06-17 13:28:48 -04001491 /**
1492 * Runnable for the thread that loads the contents of the launcher:
1493 * - workspace icons
1494 * - widgets
1495 * - all apps icons
1496 */
1497 private class LoaderTask implements Runnable {
1498 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001499 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001500 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001501 private boolean mStopped;
1502 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001503 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001504
Winson Chungc3eecff2011-07-11 17:44:15 -07001505 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001506
Dan Sandlerd5024042014-01-09 15:01:33 -05001507 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001508 mContext = context;
1509 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001510 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001511 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001512 }
1513
Joe Onorato36115782010-06-17 13:28:48 -04001514 boolean isLaunching() {
1515 return mIsLaunching;
1516 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001517
Winson Chung36a62fe2012-05-06 18:04:42 -07001518 boolean isLoadingWorkspace() {
1519 return mIsLoadingAndBindingWorkspace;
1520 }
1521
Winson Chungc763c4e2013-07-19 13:49:06 -07001522 /** Returns whether this is an upgrade path */
1523 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001524 mIsLoadingAndBindingWorkspace = true;
1525
Joe Onorato36115782010-06-17 13:28:48 -04001526 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001527 if (DEBUG_LOADERS) {
1528 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001529 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001530
Winson Chungc763c4e2013-07-19 13:49:06 -07001531 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001532 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001533 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001534 synchronized (LoaderTask.this) {
1535 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001536 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001537 }
1538 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001539 }
1540 }
1541
Joe Onorato36115782010-06-17 13:28:48 -04001542 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001543 bindWorkspace(-1, isUpgradePath);
1544 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001545 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001546
Joe Onorato36115782010-06-17 13:28:48 -04001547 private void waitForIdle() {
1548 // Wait until the either we're stopped or the other threads are done.
1549 // This way we don't start loading all apps until the workspace has settled
1550 // down.
1551 synchronized (LoaderTask.this) {
1552 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001553
Joe Onorato36115782010-06-17 13:28:48 -04001554 mHandler.postIdle(new Runnable() {
1555 public void run() {
1556 synchronized (LoaderTask.this) {
1557 mLoadAndBindStepFinished = true;
1558 if (DEBUG_LOADERS) {
1559 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001560 }
Joe Onorato36115782010-06-17 13:28:48 -04001561 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001562 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001563 }
Joe Onorato36115782010-06-17 13:28:48 -04001564 });
1565
Michael Jurkac7700af2013-05-14 20:17:58 +02001566 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001567 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001568 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1569 // wait no longer than 1sec at a time
1570 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001571 } catch (InterruptedException ex) {
1572 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001573 }
1574 }
Joe Onorato36115782010-06-17 13:28:48 -04001575 if (DEBUG_LOADERS) {
1576 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001577 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001578 + "ms for previous step to finish binding");
1579 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001580 }
Joe Onorato36115782010-06-17 13:28:48 -04001581 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001582
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001584 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 // Ensure that we have a valid page index to load synchronously
1586 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1587 "valid page index");
1588 }
1589 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1590 // Ensure that we don't try and bind a specified page when the pages have not been
1591 // loaded already (we should load everything asynchronously in that case)
1592 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1593 }
1594 synchronized (mLock) {
1595 if (mIsLoaderTaskRunning) {
1596 // Ensure that we are never running the background loading at this point since
1597 // we also touch the background collections
1598 throw new RuntimeException("Error! Background loading is already running");
1599 }
1600 }
1601
1602 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1603 // data structures, we can't allow any other thread to touch that data, but because
1604 // this call is synchronous, we can get away with not locking).
1605
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001606 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001607 // operations from the previous activity. We need to ensure that all queued operations
1608 // are executed before any synchronous binding work is done.
1609 mHandler.flush();
1610
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001611 // Divide the set of loaded items into those that we are binding synchronously, and
1612 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001613 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001614 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1615 // arise from that.
1616 onlyBindAllApps();
1617 }
1618
Joe Onorato36115782010-06-17 13:28:48 -04001619 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001620 boolean isUpgrade = false;
1621
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001622 synchronized (mLock) {
1623 mIsLoaderTaskRunning = true;
1624 }
Joe Onorato36115782010-06-17 13:28:48 -04001625 // Optimize for end-user experience: if the Launcher is up and // running with the
1626 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1627 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001628 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001629 // Elevate priority when Home launches for the first time to avoid
1630 // starving at boot time. Staring at a blank home is not cool.
1631 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001632 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1633 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001634 android.os.Process.setThreadPriority(mIsLaunching
1635 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1636 }
Winson Chung64359a52013-07-08 17:17:08 -07001637 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001638 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001639
Joe Onorato36115782010-06-17 13:28:48 -04001640 if (mStopped) {
1641 break keep_running;
1642 }
1643
1644 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1645 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001646 synchronized (mLock) {
1647 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001648 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001649 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1650 }
1651 }
Joe Onorato36115782010-06-17 13:28:48 -04001652 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001653
1654 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001655 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1656 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001657
1658 // Restore the default thread priority after we are done loading items
1659 synchronized (mLock) {
1660 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661 }
Joe Onorato36115782010-06-17 13:28:48 -04001662 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001663
Winson Chungaac01e12011-08-17 10:37:13 -07001664 // Update the saved icons if necessary
1665 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001666 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001667 for (Object key : sBgDbIconCache.keySet()) {
1668 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1669 }
1670 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001671 }
Winson Chungaac01e12011-08-17 10:37:13 -07001672
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001673 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001674 // Ensure that all the applications that are in the system are
1675 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001676 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001677 verifyApplications();
1678 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001679 }
1680
Joe Onorato36115782010-06-17 13:28:48 -04001681 // Clear out this reference, otherwise we end up holding it until all of the
1682 // callback runnables are done.
1683 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001684
Joe Onorato36115782010-06-17 13:28:48 -04001685 synchronized (mLock) {
1686 // If we are still the last one to be scheduled, remove ourselves.
1687 if (mLoaderTask == this) {
1688 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001690 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001691 }
Joe Onorato36115782010-06-17 13:28:48 -04001692 }
1693
1694 public void stopLocked() {
1695 synchronized (LoaderTask.this) {
1696 mStopped = true;
1697 this.notify();
1698 }
1699 }
1700
1701 /**
1702 * Gets the callbacks object. If we've been stopped, or if the launcher object
1703 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1704 * object that was around when the deferred message was scheduled, and if there's
1705 * a new Callbacks object around then also return null. This will save us from
1706 * calling onto it with data that will be ignored.
1707 */
1708 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1709 synchronized (mLock) {
1710 if (mStopped) {
1711 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001712 }
Joe Onorato36115782010-06-17 13:28:48 -04001713
1714 if (mCallbacks == null) {
1715 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001716 }
Joe Onorato36115782010-06-17 13:28:48 -04001717
1718 final Callbacks callbacks = mCallbacks.get();
1719 if (callbacks != oldCallbacks) {
1720 return null;
1721 }
1722 if (callbacks == null) {
1723 Log.w(TAG, "no mCallbacks");
1724 return null;
1725 }
1726
1727 return callbacks;
1728 }
1729 }
1730
Winson Chungc763c4e2013-07-19 13:49:06 -07001731 private void verifyApplications() {
1732 final Context context = mApp.getContext();
1733
1734 // Cross reference all the applications in our apps list with items in the workspace
1735 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001736 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001737 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001738 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001739 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001740 if (tmpInfos.isEmpty()) {
1741 // We are missing an application icon, so add this to the workspace
1742 added.add(app);
1743 // This is a rare event, so lets log it
1744 Log.e(TAG, "Missing Application on load: " + app);
1745 }
1746 }
1747 }
1748 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001749 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001750 }
1751 }
1752
Joe Onorato36115782010-06-17 13:28:48 -04001753 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001754 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001755 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001756 LauncherAppState app = LauncherAppState.getInstance();
1757 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001758 final int countX = (int) grid.numColumns;
1759 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001760
Adam Cohendcd297f2013-06-18 13:13:40 -07001761 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001762 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001763 // Return early if we detect that an item is under the hotseat button
1764 if (mCallbacks == null ||
1765 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001766 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001767 Log.e(TAG, "Error loading shortcut into hotseat " + item
1768 + " into position (" + item.screenId + ":" + item.cellX + ","
1769 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001770 return false;
1771 }
1772
Dan Sandler295ae182013-12-10 16:05:47 -05001773 final ItemInfo[][] hotseatItems =
1774 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1775
Adam Cohenae4409d2013-11-26 10:34:59 -08001776 if (item.screenId >= grid.numHotseatIcons) {
1777 Log.e(TAG, "Error loading shortcut " + item
1778 + " into hotseat position " + item.screenId
1779 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1780 + ")");
1781 return false;
1782 }
1783
Dan Sandler295ae182013-12-10 16:05:47 -05001784 if (hotseatItems != null) {
1785 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001786 Log.e(TAG, "Error loading shortcut into hotseat " + item
1787 + " into position (" + item.screenId + ":" + item.cellX + ","
1788 + item.cellY + ") occupied by "
1789 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1790 [(int) item.screenId][0]);
1791 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001792 } else {
1793 hotseatItems[(int) item.screenId][0] = item;
1794 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001795 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001796 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001797 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001798 items[(int) item.screenId][0] = item;
1799 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001800 return true;
1801 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001802 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1803 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001804 return true;
1805 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001806
Adam Cohendcd297f2013-06-18 13:13:40 -07001807 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001808 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 occupied.put(item.screenId, items);
1810 }
1811
Dan Sandler295ae182013-12-10 16:05:47 -05001812 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001813 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1814 item.cellX < 0 || item.cellY < 0 ||
1815 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1816 Log.e(TAG, "Error loading shortcut " + item
1817 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1818 + item.cellX + "," + item.cellY
1819 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1820 return false;
1821 }
1822
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001823 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001824 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1825 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001826 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001827 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001828 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001829 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001830 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001831 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001832 return false;
1833 }
1834 }
1835 }
1836 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1837 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001838 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001839 }
1840 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001841
Joe Onorato36115782010-06-17 13:28:48 -04001842 return true;
1843 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001844
Winson Chungba9c37f2013-08-30 14:11:37 -07001845 /** Clears all the sBg data structures */
1846 private void clearSBgDataStructures() {
1847 synchronized (sBgLock) {
1848 sBgWorkspaceItems.clear();
1849 sBgAppWidgets.clear();
1850 sBgFolders.clear();
1851 sBgItemsIdMap.clear();
1852 sBgDbIconCache.clear();
1853 sBgWorkspaceScreens.clear();
1854 }
1855 }
1856
Dan Sandlerd5024042014-01-09 15:01:33 -05001857 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001858 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001859 // Log to disk
1860 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1861
Joe Onorato36115782010-06-17 13:28:48 -04001862 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001863
Joe Onorato36115782010-06-17 13:28:48 -04001864 final Context context = mContext;
1865 final ContentResolver contentResolver = context.getContentResolver();
1866 final PackageManager manager = context.getPackageManager();
1867 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1868 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001869 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1870 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001871 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001872
Winson Chung892c74d2013-08-22 16:15:50 -07001873 LauncherAppState app = LauncherAppState.getInstance();
1874 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1875 int countX = (int) grid.numColumns;
1876 int countY = (int) grid.numRows;
1877
Dan Sandlerd5024042014-01-09 15:01:33 -05001878 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1879 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1880 LauncherAppState.getLauncherProvider().deleteDatabase();
1881 }
1882
1883 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1884 // append the user's Launcher2 shortcuts
1885 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1886 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1887 } else {
1888 // Make sure the default workspace is loaded
1889 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001890 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001891 }
Adam Cohene25af792013-06-06 23:08:25 -07001892
Adam Cohen71483f42014-05-15 14:04:01 -07001893 // This code path is for our old migration code and should no longer be exercised
1894 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001895
Winson Chung9f9f00b2013-11-15 13:27:00 -08001896 // Log to disk
1897 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001898
Winson Chung2abf94d2012-07-18 18:16:38 -07001899 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001900 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001901
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001902 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001903 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001904 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001905 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001906 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001907
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001908 // +1 for the hotseat (it can be larger than the workspace)
1909 // Load workspace in reverse order to ensure that latest items are loaded first (and
1910 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001911 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001912
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001913 try {
1914 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1915 final int intentIndex = c.getColumnIndexOrThrow
1916 (LauncherSettings.Favorites.INTENT);
1917 final int titleIndex = c.getColumnIndexOrThrow
1918 (LauncherSettings.Favorites.TITLE);
1919 final int iconTypeIndex = c.getColumnIndexOrThrow(
1920 LauncherSettings.Favorites.ICON_TYPE);
1921 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1922 final int iconPackageIndex = c.getColumnIndexOrThrow(
1923 LauncherSettings.Favorites.ICON_PACKAGE);
1924 final int iconResourceIndex = c.getColumnIndexOrThrow(
1925 LauncherSettings.Favorites.ICON_RESOURCE);
1926 final int containerIndex = c.getColumnIndexOrThrow(
1927 LauncherSettings.Favorites.CONTAINER);
1928 final int itemTypeIndex = c.getColumnIndexOrThrow(
1929 LauncherSettings.Favorites.ITEM_TYPE);
1930 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1931 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001932 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1933 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001934 final int screenIndex = c.getColumnIndexOrThrow(
1935 LauncherSettings.Favorites.SCREEN);
1936 final int cellXIndex = c.getColumnIndexOrThrow
1937 (LauncherSettings.Favorites.CELLX);
1938 final int cellYIndex = c.getColumnIndexOrThrow
1939 (LauncherSettings.Favorites.CELLY);
1940 final int spanXIndex = c.getColumnIndexOrThrow
1941 (LauncherSettings.Favorites.SPANX);
1942 final int spanYIndex = c.getColumnIndexOrThrow(
1943 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001944 final int restoredIndex = c.getColumnIndexOrThrow(
1945 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001946 final int profileIdIndex = c.getColumnIndexOrThrow(
1947 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001948 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1949 //final int displayModeIndex = c.getColumnIndexOrThrow(
1950 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001951
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001952 ShortcutInfo info;
1953 String intentDescription;
1954 LauncherAppWidgetInfo appWidgetInfo;
1955 int container;
1956 long id;
1957 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001958 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001959
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001960 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001961 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001962 try {
1963 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001964 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001965 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001966
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001967 switch (itemType) {
1968 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1969 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001970 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001971 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001972 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001973 user = mUserManager.getUserForSerialNumber(serialNumber);
1974 if (user == null) {
1975 // User has been deleted remove the item.
1976 itemsToRemove.add(id);
1977 continue;
1978 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001979 try {
1980 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001981 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001982 if (cn != null && cn.getPackageName() != null) {
1983 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1984 cn.getPackageName(), user);
1985 boolean validComponent = validPkg &&
1986 launcherApps.isActivityEnabledForProfile(cn, user);
1987
1988 if (validComponent) {
1989 if (restored) {
1990 // no special handling necessary for this item
1991 restoredRows.add(id);
1992 restored = false;
1993 }
1994 } else if (validPkg) {
1995 // The app is installed but the component is no
1996 // longer available.
1997 Launcher.addDumpLog(TAG,
1998 "Invalid component removed: " + cn, true);
1999 itemsToRemove.add(id);
2000 continue;
2001 } else if (restored) {
2002 // Package is not yet available but might be
2003 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002004 Launcher.addDumpLog(TAG,
2005 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002006 } else if (isSdCardReady) {
2007 // Do not wait for external media load anymore.
2008 // Log the invalid package, and remove it
2009 Launcher.addDumpLog(TAG,
2010 "Invalid package removed: " + cn, true);
2011 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002012 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002013 } else {
2014 // SdCard is not ready yet. Package might get available,
2015 // once it is ready.
2016 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2017 + " (check again later)", true);
2018 HashSet<String> pkgs = sPendingPackages.get(user);
2019 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002020 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002021 sPendingPackages.put(user, pkgs);
2022 }
2023 pkgs.add(cn.getPackageName());
2024 allowMissingTarget = true;
2025 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002026 }
Winson Chungee055712013-07-30 14:46:24 -07002027 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002028 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002029 Launcher.addDumpLog(TAG,
2030 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002031 continue;
2032 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002033
Chris Wrenf4d08112014-01-16 18:13:56 -05002034 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002035 if (user.equals(UserHandleCompat.myUserHandle())) {
2036 Launcher.addDumpLog(TAG,
2037 "constructing info for partially restored package",
2038 true);
2039 info = getRestoredItemInfo(c, titleIndex, intent);
2040 intent = getRestoredItemIntent(c, context, intent);
2041 } else {
2042 // Don't restore items for other profiles.
2043 itemsToRemove.add(id);
2044 continue;
2045 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002046 } else if (itemType ==
2047 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002048 info = getShortcutInfo(manager, intent, user, context, c,
2049 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002050 } else {
2051 info = getShortcutInfo(c, context, iconTypeIndex,
2052 iconPackageIndex, iconResourceIndex, iconIndex,
2053 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002054
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 // App shortcuts that used to be automatically added to Launcher
2056 // didn't always have the correct intent flags set, so do that
2057 // here
2058 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002059 intent.getCategories() != null &&
2060 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002061 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002062 intent.addFlags(
2063 Intent.FLAG_ACTIVITY_NEW_TASK |
2064 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2065 }
Michael Jurka96879562012-03-22 05:54:33 -07002066 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002067
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002069 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002070 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 container = c.getInt(containerIndex);
2072 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002073 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 info.cellX = c.getInt(cellXIndex);
2075 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002076 info.spanX = 1;
2077 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002078 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002079 info.isDisabled = isSafeMode
2080 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002081
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002083 deleteOnInvalidPlacement.set(false);
2084 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2085 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002086 itemsToRemove.add(id);
2087 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 break;
2089 }
2090
2091 switch (container) {
2092 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2093 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2094 sBgWorkspaceItems.add(info);
2095 break;
2096 default:
2097 // Item is in a user folder
2098 FolderInfo folderInfo =
2099 findOrMakeFolder(sBgFolders, container);
2100 folderInfo.add(info);
2101 break;
2102 }
2103 sBgItemsIdMap.put(info.id, info);
2104
2105 // now that we've loaded everthing re-save it with the
2106 // icon in case it disappears somehow.
2107 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002108 } else {
2109 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 }
2111 break;
2112
2113 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2114 id = c.getLong(idIndex);
2115 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2116
2117 folderInfo.title = c.getString(titleIndex);
2118 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002119 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002121 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 folderInfo.cellX = c.getInt(cellXIndex);
2123 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002124 folderInfo.spanX = 1;
2125 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002126
Daniel Sandler8802e962010-05-26 16:28:16 -04002127 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002128 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002129 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002130 deleteOnInvalidPlacement)) {
2131 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002132 itemsToRemove.add(id);
2133 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002134 break;
2135 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002136
Joe Onorato9c1289c2009-08-17 11:03:03 -04002137 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002138 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2139 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2140 sBgWorkspaceItems.add(folderInfo);
2141 break;
Joe Onorato36115782010-06-17 13:28:48 -04002142 }
Joe Onorato17a89222011-02-08 17:26:11 -08002143
Chris Wrenf4d08112014-01-16 18:13:56 -05002144 if (restored) {
2145 // no special handling required for restored folders
2146 restoredRows.add(id);
2147 }
2148
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2150 sBgFolders.put(folderInfo.id, folderInfo);
2151 break;
2152
2153 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2154 // Read all Launcher-specific widget details
2155 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002156 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002157 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002158 final ComponentName component =
2159 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002160
Sunny Goyal651077b2014-06-30 14:15:31 -07002161 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002162 final boolean isIdValid = (restoreStatus &
2163 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002164
Sunny Goyalff572272014-07-23 13:58:07 -07002165 final boolean wasProviderReady = (restoreStatus &
2166 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002167
Sunny Goyalff572272014-07-23 13:58:07 -07002168 final AppWidgetProviderInfo provider = isIdValid
2169 ? widgets.getAppWidgetInfo(appWidgetId)
2170 : findAppWidgetProviderInfoWithComponent(context, component);
2171
2172 final boolean isProviderReady = isValidProvider(provider);
2173 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002174 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002175 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002176 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002177 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002178 itemsToRemove.add(id);
2179 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002180 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002181 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2182 provider.provider);
2183 int[] minSpan =
2184 Launcher.getMinSpanForWidget(context, provider);
2185 appWidgetInfo.minSpanX = minSpan[0];
2186 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002187
2188 int status = restoreStatus;
2189 if (!wasProviderReady) {
2190 // If provider was not previously ready, update the
2191 // status and UI flag.
2192
2193 // Id would be valid only if the widget restore broadcast was received.
2194 if (isIdValid) {
2195 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2196 } else {
2197 status &= ~LauncherAppWidgetInfo
2198 .FLAG_PROVIDER_NOT_READY;
2199 }
2200 }
2201 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002202 } else {
2203 Log.v(TAG, "Widget restore pending id=" + id
2204 + " appWidgetId=" + appWidgetId
2205 + " status =" + restoreStatus);
2206 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002207 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002208 appWidgetInfo.restoreStatus = restoreStatus;
2209 }
Sunny Goyalff572272014-07-23 13:58:07 -07002210
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002211 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002212 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002213 appWidgetInfo.cellX = c.getInt(cellXIndex);
2214 appWidgetInfo.cellY = c.getInt(cellYIndex);
2215 appWidgetInfo.spanX = c.getInt(spanXIndex);
2216 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002217
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218 container = c.getInt(containerIndex);
2219 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2220 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2221 Log.e(TAG, "Widget found where container != " +
2222 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2223 continue;
2224 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002225
Adam Cohene25af792013-06-06 23:08:25 -07002226 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002227 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002228 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002229 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002230 deleteOnInvalidPlacement)) {
2231 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002232 itemsToRemove.add(id);
2233 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002234 break;
2235 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002236
Sunny Goyalff572272014-07-23 13:58:07 -07002237 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002238 String providerName = provider.provider.flattenToString();
Sunny Goyalff572272014-07-23 13:58:07 -07002239 if (!providerName.equals(savedProvider) ||
2240 (appWidgetInfo.restoreStatus != restoreStatus)) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002241 ContentValues values = new ContentValues();
2242 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2243 providerName);
2244 values.put(LauncherSettings.Favorites.RESTORED,
Sunny Goyalff572272014-07-23 13:58:07 -07002245 appWidgetInfo.restoreStatus);
Sunny Goyal651077b2014-06-30 14:15:31 -07002246 String where = BaseColumns._ID + "= ?";
2247 String[] args = {Long.toString(id)};
2248 contentResolver.update(contentUri, values, where, args);
2249 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002250 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2252 sBgAppWidgets.add(appWidgetInfo);
2253 }
Joe Onorato36115782010-06-17 13:28:48 -04002254 break;
2255 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002256 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002257 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002258 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002259 }
2260 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002261 if (c != null) {
2262 c.close();
2263 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002264 }
2265
Winson Chungba9c37f2013-08-30 14:11:37 -07002266 // Break early if we've stopped loading
2267 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002268 clearSBgDataStructures();
2269 return false;
2270 }
2271
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002272 if (itemsToRemove.size() > 0) {
2273 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002274 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 // Remove dead items
2276 for (long id : itemsToRemove) {
2277 if (DEBUG_LOADERS) {
2278 Log.d(TAG, "Removed id = " + id);
2279 }
2280 // Don't notify content observers
2281 try {
2282 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2283 null, null);
2284 } catch (RemoteException e) {
2285 Log.w(TAG, "Could not remove id = " + id);
2286 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002287 }
2288 }
2289
Chris Wrenf4d08112014-01-16 18:13:56 -05002290 if (restoredRows.size() > 0) {
2291 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2292 LauncherSettings.Favorites.CONTENT_URI);
2293 // Update restored items that no longer require special handling
2294 try {
2295 StringBuilder selectionBuilder = new StringBuilder();
2296 selectionBuilder.append(LauncherSettings.Favorites._ID);
2297 selectionBuilder.append(" IN (");
2298 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2299 selectionBuilder.append(")");
2300 ContentValues values = new ContentValues();
2301 values.put(LauncherSettings.Favorites.RESTORED, 0);
2302 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2303 values, selectionBuilder.toString(), null);
2304 } catch (RemoteException e) {
2305 Log.w(TAG, "Could not update restored rows");
2306 }
2307 }
2308
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002309 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2310 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002311 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002312 null, sWorker);
2313 }
2314
Winson Chungc763c4e2013-07-19 13:49:06 -07002315 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002316 long maxScreenId = 0;
2317 // If we're importing we use the old screen order.
2318 for (ItemInfo item: sBgItemsIdMap.values()) {
2319 long screenId = item.screenId;
2320 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2321 !sBgWorkspaceScreens.contains(screenId)) {
2322 sBgWorkspaceScreens.add(screenId);
2323 if (screenId > maxScreenId) {
2324 maxScreenId = screenId;
2325 }
2326 }
2327 }
2328 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002329 // Log to disk
2330 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2331 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2332 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002333
Michael Jurka414300a2013-08-27 15:42:35 +02002334 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002335 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002336
2337 // Update the max item id after we load an old db
2338 long maxItemId = 0;
2339 // If we're importing we use the old screen order.
2340 for (ItemInfo item: sBgItemsIdMap.values()) {
2341 maxItemId = Math.max(maxItemId, item.id);
2342 }
Michael Jurka414300a2013-08-27 15:42:35 +02002343 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002344 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002345 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2346 for (Integer i : orderedScreens.keySet()) {
2347 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002348 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002349 // Log to disk
2350 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2351 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002352
2353 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002354 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 for (ItemInfo item: sBgItemsIdMap.values()) {
2356 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002357 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2358 unusedScreens.contains(screenId)) {
2359 unusedScreens.remove(screenId);
2360 }
2361 }
2362
2363 // If there are any empty screens remove them, and update.
2364 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002365 // Log to disk
2366 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2367 TextUtils.join(", ", unusedScreens), true);
2368
Winson Chung933bae62013-08-29 11:42:30 -07002369 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002370 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2371 }
2372 }
2373
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002374 if (DEBUG_LOADERS) {
2375 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2376 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002378 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002380
Daniel Sandler566da102013-06-25 23:43:45 -04002381 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002382 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002383 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002384 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002385 line += " | ";
2386 }
Winson Chung892c74d2013-08-22 16:15:50 -07002387 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002388 ItemInfo[][] screen = occupied.get(screenId);
2389 if (x < screen.length && y < screen[x].length) {
2390 line += (screen[x][y] != null) ? "#" : ".";
2391 } else {
2392 line += "!";
2393 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002394 }
Joe Onorato36115782010-06-17 13:28:48 -04002395 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002396 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002397 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002398 }
Joe Onorato36115782010-06-17 13:28:48 -04002399 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002400 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002401 }
2402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 /** Filters the set of items who are directly or indirectly (via another container) on the
2404 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002405 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002406 ArrayList<ItemInfo> allWorkspaceItems,
2407 ArrayList<ItemInfo> currentScreenItems,
2408 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002409 // Purge any null ItemInfos
2410 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2411 while (iter.hasNext()) {
2412 ItemInfo i = iter.next();
2413 if (i == null) {
2414 iter.remove();
2415 }
2416 }
2417
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002418 // Order the set of items by their containers first, this allows use to walk through the
2419 // list sequentially, build up a list of containers that are in the specified screen,
2420 // as well as all items in those containers.
2421 Set<Long> itemsOnScreen = new HashSet<Long>();
2422 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2423 @Override
2424 public int compare(ItemInfo lhs, ItemInfo rhs) {
2425 return (int) (lhs.container - rhs.container);
2426 }
2427 });
2428 for (ItemInfo info : allWorkspaceItems) {
2429 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002430 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002431 currentScreenItems.add(info);
2432 itemsOnScreen.add(info.id);
2433 } else {
2434 otherScreenItems.add(info);
2435 }
2436 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2437 currentScreenItems.add(info);
2438 itemsOnScreen.add(info.id);
2439 } else {
2440 if (itemsOnScreen.contains(info.container)) {
2441 currentScreenItems.add(info);
2442 itemsOnScreen.add(info.id);
2443 } else {
2444 otherScreenItems.add(info);
2445 }
2446 }
2447 }
2448 }
2449
2450 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002451 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 ArrayList<LauncherAppWidgetInfo> appWidgets,
2453 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2454 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002455
2456 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002457 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002458 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002459 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002460 currentScreenWidgets.add(widget);
2461 } else {
2462 otherScreenWidgets.add(widget);
2463 }
2464 }
2465 }
2466
2467 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002468 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002469 HashMap<Long, ItemInfo> itemsIdMap,
2470 HashMap<Long, FolderInfo> folders,
2471 HashMap<Long, FolderInfo> currentScreenFolders,
2472 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473
2474 for (long id : folders.keySet()) {
2475 ItemInfo info = itemsIdMap.get(id);
2476 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002477 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002478 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002479 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 currentScreenFolders.put(id, folder);
2481 } else {
2482 otherScreenFolders.put(id, folder);
2483 }
2484 }
2485 }
2486
2487 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2488 * right) */
2489 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002490 final LauncherAppState app = LauncherAppState.getInstance();
2491 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 // XXX: review this
2493 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002494 @Override
2495 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002496 int cellCountX = (int) grid.numColumns;
2497 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002498 int screenOffset = cellCountX * cellCountY;
2499 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002500 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002501 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002502 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002503 rhs.cellY * cellCountX + rhs.cellX);
2504 return (int) (lr - rr);
2505 }
2506 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002508
Adam Cohendcd297f2013-06-18 13:13:40 -07002509 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2510 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002511 final Runnable r = new Runnable() {
2512 @Override
2513 public void run() {
2514 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2515 if (callbacks != null) {
2516 callbacks.bindScreens(orderedScreens);
2517 }
2518 }
2519 };
2520 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2521 }
2522
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2524 final ArrayList<ItemInfo> workspaceItems,
2525 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2526 final HashMap<Long, FolderInfo> folders,
2527 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002528
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529 final boolean postOnMainThread = (deferredBindRunnables != null);
2530
2531 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002532 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002534 final int start = i;
2535 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536 final Runnable r = new Runnable() {
2537 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002538 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002539 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002540 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002541 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2542 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002543 }
2544 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 };
2546 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002547 synchronized (deferredBindRunnables) {
2548 deferredBindRunnables.add(r);
2549 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002550 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002551 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552 }
Joe Onorato36115782010-06-17 13:28:48 -04002553 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002554
2555 // Bind the folders
2556 if (!folders.isEmpty()) {
2557 final Runnable r = new Runnable() {
2558 public void run() {
2559 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2560 if (callbacks != null) {
2561 callbacks.bindFolders(folders);
2562 }
2563 }
2564 };
2565 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002566 synchronized (deferredBindRunnables) {
2567 deferredBindRunnables.add(r);
2568 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002570 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002571 }
2572 }
2573
2574 // Bind the widgets, one at a time
2575 N = appWidgets.size();
2576 for (int i = 0; i < N; i++) {
2577 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2578 final Runnable r = new Runnable() {
2579 public void run() {
2580 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2581 if (callbacks != null) {
2582 callbacks.bindAppWidget(widget);
2583 }
2584 }
2585 };
2586 if (postOnMainThread) {
2587 deferredBindRunnables.add(r);
2588 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002589 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002590 }
2591 }
2592 }
2593
2594 /**
2595 * Binds all loaded data to actual views on the main thread.
2596 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002597 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 final long t = SystemClock.uptimeMillis();
2599 Runnable r;
2600
2601 // Don't use these two variables in any of the callback runnables.
2602 // Otherwise we hold a reference to them.
2603 final Callbacks oldCallbacks = mCallbacks.get();
2604 if (oldCallbacks == null) {
2605 // This launcher has exited and nobody bothered to tell us. Just bail.
2606 Log.w(TAG, "LoaderTask running with no launcher");
2607 return;
2608 }
2609
Winson Chung9b9fb962013-11-15 15:39:34 -08002610 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2612 ArrayList<LauncherAppWidgetInfo> appWidgets =
2613 new ArrayList<LauncherAppWidgetInfo>();
2614 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2615 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002616 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002617 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002618 workspaceItems.addAll(sBgWorkspaceItems);
2619 appWidgets.addAll(sBgAppWidgets);
2620 folders.putAll(sBgFolders);
2621 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002622 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002623 }
2624
Derek Prothro7aff3992013-12-10 14:00:37 -05002625 final boolean isLoadingSynchronously =
2626 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002627 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002628 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002629 if (currScreen >= orderedScreenIds.size()) {
2630 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002631 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002632 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002633 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002634 final long currentScreenId = currentScreen < 0
2635 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002636
2637 // Load all the items that are on the current page first (and in the process, unbind
2638 // all the existing workspace items before we call startBinding() below.
2639 unbindWorkspaceItemsOnMainThread();
2640
2641 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002642 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2643 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2644 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2645 new ArrayList<LauncherAppWidgetInfo>();
2646 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2647 new ArrayList<LauncherAppWidgetInfo>();
2648 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2649 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2650
Winson Chung9b9fb962013-11-15 15:39:34 -08002651 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002653 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002654 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002655 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002656 otherFolders);
2657 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2658 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2659
2660 // Tell the workspace that we're about to start binding items
2661 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002662 public void run() {
2663 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2664 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002665 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002666 }
2667 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668 };
Winson Chung81b52252012-08-27 15:34:29 -07002669 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002670
Adam Cohendcd297f2013-06-18 13:13:40 -07002671 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2672
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002673 // Load items on the current page
2674 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2675 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002676 if (isLoadingSynchronously) {
2677 r = new Runnable() {
2678 public void run() {
2679 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002680 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002681 callbacks.onPageBoundSynchronously(currentScreen);
2682 }
2683 }
2684 };
Winson Chung81b52252012-08-27 15:34:29 -07002685 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002686 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002687
Winson Chung4a2afa32012-07-19 14:53:05 -07002688 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2689 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002690 synchronized (mDeferredBindRunnables) {
2691 mDeferredBindRunnables.clear();
2692 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002693 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002694 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002695
2696 // Tell the workspace that we're done binding items
2697 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002698 public void run() {
2699 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2700 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002701 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002702 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002703
Winson Chung98e030b2012-05-07 16:01:11 -07002704 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002705 if (DEBUG_LOADERS) {
2706 Log.d(TAG, "bound workspace in "
2707 + (SystemClock.uptimeMillis()-t) + "ms");
2708 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002709
2710 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002711 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002712 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002713 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002714 synchronized (mDeferredBindRunnables) {
2715 mDeferredBindRunnables.add(r);
2716 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002717 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002718 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002719 }
Joe Onorato36115782010-06-17 13:28:48 -04002720 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002721
Joe Onorato36115782010-06-17 13:28:48 -04002722 private void loadAndBindAllApps() {
2723 if (DEBUG_LOADERS) {
2724 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2725 }
2726 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002727 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002728 synchronized (LoaderTask.this) {
2729 if (mStopped) {
2730 return;
2731 }
2732 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002733 }
Joe Onorato36115782010-06-17 13:28:48 -04002734 } else {
2735 onlyBindAllApps();
2736 }
2737 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002738
Joe Onorato36115782010-06-17 13:28:48 -04002739 private void onlyBindAllApps() {
2740 final Callbacks oldCallbacks = mCallbacks.get();
2741 if (oldCallbacks == null) {
2742 // This launcher has exited and nobody bothered to tell us. Just bail.
2743 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2744 return;
2745 }
2746
2747 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002748 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002749 final ArrayList<AppInfo> list
2750 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002751 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002752 public void run() {
2753 final long t = SystemClock.uptimeMillis();
2754 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2755 if (callbacks != null) {
2756 callbacks.bindAllApplications(list);
2757 }
2758 if (DEBUG_LOADERS) {
2759 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2760 + (SystemClock.uptimeMillis()-t) + "ms");
2761 }
2762 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002763 };
2764 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002765 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002766 r.run();
2767 } else {
2768 mHandler.post(r);
2769 }
Joe Onorato36115782010-06-17 13:28:48 -04002770 }
2771
Winson Chung64359a52013-07-08 17:17:08 -07002772 private void loadAllApps() {
2773 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002774
Joe Onorato36115782010-06-17 13:28:48 -04002775 final Callbacks oldCallbacks = mCallbacks.get();
2776 if (oldCallbacks == null) {
2777 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002778 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002779 return;
2780 }
2781
2782 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2783 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2784
Kenny Guyed131872014-04-30 03:02:21 +01002785 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2786
Winson Chung64359a52013-07-08 17:17:08 -07002787 // Clear the list of apps
2788 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002789 for (UserHandleCompat user : profiles) {
2790 // Query for the set of apps
2791 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2792 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2793 if (DEBUG_LOADERS) {
2794 Log.d(TAG, "getActivityList took "
2795 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2796 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2797 }
2798 // Fail if we don't have any apps
2799 if (apps == null || apps.isEmpty()) {
2800 return;
2801 }
2802 // Sort the applications by name
2803 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2804 Collections.sort(apps,
2805 new LauncherModel.ShortcutNameComparator(mLabelCache));
2806 if (DEBUG_LOADERS) {
2807 Log.d(TAG, "sort took "
2808 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2809 }
Joe Onorato36115782010-06-17 13:28:48 -04002810
Kenny Guyed131872014-04-30 03:02:21 +01002811 // Create the ApplicationInfos
2812 for (int i = 0; i < apps.size(); i++) {
2813 LauncherActivityInfoCompat app = apps.get(i);
2814 // This builds the icon bitmaps.
2815 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2816 }
Winson Chung64359a52013-07-08 17:17:08 -07002817 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002818 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002819 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2820 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002821
2822 // Post callback on main thread
2823 mHandler.post(new Runnable() {
2824 public void run() {
2825 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002826 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002827 if (callbacks != null) {
2828 callbacks.bindAllApplications(added);
2829 if (DEBUG_LOADERS) {
2830 Log.d(TAG, "bound " + added.size() + " apps in "
2831 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2832 }
2833 } else {
2834 Log.i(TAG, "not binding apps: no Launcher activity");
2835 }
2836 }
2837 });
2838
Joe Onorato36115782010-06-17 13:28:48 -04002839 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002840 Log.d(TAG, "Icons processed in "
2841 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002842 }
2843 }
2844
2845 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002846 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002847 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2848 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2849 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2850 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2851 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2852 }
Joe Onorato36115782010-06-17 13:28:48 -04002853 }
2854 }
2855
2856 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002857 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002858 }
2859
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002860 private class AppsAvailabilityCheck extends BroadcastReceiver {
2861
2862 @Override
2863 public void onReceive(Context context, Intent intent) {
2864 synchronized (sBgLock) {
2865 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2866 .getInstance(mApp.getContext());
2867 ArrayList<String> packagesRemoved;
2868 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2869 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002870 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002871 for (String pkg : entry.getValue()) {
2872 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2873 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2874 packagesRemoved.add(pkg);
2875 }
2876 }
2877 if (!packagesRemoved.isEmpty()) {
2878 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2879 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2880 }
2881 }
2882 sPendingPackages.clear();
2883 }
2884 }
2885 }
2886
Joe Onorato36115782010-06-17 13:28:48 -04002887 private class PackageUpdatedTask implements Runnable {
2888 int mOp;
2889 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002890 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002891
2892 public static final int OP_NONE = 0;
2893 public static final int OP_ADD = 1;
2894 public static final int OP_UPDATE = 2;
2895 public static final int OP_REMOVE = 3; // uninstlled
2896 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2897
2898
Kenny Guyed131872014-04-30 03:02:21 +01002899 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002900 mOp = op;
2901 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002902 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002903 }
2904
2905 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002906 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002907
2908 final String[] packages = mPackages;
2909 final int N = packages.length;
2910 switch (mOp) {
2911 case OP_ADD:
2912 for (int i=0; i<N; i++) {
2913 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002914 mIconCache.remove(packages[i], mUser);
2915 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002916 }
2917 break;
2918 case OP_UPDATE:
2919 for (int i=0; i<N; i++) {
2920 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002921 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002922 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002923 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002924 }
2925 break;
2926 case OP_REMOVE:
2927 case OP_UNAVAILABLE:
2928 for (int i=0; i<N; i++) {
2929 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002930 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002931 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002932 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002933 }
2934 break;
2935 }
2936
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002937 ArrayList<AppInfo> added = null;
2938 ArrayList<AppInfo> modified = null;
2939 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002940
Adam Cohen487f7dd2012-06-28 18:12:10 -07002941 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002942 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002943 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002944 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002945 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002946 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002947 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002948 }
Winson Chung5d55f332012-07-16 20:45:03 -07002949 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002950 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002951 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002952 }
2953
Joe Onorato36115782010-06-17 13:28:48 -04002954 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2955 if (callbacks == null) {
2956 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2957 return;
2958 }
2959
2960 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002961 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002962 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002963 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002964 addAndBindAddedWorkspaceApps(context, addedInfos);
2965 } else {
2966 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002967 }
Joe Onorato36115782010-06-17 13:28:48 -04002968 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002969
Joe Onorato36115782010-06-17 13:28:48 -04002970 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002971 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002972
2973 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002974 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002975 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002976 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002977 for (ItemInfo i : infos) {
2978 if (isShortcutInfoUpdateable(i)) {
2979 ShortcutInfo info = (ShortcutInfo) i;
2980 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002981 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002982 updateItemInDatabase(context, info);
2983 }
2984 }
2985 }
2986
Joe Onorato36115782010-06-17 13:28:48 -04002987 mHandler.post(new Runnable() {
2988 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002989 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2990 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002991 callbacks.bindAppsUpdated(modifiedFinal);
2992 }
2993 }
2994 });
2995 }
Winson Chung83892cc2013-05-01 16:53:33 -07002996
Winson Chungdf95eb12013-10-16 14:57:07 -07002997 final ArrayList<String> removedPackageNames =
2998 new ArrayList<String>();
2999 if (mOp == OP_REMOVE) {
3000 // Mark all packages in the broadcast to be removed
3001 removedPackageNames.addAll(Arrays.asList(packages));
3002 } else if (mOp == OP_UPDATE) {
3003 // Mark disabled packages in the broadcast to be removed
3004 final PackageManager pm = context.getPackageManager();
3005 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003006 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003007 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003008 }
3009 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003010 }
3011 // Remove all the components associated with this package
3012 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003013 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003014 }
3015 // Remove all the specific components
3016 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003017 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003018 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003019 }
3020 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3021 // Remove any queued items from the install queue
3022 String spKey = LauncherAppState.getSharedPreferencesKey();
3023 SharedPreferences sp =
3024 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3025 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3026 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003027 mHandler.post(new Runnable() {
3028 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003029 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3030 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003031 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003032 }
3033 }
3034 });
Joe Onoratobe386092009-11-17 17:32:16 -08003035 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003036
Michael Jurkac402cd92013-05-20 15:49:32 +02003037 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003038 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003039 mHandler.post(new Runnable() {
3040 @Override
3041 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003042 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3043 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003044 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003045 }
3046 }
3047 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003048
3049 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003050 mHandler.post(new Runnable() {
3051 public void run() {
3052 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3053 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003054 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003055 }
3056 }
3057 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003058 }
3059 }
3060
Michael Jurkac402cd92013-05-20 15:49:32 +02003061 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3062 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3063 PackageManager packageManager = context.getPackageManager();
3064 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003065 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3066
Michael Jurkac402cd92013-05-20 15:49:32 +02003067 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3068 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003069 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003070 return widgetsAndShortcuts;
3071 }
3072
Kenny Guyed131872014-04-30 03:02:21 +01003073 private static boolean isPackageDisabled(Context context, String packageName,
3074 UserHandleCompat user) {
3075 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3076 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003077 }
Adam Cohen556f6132014-01-15 15:18:08 -08003078
Kenny Guyed131872014-04-30 03:02:21 +01003079 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3080 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003081 if (cn == null) {
3082 return false;
3083 }
Kenny Guyed131872014-04-30 03:02:21 +01003084 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3085 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003086 return false;
3087 }
Kenny Guyed131872014-04-30 03:02:21 +01003088 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003089 }
3090
Adam Cohena28b78e2014-05-20 17:03:04 -07003091 public static boolean isValidPackage(Context context, String packageName,
3092 UserHandleCompat user) {
3093 if (packageName == null) {
3094 return false;
3095 }
3096 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3097 return launcherApps.isPackageEnabledForProfile(packageName, user);
3098 }
3099
Joe Onorato9c1289c2009-08-17 11:03:03 -04003100 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003101 * Make an ShortcutInfo object for a restored application or shortcut item that points
3102 * to a package that is not yet installed on the system.
3103 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003104 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003105 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003106 if (cursor != null) {
3107 info.title = cursor.getString(titleIndex);
3108 } else {
3109 info.title = "";
3110 }
Kenny Guyed131872014-04-30 03:02:21 +01003111 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003112 info.contentDescription = mUserManager.getBadgedLabelForUser(
3113 info.title.toString(), info.user);
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003114 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user, false));
Chris Wrenf4d08112014-01-16 18:13:56 -05003115 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003116 info.restoredIntent = intent;
Sunny Goyal34846382014-07-09 00:09:28 -07003117 info.wasPromise = true;
Chris Wren40c5ed32014-06-24 18:24:23 -04003118 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003119 return info;
3120 }
3121
3122 /**
3123 * Make an Intent object for a restored application or shortcut item that points
3124 * to the market page for the item.
3125 */
3126 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3127 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003128 return getMarketIntent(componentName.getPackageName());
3129 }
3130
3131 static Intent getMarketIntent(String packageName) {
3132 return new Intent(Intent.ACTION_VIEW)
3133 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003134 .scheme("market")
3135 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003136 .appendQueryParameter("id", packageName)
3137 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003138 }
3139
3140 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003141 * This is called from the code that adds shortcuts from the intent receiver. This
3142 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003143 */
Kenny Guyed131872014-04-30 03:02:21 +01003144 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3145 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003146 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003147 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003148
Joe Onorato56d82912010-03-07 14:32:10 -05003149 /**
3150 * Make an ShortcutInfo object for a shortcut that is an application.
3151 *
3152 * If c is not null, then it will be used to fill in missing data like the title and icon.
3153 */
Kenny Guyed131872014-04-30 03:02:21 +01003154 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3155 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003156 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003157 if (user == null) {
3158 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003159 return null;
3160 }
3161
Kenny Guyed131872014-04-30 03:02:21 +01003162 ComponentName componentName = intent.getComponent();
3163 if (componentName == null) {
3164 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3165 return null;
3166 }
3167
3168 Intent newIntent = new Intent(intent.getAction(), null);
3169 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3170 newIntent.setComponent(componentName);
3171 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003172 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003173 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3174 return null;
3175 }
3176
3177 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003178
Joe Onorato56d82912010-03-07 14:32:10 -05003179 // the resource -- This may implicitly give us back the fallback icon,
3180 // but don't worry about that. All we're doing with usingFallbackIcon is
3181 // to avoid saving lots of copies of that in the database, and most apps
3182 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003183 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003184
Joe Onorato56d82912010-03-07 14:32:10 -05003185 // the db
3186 if (icon == null) {
3187 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003188 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003189 }
3190 }
3191 // the fallback icon
3192 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003193 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003194 info.usingFallbackIcon = true;
3195 }
3196 info.setIcon(icon);
3197
Kenny Guyed131872014-04-30 03:02:21 +01003198 // From the cache.
3199 if (labelCache != null) {
3200 info.title = labelCache.get(componentName);
3201 }
3202
Joe Onorato56d82912010-03-07 14:32:10 -05003203 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003204 if (info.title == null && lai != null) {
3205 info.title = lai.getLabel();
3206 if (labelCache != null) {
3207 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003208 }
Joe Onorato56d82912010-03-07 14:32:10 -05003209 }
3210 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003211 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003212 if (c != null) {
3213 info.title = c.getString(titleIndex);
3214 }
3215 }
3216 // fall back to the class name of the activity
3217 if (info.title == null) {
3218 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003219 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003220 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003221 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003222 info.contentDescription = mUserManager.getBadgedLabelForUser(
3223 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003224 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003225 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003226
Winson Chung64359a52013-07-08 17:17:08 -07003227 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3228 ItemInfoFilter f) {
3229 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3230 for (ItemInfo i : infos) {
3231 if (i instanceof ShortcutInfo) {
3232 ShortcutInfo info = (ShortcutInfo) i;
3233 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003234 if (info.restoredIntent != null) {
3235 cn = info.restoredIntent.getComponent();
3236 }
Winson Chung64359a52013-07-08 17:17:08 -07003237 if (cn != null && f.filterItem(null, info, cn)) {
3238 filtered.add(info);
3239 }
3240 } else if (i instanceof FolderInfo) {
3241 FolderInfo info = (FolderInfo) i;
3242 for (ShortcutInfo s : info.contents) {
3243 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003244 if (s.restoredIntent != null) {
3245 cn = s.restoredIntent.getComponent();
3246 }
Winson Chung64359a52013-07-08 17:17:08 -07003247 if (cn != null && f.filterItem(info, s, cn)) {
3248 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003249 }
3250 }
Winson Chung64359a52013-07-08 17:17:08 -07003251 } else if (i instanceof LauncherAppWidgetInfo) {
3252 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3253 ComponentName cn = info.providerName;
3254 if (cn != null && f.filterItem(null, info, cn)) {
3255 filtered.add(info);
3256 }
Winson Chung8a435102012-08-30 17:16:53 -07003257 }
3258 }
Winson Chung64359a52013-07-08 17:17:08 -07003259 return new ArrayList<ItemInfo>(filtered);
3260 }
3261
Kenny Guyed131872014-04-30 03:02:21 +01003262 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3263 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003264 ItemInfoFilter filter = new ItemInfoFilter() {
3265 @Override
3266 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003267 if (info.user == null) {
3268 return cn.equals(cname);
3269 } else {
3270 return cn.equals(cname) && info.user.equals(user);
3271 }
Winson Chung64359a52013-07-08 17:17:08 -07003272 }
3273 };
3274 return filterItemInfos(sBgItemsIdMap.values(), filter);
3275 }
3276
3277 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3278 if (i instanceof ShortcutInfo) {
3279 ShortcutInfo info = (ShortcutInfo) i;
3280 // We need to check for ACTION_MAIN otherwise getComponent() might
3281 // return null for some shortcuts (for instance, for shortcuts to
3282 // web pages.)
3283 Intent intent = info.intent;
3284 ComponentName name = intent.getComponent();
3285 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3286 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3287 return true;
3288 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003289 // placeholder shortcuts get special treatment, let them through too.
3290 if (info.getRestoredIntent() != null) {
3291 return true;
3292 }
Winson Chung64359a52013-07-08 17:17:08 -07003293 }
3294 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003295 }
3296
3297 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003298 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003299 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003300 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003301 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3302 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003303
Joe Onorato56d82912010-03-07 14:32:10 -05003304 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003305 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003306 // Non-app shortcuts are only supported for current user.
3307 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003308 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003309
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003310 // TODO: If there's an explicit component and we can't install that, delete it.
3311
Joe Onorato56d82912010-03-07 14:32:10 -05003312 info.title = c.getString(titleIndex);
3313
Joe Onorato9c1289c2009-08-17 11:03:03 -04003314 int iconType = c.getInt(iconTypeIndex);
3315 switch (iconType) {
3316 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3317 String packageName = c.getString(iconPackageIndex);
3318 String resourceName = c.getString(iconResourceIndex);
3319 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003320 info.customIcon = false;
3321 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003322 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003323 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003324 if (resources != null) {
3325 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003326 icon = Utilities.createIconBitmap(
3327 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003328 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003329 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003330 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003331 }
Joe Onorato56d82912010-03-07 14:32:10 -05003332 // the db
3333 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003334 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003335 }
3336 // the fallback icon
3337 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003338 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003339 info.usingFallbackIcon = true;
3340 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003341 break;
3342 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003343 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003344 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003345 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003346 info.customIcon = false;
3347 info.usingFallbackIcon = true;
3348 } else {
3349 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003350 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003351 break;
3352 default:
Kenny Guyed131872014-04-30 03:02:21 +01003353 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003354 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003355 info.customIcon = false;
3356 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003357 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003358 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003359 return info;
3360 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003361
Michael Jurka931dc972011-08-05 15:08:15 -07003362 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003363 @SuppressWarnings("all") // suppress dead code warning
3364 final boolean debug = false;
3365 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003366 Log.d(TAG, "getIconFromCursor app="
3367 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3368 }
3369 byte[] data = c.getBlob(iconIndex);
3370 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003371 return Utilities.createIconBitmap(
3372 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003373 } catch (Exception e) {
3374 return null;
3375 }
3376 }
3377
Winson Chung3d503fb2011-07-13 17:25:49 -07003378 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3379 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003380 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003381 if (info == null) {
3382 return null;
3383 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003384 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003385
3386 return info;
3387 }
3388
Winson Chunga9abd0e2010-10-27 17:18:37 -07003389 /**
Winson Chung55cef262010-10-28 14:14:18 -07003390 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3391 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003392 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003393 ComponentName component) {
3394 List<AppWidgetProviderInfo> widgets =
3395 AppWidgetManager.getInstance(context).getInstalledProviders();
3396 for (AppWidgetProviderInfo info : widgets) {
3397 if (info.provider.equals(component)) {
3398 return info;
3399 }
3400 }
3401 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003402 }
3403
3404 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003405 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3406 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3407 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3408
Adam Cohend9198822011-11-22 16:42:47 -08003409 if (intent == null) {
3410 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3411 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3412 return null;
3413 }
3414
Joe Onorato0589f0f2010-02-08 13:44:00 -08003415 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003416 boolean customIcon = false;
3417 ShortcutIconResource iconResource = null;
3418
3419 if (bitmap != null && bitmap instanceof Bitmap) {
3420 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003421 customIcon = true;
3422 } else {
3423 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3424 if (extra != null && extra instanceof ShortcutIconResource) {
3425 try {
3426 iconResource = (ShortcutIconResource) extra;
3427 final PackageManager packageManager = context.getPackageManager();
3428 Resources resources = packageManager.getResourcesForApplication(
3429 iconResource.packageName);
3430 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003431 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003432 mIconCache.getFullResIcon(resources, id),
3433 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003434 } catch (Exception e) {
3435 Log.w(TAG, "Could not load shortcut icon: " + extra);
3436 }
3437 }
3438 }
3439
Michael Jurkac9d95c52011-08-29 14:03:34 -07003440 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003441
Kenny Guyed131872014-04-30 03:02:21 +01003442 // Only support intents for current user for now. Intents sent from other
3443 // users wouldn't get here without intent forwarding anyway.
3444 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003445 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003446 if (fallbackIcon != null) {
3447 icon = fallbackIcon;
3448 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003449 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003450 info.usingFallbackIcon = true;
3451 }
Joe Onorato56d82912010-03-07 14:32:10 -05003452 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003453 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003454
Joe Onorato0589f0f2010-02-08 13:44:00 -08003455 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003456 info.contentDescription = mUserManager.getBadgedLabelForUser(
3457 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003458 info.intent = intent;
3459 info.customIcon = customIcon;
3460 info.iconResource = iconResource;
3461
3462 return info;
3463 }
3464
Winson Chungaac01e12011-08-17 10:37:13 -07003465 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3466 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003467 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003468 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003469 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003470 }
Joe Onorato56d82912010-03-07 14:32:10 -05003471 // If this icon doesn't have a custom icon, check to see
3472 // what's stored in the DB, and if it doesn't match what
3473 // we're going to show, store what we are going to show back
3474 // into the DB. We do this so when we're loading, if the
3475 // package manager can't find an icon (for example because
3476 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003477 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003478 cache.put(info, c.getBlob(iconIndex));
3479 return true;
3480 }
3481 return false;
3482 }
3483 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3484 boolean needSave = false;
3485 try {
3486 if (data != null) {
3487 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3488 Bitmap loaded = info.getIcon(mIconCache);
3489 needSave = !saved.sameAs(loaded);
3490 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003491 needSave = true;
3492 }
Winson Chungaac01e12011-08-17 10:37:13 -07003493 } catch (Exception e) {
3494 needSave = true;
3495 }
3496 if (needSave) {
3497 Log.d(TAG, "going to save icon bitmap for info=" + info);
3498 // This is slower than is ideal, but this only happens once
3499 // or when the app is updated with a new icon.
3500 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003501 }
3502 }
3503
Joe Onorato9c1289c2009-08-17 11:03:03 -04003504 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003505 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003506 * or make a new one.
3507 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003508 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003509 // See if a placeholder was created for us already
3510 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003511 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003512 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003513 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003514 folders.put(id, folderInfo);
3515 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003516 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003517 }
3518
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003519 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003520 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003521 return new Comparator<AppInfo>() {
3522 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003523 if (a.user.equals(b.user)) {
3524 int result = collator.compare(a.title.toString().trim(),
3525 b.title.toString().trim());
3526 if (result == 0) {
3527 result = a.componentName.compareTo(b.componentName);
3528 }
3529 return result;
3530 } else {
3531 // TODO Need to figure out rules for sorting
3532 // profiles, this puts work second.
3533 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003534 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003535 }
Winson Chung11904872012-09-17 16:58:46 -07003536 };
3537 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003538 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3539 = new Comparator<AppInfo>() {
3540 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003541 if (a.firstInstallTime < b.firstInstallTime) return 1;
3542 if (a.firstInstallTime > b.firstInstallTime) return -1;
3543 return 0;
3544 }
3545 };
Winson Chung5308f242011-08-18 12:12:41 -07003546 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3547 if (info.activityInfo != null) {
3548 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3549 } else {
3550 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3551 }
3552 }
Kenny Guyed131872014-04-30 03:02:21 +01003553 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003554 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003555 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003556 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003557 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003558 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003559 }
Kenny Guyed131872014-04-30 03:02:21 +01003560 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003561 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003562 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003563 }
Kenny Guyed131872014-04-30 03:02:21 +01003564 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003565 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003566 ComponentName keyA = a.getComponentName();
3567 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003568 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003569 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003570 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003571 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003572
Winson Chung5308f242011-08-18 12:12:41 -07003573 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003574 }
Winson Chung5308f242011-08-18 12:12:41 -07003575 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003576 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003577 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003578 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003579
Winson Chung5308f242011-08-18 12:12:41 -07003580 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003581 }
Winson Chung11904872012-09-17 16:58:46 -07003582 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003583 }
3584 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003585 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003586 private final AppWidgetManagerCompat mManager;
3587 private final PackageManager mPackageManager;
3588 private final HashMap<Object, String> mLabelCache;
3589 private final Collator mCollator;
3590
3591 WidgetAndShortcutNameComparator(Context context) {
3592 mManager = AppWidgetManagerCompat.getInstance(context);
3593 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003594 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003595 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003596 }
3597 public final int compare(Object a, Object b) {
3598 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003599 if (mLabelCache.containsKey(a)) {
3600 labelA = mLabelCache.get(a);
3601 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003602 labelA = (a instanceof AppWidgetProviderInfo)
3603 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3604 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003605 mLabelCache.put(a, labelA);
3606 }
3607 if (mLabelCache.containsKey(b)) {
3608 labelB = mLabelCache.get(b);
3609 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003610 labelB = (b instanceof AppWidgetProviderInfo)
3611 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3612 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003613 mLabelCache.put(b, labelB);
3614 }
Winson Chung11904872012-09-17 16:58:46 -07003615 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003616 }
3617 };
Joe Onoratobe386092009-11-17 17:32:16 -08003618
Sunny Goyal651077b2014-06-30 14:15:31 -07003619 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3620 return (provider != null) && (provider.provider != null)
3621 && (provider.provider.getPackageName() != null);
3622 }
3623
Joe Onoratobe386092009-11-17 17:32:16 -08003624 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003625 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003626 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3627 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3628 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3629 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003630 if (mLoaderTask != null) {
3631 mLoaderTask.dumpState();
3632 } else {
3633 Log.d(TAG, "mLoaderTask=null");
3634 }
Joe Onoratobe386092009-11-17 17:32:16 -08003635 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003636}