blob: 4c9d1a700d54ccf1dc99aa94ce865d2c995df7e9 [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.ActivityInfo;
34import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040035import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070037import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.content.res.Resources;
39import android.database.Cursor;
40import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
42import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080043import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040044import android.os.Handler;
45import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080046import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080047import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070048import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040049import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040050import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080051import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070052import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070053import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010054
Sunny Goyalf599ccf2014-07-08 13:01:29 -070055import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.LauncherActivityInfoCompat;
57import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
64import java.text.Collator;
65import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070066import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070067import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070068import java.util.Collections;
69import java.util.Comparator;
70import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070071import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070072import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070073import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070074import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070075import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070076import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070077import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079/**
80 * Maintains in-memory state of the Launcher. It is expected that there should be only one
81 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070082 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 */
Kenny Guyed131872014-04-30 03:02:21 +010084public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010085 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080086 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040087 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
88
Joe Onorato9c1289c2009-08-17 11:03:03 -040089 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070090
Daniel Sandler8707e0f2013-08-15 15:54:18 -070091 // true = use a "More Apps" folder for non-workspace apps on upgrade
92 // false = strew non-workspace apps across the workspace on upgrade
93 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050094 public static final int LOADER_FLAG_NONE = 0;
95 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
96 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
97
Joe Onorato36115782010-06-17 13:28:48 -040098 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050099 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800100
Winson Chungee055712013-07-30 14:46:24 -0700101 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800102 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400103
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400104 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400105 private final Object mLock = new Object();
106 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400107 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700108 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200109 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
Winson Chung81b52252012-08-27 15:34:29 -0700111 // Specific runnable types that are run on the main thread deferred handler, this allows us to
112 // clear all queued binding runnables when the Launcher activity is destroyed.
113 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
114 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
115
Jason Monkbbe1e242014-05-16 17:37:34 -0400116 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700117
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700118 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
119 static {
120 sWorkerThread.start();
121 }
122 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
123
Joe Onoratocc67f472010-06-08 10:54:30 -0700124 // We start off with everything not loaded. After that, we assume that
125 // our monitoring of the package manager provides all updates and we never
126 // need to do a requery. These are only ever touched from the loader thread.
127 private boolean mWorkspaceLoaded;
128 private boolean mAllAppsLoaded;
129
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700130 // When we are loading pages synchronously, we can't just post the binding of items on the side
131 // pages as this delays the rotation process. Instead, we wait for a callback from the first
132 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
133 // a normal load, we also clear this set of Runnables.
134 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
135
Joe Onorato9c1289c2009-08-17 11:03:03 -0400136 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700139 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700141 // The lock that must be acquired before referencing any static bg data structures. Unlike
142 // other locks, this one can generally be held long-term because we never expect any of these
143 // static data structures to be referenced outside of the worker thread except on the first
144 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700145 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700146
Adam Cohen487f7dd2012-06-28 18:12:10 -0700147 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
152 // created by LauncherModel that are directly on the home screen (however, no widgets or
153 // shortcuts within folders).
154 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155
Adam Cohen487f7dd2012-06-28 18:12:10 -0700156 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
157 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 new ArrayList<LauncherAppWidgetInfo>();
159
Adam Cohen487f7dd2012-06-28 18:12:10 -0700160 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
161 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700162
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
164 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700165
166 // sBgWorkspaceScreens is the ordered set of workspace screens.
167 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
168
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700169 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700170 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
171 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700172
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 // </ only access in worker thread >
174
175 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
Reena Lee99a73f32011-10-24 17:27:37 -0700177 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700178
Kenny Guyed131872014-04-30 03:02:21 +0100179 private final LauncherAppsCompat mLauncherApps;
180 private final UserManagerCompat mUserManager;
181
Joe Onorato9c1289c2009-08-17 11:03:03 -0400182 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700183 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public int getCurrentWorkspaceScreen();
185 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700186 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
187 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700188 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700189 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500190 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700191 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400192 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200193 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700194 public void bindAppsAdded(ArrayList<Long> newScreens,
195 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700196 ArrayList<ItemInfo> addAnimated,
197 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200198 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyale755d462014-07-22 13:48:29 -0700199 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Winson Chung83892cc2013-05-01 16:53:33 -0700200 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100201 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200202 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100203 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700204 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700205 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700206 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400207 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208
Winson Chung64359a52013-07-08 17:17:08 -0700209 public interface ItemInfoFilter {
210 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
211 }
212
Bjorn Bringert1307f632013-10-03 22:31:03 +0100213 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800214 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400215
Winson Chungee055712013-07-30 14:46:24 -0700216 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700217 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400218 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
219 // resource string.
220 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
221 ProviderInfo providerInfo =
222 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
223 ProviderInfo redirectProvider =
224 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700225
226 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400227 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700228
229 if (mOldContentProviderExists) {
230 Log.d(TAG, "Old launcher provider exists.");
231 } else {
232 Log.d(TAG, "Old launcher provider does not exist.");
233 }
234
Daniel Sandlere4f98912013-06-25 15:13:26 -0400235 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100236 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800237 mIconCache = iconCache;
238
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400239 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700240 Configuration config = res.getConfiguration();
241 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100242 mLauncherApps = LauncherAppsCompat.getInstance(context);
243 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800244 }
245
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700246 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
247 * posted on the main thread handler. */
248 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700249 runOnMainThread(r, 0);
250 }
251 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700252 if (sWorkerThread.getThreadId() == Process.myTid()) {
253 // If we are on the worker thread, post onto the main handler
254 mHandler.post(r);
255 } else {
256 r.run();
257 }
258 }
259
260 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
261 * posted on the worker thread handler. */
262 private static void runOnWorkerThread(Runnable r) {
263 if (sWorkerThread.getThreadId() == Process.myTid()) {
264 r.run();
265 } else {
266 // If we are not on the worker thread, then post to the worker handler
267 sWorker.post(r);
268 }
269 }
270
Winson Chunge43a1e72014-01-15 10:33:02 -0800271 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
272 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800273 }
274
Winson Chungc9168342013-06-26 14:54:55 -0700275 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
276 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700277 LauncherAppState app = LauncherAppState.getInstance();
278 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
279 final int xCount = (int) grid.numColumns;
280 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700281 boolean[][] occupied = new boolean[xCount][yCount];
282
283 int cellX, cellY, spanX, spanY;
284 for (int i = 0; i < items.size(); ++i) {
285 final ItemInfo item = items.get(i);
286 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
287 if (item.screenId == screen) {
288 cellX = item.cellX;
289 cellY = item.cellY;
290 spanX = item.spanX;
291 spanY = item.spanY;
292 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
293 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
294 occupied[x][y] = true;
295 }
296 }
297 }
298 }
299 }
300
301 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
302 }
303 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700304 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700305 int firstScreenIndex,
306 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700307 // Lock on the app so that we don't try and get the items while apps are being added
308 LauncherAppState app = LauncherAppState.getInstance();
309 LauncherModel model = app.getModel();
310 boolean found = false;
311 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700312 if (sWorkerThread.getThreadId() != Process.myTid()) {
313 // Flush the LauncherModel worker thread, so that if we just did another
314 // processInstallShortcut, we give it time for its shortcut to get added to the
315 // database (getItemsInLocalCoordinates reads the database)
316 model.flushWorkerThread();
317 }
Winson Chungc9168342013-06-26 14:54:55 -0700318 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700319
320 // Try adding to the workspace screens incrementally, starting at the default or center
321 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700322 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
323 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700324 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700325 int[] tmpCoordinates = new int[2];
326 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700327 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700328 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700329 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700330 }
331 }
332 }
Winson Chungc9168342013-06-26 14:54:55 -0700333 return null;
334 }
335
Sunny Goyale755d462014-07-22 13:48:29 -0700336 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500337 // Process the updated package state
338 Runnable r = new Runnable() {
339 public void run() {
340 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
341 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700342 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500343 }
344 }
345 };
346 mHandler.post(r);
347 }
348
Adam Cohen76a47a12014-02-05 11:47:43 -0800349 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
350 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
351
352 if (allAppsApps == null) {
353 throw new RuntimeException("allAppsApps must not be null");
354 }
355 if (allAppsApps.isEmpty()) {
356 return;
357 }
358
Chris Wrenb6d4c282014-01-27 14:17:08 -0500359 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
360 Iterator<AppInfo> iter = allAppsApps.iterator();
361 while (iter.hasNext()) {
362 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100363 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500364 restoredAppsFinal.add((AppInfo) a);
365 }
366 }
367
Adam Cohen76a47a12014-02-05 11:47:43 -0800368 // Process the newly added applications and add them to the database first
369 Runnable r = new Runnable() {
370 public void run() {
371 runOnMainThread(new Runnable() {
372 public void run() {
373 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
374 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500375 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500376 for (AppInfo info : restoredAppsFinal) {
377 final Intent intent = info.getIntent();
378 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100379 mIconCache.deletePreloadedIcon(intent.getComponent(),
380 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500381 }
382 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500383 callbacks.bindAppsUpdated(restoredAppsFinal);
384 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500385 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800386 }
387 }
388 });
389 }
390 };
391 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700392 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800393
394 public void addAndBindAddedWorkspaceApps(final Context context,
395 final ArrayList<ItemInfo> workspaceApps) {
396 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
397
398 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800399 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
400 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800401 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700402 return;
Winson Chung997a9232013-07-24 15:33:46 -0700403 }
Winson Chung64359a52013-07-08 17:17:08 -0700404 // Process the newly added applications and add them to the database first
405 Runnable r = new Runnable() {
406 public void run() {
407 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
408 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500409 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700410
Winson Chung76828c82013-08-19 15:43:29 -0700411 // Get the list of workspace screens. We need to append to this list and
412 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
413 // called.
414 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
415 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
416 for (Integer i : orderedScreens.keySet()) {
417 long screenId = orderedScreens.get(i);
418 workspaceScreens.add(screenId);
419 }
420
Winson Chung64359a52013-07-08 17:17:08 -0700421 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700422 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700423 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700424 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700425 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700426 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700427
428 // Short-circuit this logic if the icon exists somewhere on the workspace
429 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500430 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
431 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100432 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500433 restoredAppsFinal.add((AppInfo) a);
434 }
Winson Chung64359a52013-07-08 17:17:08 -0700435 continue;
436 }
437
Winson Chung87412982013-10-03 18:34:14 -0700438 // Add this icon to the db, creating a new page if necessary. If there
439 // is only the empty page then we just add items to the first page.
440 // Otherwise, we add them to the next pages.
441 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700442 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700443 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700444 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200445 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700446
447 // If we can't find a valid position, then just add a new screen.
448 // This takes time so we need to re-queue the add until the new
449 // page is added. Create as many screens as necessary to satisfy
450 // the startSearchPageIndex.
451 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700452 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700453 while (numPagesToAdd > 0) {
454 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700455 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700456 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700457 addedWorkspaceScreensFinal.add(screenId);
458 numPagesToAdd--;
459 }
Winson Chung76828c82013-08-19 15:43:29 -0700460
Winson Chung64359a52013-07-08 17:17:08 -0700461 // Find the coordinate again
462 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700463 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700464 }
465 if (coords == null) {
466 throw new RuntimeException("Coordinates should not be null");
467 }
468
Winson Chung997a9232013-07-24 15:33:46 -0700469 ShortcutInfo shortcutInfo;
470 if (a instanceof ShortcutInfo) {
471 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200472 } else if (a instanceof AppInfo) {
473 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700474 } else {
475 throw new RuntimeException("Unexpected info type");
476 }
Winson Chung94d67682013-09-25 16:29:40 -0700477
Winson Chung64359a52013-07-08 17:17:08 -0700478 // Add the shortcut to the db
479 addItemToDatabase(context, shortcutInfo,
480 LauncherSettings.Favorites.CONTAINER_DESKTOP,
481 coords.first, coords.second[0], coords.second[1], false);
482 // Save the ShortcutInfo for binding in the workspace
483 addedShortcutsFinal.add(shortcutInfo);
484 }
485 }
486
Winson Chung76828c82013-08-19 15:43:29 -0700487 // Update the workspace screens
488 updateWorkspaceScreenOrder(context, workspaceScreens);
489
Adam Cohen76a47a12014-02-05 11:47:43 -0800490 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700491 runOnMainThread(new Runnable() {
492 public void run() {
493 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
494 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700495 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
496 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700497 if (!addedShortcutsFinal.isEmpty()) {
498 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
499 long lastScreenId = info.screenId;
500 for (ItemInfo i : addedShortcutsFinal) {
501 if (i.screenId == lastScreenId) {
502 addAnimated.add(i);
503 } else {
504 addNotAnimated.add(i);
505 }
Winson Chung997a9232013-07-24 15:33:46 -0700506 }
507 }
Winson Chungd64d1762013-08-20 14:37:16 -0700508 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800509 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500510 if (!restoredAppsFinal.isEmpty()) {
511 callbacks.bindAppsUpdated(restoredAppsFinal);
512 }
Winson Chung997a9232013-07-24 15:33:46 -0700513 }
Winson Chung64359a52013-07-08 17:17:08 -0700514 }
Winson Chung997a9232013-07-24 15:33:46 -0700515 });
516 }
Winson Chung64359a52013-07-08 17:17:08 -0700517 }
518 };
519 runOnWorkerThread(r);
520 }
521
Winson Chung81b52252012-08-27 15:34:29 -0700522 public void unbindItemInfosAndClearQueuedBindRunnables() {
523 if (sWorkerThread.getThreadId() == Process.myTid()) {
524 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
525 "main thread");
526 }
527
528 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400529 synchronized (mDeferredBindRunnables) {
530 mDeferredBindRunnables.clear();
531 }
Winson Chung81b52252012-08-27 15:34:29 -0700532 // Remove any queued bind runnables
533 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
534 // Unbind all the workspace items
535 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700536 }
537
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700538 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700539 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700540 // Ensure that we don't use the same workspace items data structure on the main thread
541 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700542 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
543 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700544 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700545 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
546 tmpAppWidgets.addAll(sBgAppWidgets);
547 }
548 Runnable r = new Runnable() {
549 @Override
550 public void run() {
551 for (ItemInfo item : tmpWorkspaceItems) {
552 item.unbind();
553 }
554 for (ItemInfo item : tmpAppWidgets) {
555 item.unbind();
556 }
557 }
558 };
559 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700560 }
561
Joe Onorato9c1289c2009-08-17 11:03:03 -0400562 /**
563 * Adds an item to the DB if it was not created previously, or move it to a new
564 * <container, screen, cellX, cellY>
565 */
566 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700567 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400568 if (item.container == ItemInfo.NO_ID) {
569 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400571 } else {
572 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 }
575 }
576
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700577 static void checkItemInfoLocked(
578 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
579 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
580 if (modelItem != null && item != modelItem) {
581 // check all the data is consistent
582 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
583 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
584 ShortcutInfo shortcut = (ShortcutInfo) item;
585 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
586 modelShortcut.intent.filterEquals(shortcut.intent) &&
587 modelShortcut.id == shortcut.id &&
588 modelShortcut.itemType == shortcut.itemType &&
589 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700590 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700591 modelShortcut.cellX == shortcut.cellX &&
592 modelShortcut.cellY == shortcut.cellY &&
593 modelShortcut.spanX == shortcut.spanX &&
594 modelShortcut.spanY == shortcut.spanY &&
595 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
596 (modelShortcut.dropPos != null &&
597 shortcut.dropPos != null &&
598 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
599 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
600 // For all intents and purposes, this is the same object
601 return;
602 }
603 }
604
605 // the modelItem needs to match up perfectly with item if our model is
606 // to be consistent with the database-- for now, just require
607 // modelItem == item or the equality check above
608 String msg = "item: " + ((item != null) ? item.toString() : "null") +
609 "modelItem: " +
610 ((modelItem != null) ? modelItem.toString() : "null") +
611 "Error: ItemInfo passed to checkItemInfo doesn't match original";
612 RuntimeException e = new RuntimeException(msg);
613 if (stackTrace != null) {
614 e.setStackTrace(stackTrace);
615 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800616 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700617 }
618 }
619
Michael Jurka816474f2012-06-25 14:49:02 -0700620 static void checkItemInfo(final ItemInfo item) {
621 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
622 final long itemId = item.id;
623 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700624 public void run() {
625 synchronized (sBgLock) {
626 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700627 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700628 }
629 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700630 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700631 }
632
Michael Jurkac9d95c52011-08-29 14:03:34 -0700633 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
634 final ItemInfo item, final String callingFunction) {
635 final long itemId = item.id;
636 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
637 final ContentResolver cr = context.getContentResolver();
638
Adam Cohen487f7dd2012-06-28 18:12:10 -0700639 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700640 Runnable r = new Runnable() {
641 public void run() {
642 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700643 updateItemArrays(item, itemId, stackTrace);
644 }
645 };
646 runOnWorkerThread(r);
647 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700648
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700649 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
650 final ArrayList<ItemInfo> items, final String callingFunction) {
651 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700652
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700653 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
654 Runnable r = new Runnable() {
655 public void run() {
656 ArrayList<ContentProviderOperation> ops =
657 new ArrayList<ContentProviderOperation>();
658 int count = items.size();
659 for (int i = 0; i < count; i++) {
660 ItemInfo item = items.get(i);
661 final long itemId = item.id;
662 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
663 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700664
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700665 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
666 updateItemArrays(item, itemId, stackTrace);
667
668 }
669 try {
670 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
671 } catch (Exception e) {
672 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700673 }
674 }
675 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700676 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700677 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700678
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700679 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
680 // Lock on mBgLock *after* the db operation
681 synchronized (sBgLock) {
682 checkItemInfoLocked(itemId, item, stackTrace);
683
684 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
685 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
686 // Item is in a folder, make sure this folder exists
687 if (!sBgFolders.containsKey(item.container)) {
688 // An items container is being set to a that of an item which is not in
689 // the list of Folders.
690 String msg = "item: " + item + " container being set to: " +
691 item.container + ", not in the list of folders";
692 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700693 }
694 }
695
696 // Items are added/removed from the corresponding FolderInfo elsewhere, such
697 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
698 // that are on the desktop, as appropriate
699 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800700 if (modelItem != null &&
701 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
702 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700703 switch (modelItem.itemType) {
704 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
705 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
706 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
707 if (!sBgWorkspaceItems.contains(modelItem)) {
708 sBgWorkspaceItems.add(modelItem);
709 }
710 break;
711 default:
712 break;
713 }
714 } else {
715 sBgWorkspaceItems.remove(modelItem);
716 }
717 }
718 }
719
Michael Jurkac7700af2013-05-14 20:17:58 +0200720 public void flushWorkerThread() {
721 mFlushingWorkerThread = true;
722 Runnable waiter = new Runnable() {
723 public void run() {
724 synchronized (this) {
725 notifyAll();
726 mFlushingWorkerThread = false;
727 }
728 }
729 };
730
731 synchronized(waiter) {
732 runOnWorkerThread(waiter);
733 if (mLoaderTask != null) {
734 synchronized(mLoaderTask) {
735 mLoaderTask.notify();
736 }
737 }
738 boolean success = false;
739 while (!success) {
740 try {
741 waiter.wait();
742 success = true;
743 } catch (InterruptedException e) {
744 }
745 }
746 }
747 }
748
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400750 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700751 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700752 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700753 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 item.cellX = cellX;
756 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757
Winson Chung3d503fb2011-07-13 17:25:49 -0700758 // We store hotseat items in canonical form which is this orientation invariant position
759 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700763 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700764 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700765 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766
767 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400768 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700769 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
770 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700771 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400772
Michael Jurkac9d95c52011-08-29 14:03:34 -0700773 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700774 }
775
776 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700777 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
778 * cellX, cellY have already been updated on the ItemInfos.
779 */
780 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
781 final long container, final int screen) {
782
783 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
784 int count = items.size();
785
786 for (int i = 0; i < count; i++) {
787 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700788 item.container = container;
789
790 // We store hotseat items in canonical form which is this orientation invariant position
791 // in the hotseat
792 if (context instanceof Launcher && screen < 0 &&
793 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700794 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700795 item.cellY);
796 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700797 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700798 }
799
800 final ContentValues values = new ContentValues();
801 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
802 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
803 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700805
806 contentValues.add(values);
807 }
808 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
809 }
810
811 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700812 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800813 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700814 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700816 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800817 item.cellX = cellX;
818 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700819 item.spanX = spanX;
820 item.spanY = spanY;
821
822 // We store hotseat items in canonical form which is this orientation invariant position
823 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700825 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 }
Adam Cohend4844c32011-02-18 19:25:06 -0800830
Adam Cohend4844c32011-02-18 19:25:06 -0800831 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800832 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700833 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
834 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
835 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
836 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700837 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800838
Michael Jurka816474f2012-06-25 14:49:02 -0700839 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700840 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700841
842 /**
843 * Update an item to the database in a specified container.
844 */
845 static void updateItemInDatabase(Context context, final ItemInfo item) {
846 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100847 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700848 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
849 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800850 }
851
852 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400853 * Returns true if the shortcuts already exists in the database.
854 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800855 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400856 static boolean shortcutExists(Context context, String title, Intent intent) {
857 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700858 final Intent intentWithPkg, intentWithoutPkg;
859
860 if (intent.getComponent() != null) {
861 // If component is not null, an intent with null package will produce
862 // the same result and should also be a match.
863 if (intent.getPackage() != null) {
864 intentWithPkg = intent;
865 intentWithoutPkg = new Intent(intent).setPackage(null);
866 } else {
867 intentWithPkg = new Intent(intent).setPackage(
868 intent.getComponent().getPackageName());
869 intentWithoutPkg = intent;
870 }
871 } else {
872 intentWithPkg = intent;
873 intentWithoutPkg = intent;
874 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400875 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700876 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
877 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400878 boolean result = false;
879 try {
880 result = c.moveToFirst();
881 } finally {
882 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800883 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400884 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700885 }
886
Joe Onorato9c1289c2009-08-17 11:03:03 -0400887 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500888 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100889 * we identify a shortcut by the component name of the intent
890 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500891 */
Kenny Guyed131872014-04-30 03:02:21 +0100892 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500893 final ContentResolver cr = context.getContentResolver();
894 final ComponentName component = intent.getComponent();
895 if (component == null) {
896 return false;
897 }
898 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400899 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100900 long serialNumber = UserManagerCompat.getInstance(context)
901 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400902 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
903 "intent glob \"*component=" + shortName + "*\")" +
904 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500905 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100906 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500907 boolean result = false;
908 try {
909 result = c.moveToFirst();
910 } finally {
911 c.close();
912 }
913 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
914 return result;
915 }
916
917 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700918 * Returns an ItemInfo array containing all the items in the LauncherModel.
919 * The ItemInfo.id is not set through this function.
920 */
921 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
922 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
923 final ContentResolver cr = context.getContentResolver();
924 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
925 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100926 LauncherSettings.Favorites.SCREEN,
927 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
928 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
929 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700930
931 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
932 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
933 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
934 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
935 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
936 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
937 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100938 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
939 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700940 try {
941 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700942 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700943 item.cellX = c.getInt(cellXIndex);
944 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700945 item.spanX = Math.max(1, c.getInt(spanXIndex));
946 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700947 item.container = c.getInt(containerIndex);
948 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700949 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100950 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100951 item.user = userManager.getUserForSerialNumber(serialNumber);
952 // Skip if user has been deleted.
953 if (item.user != null) {
954 items.add(item);
955 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700956 }
957 } catch (Exception e) {
958 items.clear();
959 } finally {
960 c.close();
961 }
962
963 return items;
964 }
965
966 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
968 */
969 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
970 final ContentResolver cr = context.getContentResolver();
971 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
972 "_id=? and (itemType=? or itemType=?)",
973 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700974 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700975
Joe Onorato9c1289c2009-08-17 11:03:03 -0400976 try {
977 if (c.moveToFirst()) {
978 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
979 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
980 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
981 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
982 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
983 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800984
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 FolderInfo folderInfo = null;
986 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700987 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
988 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700990 }
991
Joe Onorato9c1289c2009-08-17 11:03:03 -0400992 folderInfo.title = c.getString(titleIndex);
993 folderInfo.id = id;
994 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700996 folderInfo.cellX = c.getInt(cellXIndex);
997 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998
999 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001000 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001001 } finally {
1002 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001003 }
1004
1005 return null;
1006 }
1007
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008 /**
1009 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1010 * cellY fields of the item. Also assigns an ID to the item.
1011 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001012 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001013 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001014 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001015 item.cellX = cellX;
1016 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001017 // We store hotseat items in canonical form which is this orientation invariant position
1018 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001020 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001022 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001023 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001024 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001025
1026 final ContentValues values = new ContentValues();
1027 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001028 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001029
Michael Jurka414300a2013-08-27 15:42:35 +02001030 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001031 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001032 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001033
Jason Monk8e19cf22014-03-20 15:06:57 -04001034 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001035 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036 public void run() {
1037 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1038 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001039
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001041 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001042 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001043 sBgItemsIdMap.put(item.id, item);
1044 switch (item.itemType) {
1045 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1046 sBgFolders.put(item.id, (FolderInfo) item);
1047 // Fall through
1048 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1049 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1050 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1051 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1052 sBgWorkspaceItems.add(item);
1053 } else {
1054 if (!sBgFolders.containsKey(item.container)) {
1055 // Adding an item to a folder that doesn't exist.
1056 String msg = "adding item: " + item + " to a folder that " +
1057 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001058 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001059 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001060 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001061 break;
1062 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1063 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1064 break;
1065 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001066 }
1067 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001068 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001069 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001070 }
1071
Joe Onorato9c1289c2009-08-17 11:03:03 -04001072 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001073 * Creates a new unique child id, for a given cell span across all layouts.
1074 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001075 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001077 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001078 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001079 }
1080
Winson Chungaafa03c2010-06-11 17:34:16 -07001081 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001082 * Removes the specified item from the database
1083 * @param context
1084 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001085 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001086 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001087 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001088 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001089
Michael Jurka83df1882011-08-31 20:59:26 -07001090 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001091 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001092 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001093
1094 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001095 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001096 switch (item.itemType) {
1097 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1098 sBgFolders.remove(item.id);
1099 for (ItemInfo info: sBgItemsIdMap.values()) {
1100 if (info.container == item.id) {
1101 // We are deleting a folder which still contains items that
1102 // think they are contained by that folder.
1103 String msg = "deleting a folder (" + item + ") which still " +
1104 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001105 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001107 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001108 sBgWorkspaceItems.remove(item);
1109 break;
1110 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1111 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1112 sBgWorkspaceItems.remove(item);
1113 break;
1114 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1115 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1116 break;
1117 }
1118 sBgItemsIdMap.remove(item.id);
1119 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001120 }
1121 }
Michael Jurka83df1882011-08-31 20:59:26 -07001122 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001123 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001124 }
1125
1126 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001127 * Update the order of the workspace screens in the database. The array list contains
1128 * a list of screen ids in the order that they should appear.
1129 */
Winson Chungc9168342013-06-26 14:54:55 -07001130 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001131 // Log to disk
1132 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1133 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1134
Winson Chung64359a52013-07-08 17:17:08 -07001135 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001136 final ContentResolver cr = context.getContentResolver();
1137 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1138
1139 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001140 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001141 while (iter.hasNext()) {
1142 long id = iter.next();
1143 if (id < 0) {
1144 iter.remove();
1145 }
1146 }
1147
1148 Runnable r = new Runnable() {
1149 @Override
1150 public void run() {
Yura085c8532014-02-11 15:15:29 +00001151 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001152 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001153 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001154 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 for (int i = 0; i < count; i++) {
1156 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001157 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001158 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1159 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001160 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001161 }
Yura085c8532014-02-11 15:15:29 +00001162
1163 try {
1164 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1165 } catch (Exception ex) {
1166 throw new RuntimeException(ex);
1167 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001168
Winson Chungba9c37f2013-08-30 14:11:37 -07001169 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001170 sBgWorkspaceScreens.clear();
1171 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001172 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001173 }
1174 };
1175 runOnWorkerThread(r);
1176 }
1177
1178 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001179 * Remove the contents of the specified folder from the database
1180 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001181 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001182 final ContentResolver cr = context.getContentResolver();
1183
Michael Jurkac9d95c52011-08-29 14:03:34 -07001184 Runnable r = new Runnable() {
1185 public void run() {
1186 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001187 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001188 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001189 sBgItemsIdMap.remove(info.id);
1190 sBgFolders.remove(info.id);
1191 sBgDbIconCache.remove(info);
1192 sBgWorkspaceItems.remove(info);
1193 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001194
Michael Jurkac9d95c52011-08-29 14:03:34 -07001195 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1196 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001198 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001199 for (ItemInfo childInfo : info.contents) {
1200 sBgItemsIdMap.remove(childInfo.id);
1201 sBgDbIconCache.remove(childInfo);
1202 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001203 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001204 }
1205 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001206 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001207 }
1208
1209 /**
1210 * Set this as the current Launcher activity object for the loader.
1211 */
1212 public void initialize(Callbacks callbacks) {
1213 synchronized (mLock) {
1214 mCallbacks = new WeakReference<Callbacks>(callbacks);
1215 }
1216 }
1217
Kenny Guyed131872014-04-30 03:02:21 +01001218 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001219 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001220 int op = PackageUpdatedTask.OP_UPDATE;
1221 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1222 user));
1223 }
1224
1225 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001226 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001227 int op = PackageUpdatedTask.OP_REMOVE;
1228 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1229 user));
1230 }
1231
1232 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001233 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001234 int op = PackageUpdatedTask.OP_ADD;
1235 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1236 user));
1237 }
1238
1239 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001240 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001241 boolean replacing) {
1242 if (!replacing) {
1243 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1244 user));
1245 if (mAppsCanBeOnRemoveableStorage) {
1246 // Only rebind if we support removable storage. It catches the
1247 // case where
1248 // apps on the external sd card need to be reloaded
1249 startLoaderFromBackground();
1250 }
1251 } else {
1252 // If we are replacing then just update the packages in the list
1253 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1254 packageNames, user));
1255 }
1256 }
1257
1258 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001259 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001260 boolean replacing) {
1261 if (!replacing) {
1262 enqueuePackageUpdated(new PackageUpdatedTask(
1263 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1264 user));
1265 }
1266
1267 }
1268
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001269 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001270 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1271 * ACTION_PACKAGE_CHANGED.
1272 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001273 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001274 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001275 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001276
Joe Onorato36115782010-06-17 13:28:48 -04001277 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001278 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001279 // If we have changed locale we need to clear out the labels in all apps/workspace.
1280 forceReload();
1281 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1282 // Check if configuration change was an mcc/mnc change which would affect app resources
1283 // and we would need to clear out the labels in all apps/workspace. Same handling as
1284 // above for ACTION_LOCALE_CHANGED
1285 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001286 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001287 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001288 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001289 forceReload();
1290 }
1291 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001292 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001293 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1294 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001295 if (mCallbacks != null) {
1296 Callbacks callbacks = mCallbacks.get();
1297 if (callbacks != null) {
1298 callbacks.bindSearchablesChanged();
1299 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001300 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001301 }
1302 }
1303
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001304 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001305 resetLoadedState(true, true);
1306
Reena Lee93f824a2011-09-23 17:20:28 -07001307 // Do this here because if the launcher activity is running it will be restarted.
1308 // If it's not running startLoaderFromBackground will merely tell it that it needs
1309 // to reload.
1310 startLoaderFromBackground();
1311 }
1312
Winson Chungf0c6ae02012-03-21 16:10:31 -07001313 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1314 synchronized (mLock) {
1315 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1316 // mWorkspaceLoaded to true later
1317 stopLoaderLocked();
1318 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1319 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1320 }
1321 }
1322
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001323 /**
1324 * When the launcher is in the background, it's possible for it to miss paired
1325 * configuration changes. So whenever we trigger the loader from the background
1326 * tell the launcher that it needs to re-run the loader when it comes back instead
1327 * of doing it now.
1328 */
1329 public void startLoaderFromBackground() {
1330 boolean runLoader = false;
1331 if (mCallbacks != null) {
1332 Callbacks callbacks = mCallbacks.get();
1333 if (callbacks != null) {
1334 // Only actually run the loader if they're not paused.
1335 if (!callbacks.setLoadOnResume()) {
1336 runLoader = true;
1337 }
1338 }
1339 }
1340 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001341 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001342 }
Joe Onorato36115782010-06-17 13:28:48 -04001343 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001344
Reena Lee93f824a2011-09-23 17:20:28 -07001345 // If there is already a loader task running, tell it to stop.
1346 // returns true if isLaunching() was true on the old task
1347 private boolean stopLoaderLocked() {
1348 boolean isLaunching = false;
1349 LoaderTask oldTask = mLoaderTask;
1350 if (oldTask != null) {
1351 if (oldTask.isLaunching()) {
1352 isLaunching = true;
1353 }
1354 oldTask.stopLocked();
1355 }
1356 return isLaunching;
1357 }
1358
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001359 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001360 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1361 }
1362
1363 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001364 synchronized (mLock) {
1365 if (DEBUG_LOADERS) {
1366 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1367 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001368
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001369 // Clear any deferred bind-runnables from the synchronized load process
1370 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001371 synchronized (mDeferredBindRunnables) {
1372 mDeferredBindRunnables.clear();
1373 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001374
Joe Onorato36115782010-06-17 13:28:48 -04001375 // Don't bother to start the thread if we know it's not going to do anything
1376 if (mCallbacks != null && mCallbacks.get() != null) {
1377 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001378 // also, don't downgrade isLaunching if we're already running
1379 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001380 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001381 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1382 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001383 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1384 } else {
1385 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1386 sWorker.post(mLoaderTask);
1387 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001388 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001389 }
1390 }
1391
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001392 void bindRemainingSynchronousPages() {
1393 // Post the remaining side pages to be loaded
1394 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001395 Runnable[] deferredBindRunnables = null;
1396 synchronized (mDeferredBindRunnables) {
1397 deferredBindRunnables = mDeferredBindRunnables.toArray(
1398 new Runnable[mDeferredBindRunnables.size()]);
1399 mDeferredBindRunnables.clear();
1400 }
1401 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001402 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001404 }
1405 }
1406
Joe Onorato36115782010-06-17 13:28:48 -04001407 public void stopLoader() {
1408 synchronized (mLock) {
1409 if (mLoaderTask != null) {
1410 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001411 }
1412 }
Joe Onorato36115782010-06-17 13:28:48 -04001413 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001414
Winson Chung76828c82013-08-19 15:43:29 -07001415 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1416 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1417 final ContentResolver contentResolver = context.getContentResolver();
1418 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1419 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1420 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1421
1422 try {
1423 final int idIndex = sc.getColumnIndexOrThrow(
1424 LauncherSettings.WorkspaceScreens._ID);
1425 final int rankIndex = sc.getColumnIndexOrThrow(
1426 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1427 while (sc.moveToNext()) {
1428 try {
1429 long screenId = sc.getLong(idIndex);
1430 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001431 orderedScreens.put(rank, screenId);
1432 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001433 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001434 }
1435 }
1436 } finally {
1437 sc.close();
1438 }
Winson Chunga90303b2013-11-15 13:05:06 -08001439
1440 // Log to disk
1441 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1442 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1443 for (Integer i : orderedScreens.keySet()) {
1444 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1445 }
1446 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1447 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001448 return orderedScreens;
1449 }
1450
Michael Jurkac57b7a82011-08-09 22:02:20 -07001451 public boolean isAllAppsLoaded() {
1452 return mAllAppsLoaded;
1453 }
1454
Winson Chung36a62fe2012-05-06 18:04:42 -07001455 boolean isLoadingWorkspace() {
1456 synchronized (mLock) {
1457 if (mLoaderTask != null) {
1458 return mLoaderTask.isLoadingWorkspace();
1459 }
1460 }
1461 return false;
1462 }
1463
Joe Onorato36115782010-06-17 13:28:48 -04001464 /**
1465 * Runnable for the thread that loads the contents of the launcher:
1466 * - workspace icons
1467 * - widgets
1468 * - all apps icons
1469 */
1470 private class LoaderTask implements Runnable {
1471 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001472 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001473 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001474 private boolean mStopped;
1475 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001476 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001477
Winson Chungc3eecff2011-07-11 17:44:15 -07001478 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001479
Dan Sandlerd5024042014-01-09 15:01:33 -05001480 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001481 mContext = context;
1482 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001483 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001484 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001485 }
1486
Joe Onorato36115782010-06-17 13:28:48 -04001487 boolean isLaunching() {
1488 return mIsLaunching;
1489 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001490
Winson Chung36a62fe2012-05-06 18:04:42 -07001491 boolean isLoadingWorkspace() {
1492 return mIsLoadingAndBindingWorkspace;
1493 }
1494
Winson Chungc763c4e2013-07-19 13:49:06 -07001495 /** Returns whether this is an upgrade path */
1496 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001497 mIsLoadingAndBindingWorkspace = true;
1498
Joe Onorato36115782010-06-17 13:28:48 -04001499 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001500 if (DEBUG_LOADERS) {
1501 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001502 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001503
Winson Chungc763c4e2013-07-19 13:49:06 -07001504 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001505 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001506 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001507 synchronized (LoaderTask.this) {
1508 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001509 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001510 }
1511 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001512 }
1513 }
1514
Joe Onorato36115782010-06-17 13:28:48 -04001515 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001516 bindWorkspace(-1, isUpgradePath);
1517 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001518 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001519
Joe Onorato36115782010-06-17 13:28:48 -04001520 private void waitForIdle() {
1521 // Wait until the either we're stopped or the other threads are done.
1522 // This way we don't start loading all apps until the workspace has settled
1523 // down.
1524 synchronized (LoaderTask.this) {
1525 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001526
Joe Onorato36115782010-06-17 13:28:48 -04001527 mHandler.postIdle(new Runnable() {
1528 public void run() {
1529 synchronized (LoaderTask.this) {
1530 mLoadAndBindStepFinished = true;
1531 if (DEBUG_LOADERS) {
1532 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001533 }
Joe Onorato36115782010-06-17 13:28:48 -04001534 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001535 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001536 }
Joe Onorato36115782010-06-17 13:28:48 -04001537 });
1538
Michael Jurkac7700af2013-05-14 20:17:58 +02001539 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001540 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001541 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1542 // wait no longer than 1sec at a time
1543 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001544 } catch (InterruptedException ex) {
1545 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001546 }
1547 }
Joe Onorato36115782010-06-17 13:28:48 -04001548 if (DEBUG_LOADERS) {
1549 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001550 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001551 + "ms for previous step to finish binding");
1552 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001553 }
Joe Onorato36115782010-06-17 13:28:48 -04001554 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001555
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001556 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001557 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001558 // Ensure that we have a valid page index to load synchronously
1559 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1560 "valid page index");
1561 }
1562 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1563 // Ensure that we don't try and bind a specified page when the pages have not been
1564 // loaded already (we should load everything asynchronously in that case)
1565 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1566 }
1567 synchronized (mLock) {
1568 if (mIsLoaderTaskRunning) {
1569 // Ensure that we are never running the background loading at this point since
1570 // we also touch the background collections
1571 throw new RuntimeException("Error! Background loading is already running");
1572 }
1573 }
1574
1575 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1576 // data structures, we can't allow any other thread to touch that data, but because
1577 // this call is synchronous, we can get away with not locking).
1578
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001579 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001580 // operations from the previous activity. We need to ensure that all queued operations
1581 // are executed before any synchronous binding work is done.
1582 mHandler.flush();
1583
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001584 // Divide the set of loaded items into those that we are binding synchronously, and
1585 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001586 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001587 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1588 // arise from that.
1589 onlyBindAllApps();
1590 }
1591
Joe Onorato36115782010-06-17 13:28:48 -04001592 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001593 boolean isUpgrade = false;
1594
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001595 synchronized (mLock) {
1596 mIsLoaderTaskRunning = true;
1597 }
Joe Onorato36115782010-06-17 13:28:48 -04001598 // Optimize for end-user experience: if the Launcher is up and // running with the
1599 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1600 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001601 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001602 // Elevate priority when Home launches for the first time to avoid
1603 // starving at boot time. Staring at a blank home is not cool.
1604 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001605 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1606 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001607 android.os.Process.setThreadPriority(mIsLaunching
1608 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1609 }
Winson Chung64359a52013-07-08 17:17:08 -07001610 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001611 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001612
Joe Onorato36115782010-06-17 13:28:48 -04001613 if (mStopped) {
1614 break keep_running;
1615 }
1616
1617 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1618 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001619 synchronized (mLock) {
1620 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001621 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001622 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1623 }
1624 }
Joe Onorato36115782010-06-17 13:28:48 -04001625 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001626
1627 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001628 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1629 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001630
1631 // Restore the default thread priority after we are done loading items
1632 synchronized (mLock) {
1633 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1634 }
Joe Onorato36115782010-06-17 13:28:48 -04001635 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001636
Winson Chungaac01e12011-08-17 10:37:13 -07001637 // Update the saved icons if necessary
1638 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001639 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001640 for (Object key : sBgDbIconCache.keySet()) {
1641 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1642 }
1643 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001644 }
Winson Chungaac01e12011-08-17 10:37:13 -07001645
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001646 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001647 // Ensure that all the applications that are in the system are
1648 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001649 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001650 verifyApplications();
1651 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001652 }
1653
Joe Onorato36115782010-06-17 13:28:48 -04001654 // Clear out this reference, otherwise we end up holding it until all of the
1655 // callback runnables are done.
1656 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001657
Joe Onorato36115782010-06-17 13:28:48 -04001658 synchronized (mLock) {
1659 // If we are still the last one to be scheduled, remove ourselves.
1660 if (mLoaderTask == this) {
1661 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001662 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001663 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001664 }
Joe Onorato36115782010-06-17 13:28:48 -04001665 }
1666
1667 public void stopLocked() {
1668 synchronized (LoaderTask.this) {
1669 mStopped = true;
1670 this.notify();
1671 }
1672 }
1673
1674 /**
1675 * Gets the callbacks object. If we've been stopped, or if the launcher object
1676 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1677 * object that was around when the deferred message was scheduled, and if there's
1678 * a new Callbacks object around then also return null. This will save us from
1679 * calling onto it with data that will be ignored.
1680 */
1681 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1682 synchronized (mLock) {
1683 if (mStopped) {
1684 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001685 }
Joe Onorato36115782010-06-17 13:28:48 -04001686
1687 if (mCallbacks == null) {
1688 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001689 }
Joe Onorato36115782010-06-17 13:28:48 -04001690
1691 final Callbacks callbacks = mCallbacks.get();
1692 if (callbacks != oldCallbacks) {
1693 return null;
1694 }
1695 if (callbacks == null) {
1696 Log.w(TAG, "no mCallbacks");
1697 return null;
1698 }
1699
1700 return callbacks;
1701 }
1702 }
1703
Winson Chungc763c4e2013-07-19 13:49:06 -07001704 private void verifyApplications() {
1705 final Context context = mApp.getContext();
1706
1707 // Cross reference all the applications in our apps list with items in the workspace
1708 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001709 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001710 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001711 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001712 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001713 if (tmpInfos.isEmpty()) {
1714 // We are missing an application icon, so add this to the workspace
1715 added.add(app);
1716 // This is a rare event, so lets log it
1717 Log.e(TAG, "Missing Application on load: " + app);
1718 }
1719 }
1720 }
1721 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001722 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001723 }
1724 }
1725
Joe Onorato36115782010-06-17 13:28:48 -04001726 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001727 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001728 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001729 LauncherAppState app = LauncherAppState.getInstance();
1730 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001731 final int countX = (int) grid.numColumns;
1732 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001733
Adam Cohendcd297f2013-06-18 13:13:40 -07001734 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001735 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001736 // Return early if we detect that an item is under the hotseat button
1737 if (mCallbacks == null ||
1738 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001739 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001740 Log.e(TAG, "Error loading shortcut into hotseat " + item
1741 + " into position (" + item.screenId + ":" + item.cellX + ","
1742 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001743 return false;
1744 }
1745
Dan Sandler295ae182013-12-10 16:05:47 -05001746 final ItemInfo[][] hotseatItems =
1747 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1748
Adam Cohenae4409d2013-11-26 10:34:59 -08001749 if (item.screenId >= grid.numHotseatIcons) {
1750 Log.e(TAG, "Error loading shortcut " + item
1751 + " into hotseat position " + item.screenId
1752 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1753 + ")");
1754 return false;
1755 }
1756
Dan Sandler295ae182013-12-10 16:05:47 -05001757 if (hotseatItems != null) {
1758 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001759 Log.e(TAG, "Error loading shortcut into hotseat " + item
1760 + " into position (" + item.screenId + ":" + item.cellX + ","
1761 + item.cellY + ") occupied by "
1762 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1763 [(int) item.screenId][0]);
1764 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001765 } else {
1766 hotseatItems[(int) item.screenId][0] = item;
1767 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001768 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001769 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001770 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001771 items[(int) item.screenId][0] = item;
1772 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001773 return true;
1774 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001775 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1776 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001777 return true;
1778 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001779
Adam Cohendcd297f2013-06-18 13:13:40 -07001780 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001781 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001782 occupied.put(item.screenId, items);
1783 }
1784
Dan Sandler295ae182013-12-10 16:05:47 -05001785 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001786 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1787 item.cellX < 0 || item.cellY < 0 ||
1788 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1789 Log.e(TAG, "Error loading shortcut " + item
1790 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1791 + item.cellX + "," + item.cellY
1792 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1793 return false;
1794 }
1795
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001796 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001797 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1798 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001800 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001801 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001802 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001803 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001804 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001805 return false;
1806 }
1807 }
1808 }
1809 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1810 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001811 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001812 }
1813 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001814
Joe Onorato36115782010-06-17 13:28:48 -04001815 return true;
1816 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001817
Winson Chungba9c37f2013-08-30 14:11:37 -07001818 /** Clears all the sBg data structures */
1819 private void clearSBgDataStructures() {
1820 synchronized (sBgLock) {
1821 sBgWorkspaceItems.clear();
1822 sBgAppWidgets.clear();
1823 sBgFolders.clear();
1824 sBgItemsIdMap.clear();
1825 sBgDbIconCache.clear();
1826 sBgWorkspaceScreens.clear();
1827 }
1828 }
1829
Dan Sandlerd5024042014-01-09 15:01:33 -05001830 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001831 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001832 // Log to disk
1833 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1834
Joe Onorato36115782010-06-17 13:28:48 -04001835 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001836
Joe Onorato36115782010-06-17 13:28:48 -04001837 final Context context = mContext;
1838 final ContentResolver contentResolver = context.getContentResolver();
1839 final PackageManager manager = context.getPackageManager();
1840 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1841 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001842 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1843 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001844 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001845
Winson Chung892c74d2013-08-22 16:15:50 -07001846 LauncherAppState app = LauncherAppState.getInstance();
1847 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1848 int countX = (int) grid.numColumns;
1849 int countY = (int) grid.numRows;
1850
Dan Sandlerd5024042014-01-09 15:01:33 -05001851 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1852 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1853 LauncherAppState.getLauncherProvider().deleteDatabase();
1854 }
1855
1856 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1857 // append the user's Launcher2 shortcuts
1858 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1859 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1860 } else {
1861 // Make sure the default workspace is loaded
1862 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001863 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001864 }
Adam Cohene25af792013-06-06 23:08:25 -07001865
Adam Cohen71483f42014-05-15 14:04:01 -07001866 // This code path is for our old migration code and should no longer be exercised
1867 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001868
Winson Chung9f9f00b2013-11-15 13:27:00 -08001869 // Log to disk
1870 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001871
Winson Chung2abf94d2012-07-18 18:16:38 -07001872 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001873 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001874
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001875 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001876 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001877 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001878 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001879 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001880
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 // +1 for the hotseat (it can be larger than the workspace)
1882 // Load workspace in reverse order to ensure that latest items are loaded first (and
1883 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001884 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001885
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001886 try {
1887 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1888 final int intentIndex = c.getColumnIndexOrThrow
1889 (LauncherSettings.Favorites.INTENT);
1890 final int titleIndex = c.getColumnIndexOrThrow
1891 (LauncherSettings.Favorites.TITLE);
1892 final int iconTypeIndex = c.getColumnIndexOrThrow(
1893 LauncherSettings.Favorites.ICON_TYPE);
1894 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1895 final int iconPackageIndex = c.getColumnIndexOrThrow(
1896 LauncherSettings.Favorites.ICON_PACKAGE);
1897 final int iconResourceIndex = c.getColumnIndexOrThrow(
1898 LauncherSettings.Favorites.ICON_RESOURCE);
1899 final int containerIndex = c.getColumnIndexOrThrow(
1900 LauncherSettings.Favorites.CONTAINER);
1901 final int itemTypeIndex = c.getColumnIndexOrThrow(
1902 LauncherSettings.Favorites.ITEM_TYPE);
1903 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001905 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001907 final int screenIndex = c.getColumnIndexOrThrow(
1908 LauncherSettings.Favorites.SCREEN);
1909 final int cellXIndex = c.getColumnIndexOrThrow
1910 (LauncherSettings.Favorites.CELLX);
1911 final int cellYIndex = c.getColumnIndexOrThrow
1912 (LauncherSettings.Favorites.CELLY);
1913 final int spanXIndex = c.getColumnIndexOrThrow
1914 (LauncherSettings.Favorites.SPANX);
1915 final int spanYIndex = c.getColumnIndexOrThrow(
1916 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001917 final int restoredIndex = c.getColumnIndexOrThrow(
1918 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001919 final int profileIdIndex = c.getColumnIndexOrThrow(
1920 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001921 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1922 //final int displayModeIndex = c.getColumnIndexOrThrow(
1923 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001924
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001925 ShortcutInfo info;
1926 String intentDescription;
1927 LauncherAppWidgetInfo appWidgetInfo;
1928 int container;
1929 long id;
1930 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001931 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001932
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001933 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001934 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001935 try {
1936 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001937 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001938 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001939
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001940 switch (itemType) {
1941 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1942 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001943 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001944 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001945 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001946 user = mUserManager.getUserForSerialNumber(serialNumber);
1947 if (user == null) {
1948 // User has been deleted remove the item.
1949 itemsToRemove.add(id);
1950 continue;
1951 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001952 try {
1953 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001954 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001955 if (cn != null && cn.getPackageName() != null) {
1956 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1957 cn.getPackageName(), user);
1958 boolean validComponent = validPkg &&
1959 launcherApps.isActivityEnabledForProfile(cn, user);
1960
1961 if (validComponent) {
1962 if (restored) {
1963 // no special handling necessary for this item
1964 restoredRows.add(id);
1965 restored = false;
1966 }
1967 } else if (validPkg) {
1968 // The app is installed but the component is no
1969 // longer available.
1970 Launcher.addDumpLog(TAG,
1971 "Invalid component removed: " + cn, true);
1972 itemsToRemove.add(id);
1973 continue;
1974 } else if (restored) {
1975 // Package is not yet available but might be
1976 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001977 Launcher.addDumpLog(TAG,
1978 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001979 } else if (isSdCardReady) {
1980 // Do not wait for external media load anymore.
1981 // Log the invalid package, and remove it
1982 Launcher.addDumpLog(TAG,
1983 "Invalid package removed: " + cn, true);
1984 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05001985 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001986 } else {
1987 // SdCard is not ready yet. Package might get available,
1988 // once it is ready.
1989 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1990 + " (check again later)", true);
1991 HashSet<String> pkgs = sPendingPackages.get(user);
1992 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001993 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001994 sPendingPackages.put(user, pkgs);
1995 }
1996 pkgs.add(cn.getPackageName());
1997 allowMissingTarget = true;
1998 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07001999 }
Winson Chungee055712013-07-30 14:46:24 -07002000 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002001 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002002 Launcher.addDumpLog(TAG,
2003 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002004 continue;
2005 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002006
Chris Wrenf4d08112014-01-16 18:13:56 -05002007 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002008 if (user.equals(UserHandleCompat.myUserHandle())) {
2009 Launcher.addDumpLog(TAG,
2010 "constructing info for partially restored package",
2011 true);
2012 info = getRestoredItemInfo(c, titleIndex, intent);
2013 intent = getRestoredItemIntent(c, context, intent);
2014 } else {
2015 // Don't restore items for other profiles.
2016 itemsToRemove.add(id);
2017 continue;
2018 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002019 } else if (itemType ==
2020 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002021 info = getShortcutInfo(manager, intent, user, context, c,
2022 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002023 } else {
2024 info = getShortcutInfo(c, context, iconTypeIndex,
2025 iconPackageIndex, iconResourceIndex, iconIndex,
2026 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002027
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002028 // App shortcuts that used to be automatically added to Launcher
2029 // didn't always have the correct intent flags set, so do that
2030 // here
2031 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002032 intent.getCategories() != null &&
2033 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002034 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002035 intent.addFlags(
2036 Intent.FLAG_ACTIVITY_NEW_TASK |
2037 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2038 }
Michael Jurka96879562012-03-22 05:54:33 -07002039 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002040
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002041 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002042 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002043 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002044 container = c.getInt(containerIndex);
2045 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002046 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002047 info.cellX = c.getInt(cellXIndex);
2048 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002049 info.spanX = 1;
2050 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002051 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002052 info.isDisabled = isSafeMode
2053 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002054
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002056 deleteOnInvalidPlacement.set(false);
2057 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2058 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002059 itemsToRemove.add(id);
2060 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002061 break;
2062 }
2063
2064 switch (container) {
2065 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2066 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2067 sBgWorkspaceItems.add(info);
2068 break;
2069 default:
2070 // Item is in a user folder
2071 FolderInfo folderInfo =
2072 findOrMakeFolder(sBgFolders, container);
2073 folderInfo.add(info);
2074 break;
2075 }
2076 sBgItemsIdMap.put(info.id, info);
2077
2078 // now that we've loaded everthing re-save it with the
2079 // icon in case it disappears somehow.
2080 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002081 } else {
2082 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 }
2084 break;
2085
2086 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2087 id = c.getLong(idIndex);
2088 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2089
2090 folderInfo.title = c.getString(titleIndex);
2091 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002092 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002094 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002095 folderInfo.cellX = c.getInt(cellXIndex);
2096 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002097 folderInfo.spanX = 1;
2098 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002099
Daniel Sandler8802e962010-05-26 16:28:16 -04002100 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002101 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002102 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002103 deleteOnInvalidPlacement)) {
2104 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002105 itemsToRemove.add(id);
2106 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002107 break;
2108 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002109
Joe Onorato9c1289c2009-08-17 11:03:03 -04002110 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2112 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2113 sBgWorkspaceItems.add(folderInfo);
2114 break;
Joe Onorato36115782010-06-17 13:28:48 -04002115 }
Joe Onorato17a89222011-02-08 17:26:11 -08002116
Chris Wrenf4d08112014-01-16 18:13:56 -05002117 if (restored) {
2118 // no special handling required for restored folders
2119 restoredRows.add(id);
2120 }
2121
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2123 sBgFolders.put(folderInfo.id, folderInfo);
2124 break;
2125
2126 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2127 // Read all Launcher-specific widget details
2128 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002129 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002130 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002131 final ComponentName component =
2132 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002133
Sunny Goyal651077b2014-06-30 14:15:31 -07002134 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002135 final boolean isIdValid = (restoreStatus &
2136 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002137
Sunny Goyalff572272014-07-23 13:58:07 -07002138 final boolean wasProviderReady = (restoreStatus &
2139 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002140
Sunny Goyalff572272014-07-23 13:58:07 -07002141 final AppWidgetProviderInfo provider = isIdValid
2142 ? widgets.getAppWidgetInfo(appWidgetId)
2143 : findAppWidgetProviderInfoWithComponent(context, component);
2144
2145 final boolean isProviderReady = isValidProvider(provider);
2146 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002147 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002148 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002150 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 itemsToRemove.add(id);
2152 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002153 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002154 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2155 provider.provider);
2156 int[] minSpan =
2157 Launcher.getMinSpanForWidget(context, provider);
2158 appWidgetInfo.minSpanX = minSpan[0];
2159 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002160
2161 int status = restoreStatus;
2162 if (!wasProviderReady) {
2163 // If provider was not previously ready, update the
2164 // status and UI flag.
2165
2166 // Id would be valid only if the widget restore broadcast was received.
2167 if (isIdValid) {
2168 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2169 } else {
2170 status &= ~LauncherAppWidgetInfo
2171 .FLAG_PROVIDER_NOT_READY;
2172 }
2173 }
2174 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002175 } else {
2176 Log.v(TAG, "Widget restore pending id=" + id
2177 + " appWidgetId=" + appWidgetId
2178 + " status =" + restoreStatus);
2179 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002180 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002181 appWidgetInfo.restoreStatus = restoreStatus;
2182 }
Sunny Goyalff572272014-07-23 13:58:07 -07002183
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002185 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002186 appWidgetInfo.cellX = c.getInt(cellXIndex);
2187 appWidgetInfo.cellY = c.getInt(cellYIndex);
2188 appWidgetInfo.spanX = c.getInt(spanXIndex);
2189 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002190
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002191 container = c.getInt(containerIndex);
2192 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2193 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2194 Log.e(TAG, "Widget found where container != " +
2195 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2196 continue;
2197 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002198
Adam Cohene25af792013-06-06 23:08:25 -07002199 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002200 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002201 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002202 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002203 deleteOnInvalidPlacement)) {
2204 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002205 itemsToRemove.add(id);
2206 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002207 break;
2208 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002209
Sunny Goyalff572272014-07-23 13:58:07 -07002210 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 String providerName = provider.provider.flattenToString();
Sunny Goyalff572272014-07-23 13:58:07 -07002212 if (!providerName.equals(savedProvider) ||
2213 (appWidgetInfo.restoreStatus != restoreStatus)) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002214 ContentValues values = new ContentValues();
2215 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2216 providerName);
2217 values.put(LauncherSettings.Favorites.RESTORED,
Sunny Goyalff572272014-07-23 13:58:07 -07002218 appWidgetInfo.restoreStatus);
Sunny Goyal651077b2014-06-30 14:15:31 -07002219 String where = BaseColumns._ID + "= ?";
2220 String[] args = {Long.toString(id)};
2221 contentResolver.update(contentUri, values, where, args);
2222 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002223 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002224 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2225 sBgAppWidgets.add(appWidgetInfo);
2226 }
Joe Onorato36115782010-06-17 13:28:48 -04002227 break;
2228 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002229 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002230 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002231 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 }
2233 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002234 if (c != null) {
2235 c.close();
2236 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002237 }
2238
Winson Chungba9c37f2013-08-30 14:11:37 -07002239 // Break early if we've stopped loading
2240 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002241 clearSBgDataStructures();
2242 return false;
2243 }
2244
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 if (itemsToRemove.size() > 0) {
2246 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002247 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002248 // Remove dead items
2249 for (long id : itemsToRemove) {
2250 if (DEBUG_LOADERS) {
2251 Log.d(TAG, "Removed id = " + id);
2252 }
2253 // Don't notify content observers
2254 try {
2255 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2256 null, null);
2257 } catch (RemoteException e) {
2258 Log.w(TAG, "Could not remove id = " + id);
2259 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002260 }
2261 }
2262
Chris Wrenf4d08112014-01-16 18:13:56 -05002263 if (restoredRows.size() > 0) {
2264 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2265 LauncherSettings.Favorites.CONTENT_URI);
2266 // Update restored items that no longer require special handling
2267 try {
2268 StringBuilder selectionBuilder = new StringBuilder();
2269 selectionBuilder.append(LauncherSettings.Favorites._ID);
2270 selectionBuilder.append(" IN (");
2271 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2272 selectionBuilder.append(")");
2273 ContentValues values = new ContentValues();
2274 values.put(LauncherSettings.Favorites.RESTORED, 0);
2275 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2276 values, selectionBuilder.toString(), null);
2277 } catch (RemoteException e) {
2278 Log.w(TAG, "Could not update restored rows");
2279 }
2280 }
2281
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002282 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2283 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002284 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002285 null, sWorker);
2286 }
2287
Winson Chungc763c4e2013-07-19 13:49:06 -07002288 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002289 long maxScreenId = 0;
2290 // If we're importing we use the old screen order.
2291 for (ItemInfo item: sBgItemsIdMap.values()) {
2292 long screenId = item.screenId;
2293 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2294 !sBgWorkspaceScreens.contains(screenId)) {
2295 sBgWorkspaceScreens.add(screenId);
2296 if (screenId > maxScreenId) {
2297 maxScreenId = screenId;
2298 }
2299 }
2300 }
2301 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002302 // Log to disk
2303 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2304 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2305 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002306
Michael Jurka414300a2013-08-27 15:42:35 +02002307 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002308 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002309
2310 // Update the max item id after we load an old db
2311 long maxItemId = 0;
2312 // If we're importing we use the old screen order.
2313 for (ItemInfo item: sBgItemsIdMap.values()) {
2314 maxItemId = Math.max(maxItemId, item.id);
2315 }
Michael Jurka414300a2013-08-27 15:42:35 +02002316 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002317 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002318 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2319 for (Integer i : orderedScreens.keySet()) {
2320 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002321 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002322 // Log to disk
2323 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2324 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002325
2326 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002327 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002328 for (ItemInfo item: sBgItemsIdMap.values()) {
2329 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002330 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2331 unusedScreens.contains(screenId)) {
2332 unusedScreens.remove(screenId);
2333 }
2334 }
2335
2336 // If there are any empty screens remove them, and update.
2337 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002338 // Log to disk
2339 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2340 TextUtils.join(", ", unusedScreens), true);
2341
Winson Chung933bae62013-08-29 11:42:30 -07002342 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002343 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2344 }
2345 }
2346
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002347 if (DEBUG_LOADERS) {
2348 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2349 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002350 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002351 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002352 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002353
Daniel Sandler566da102013-06-25 23:43:45 -04002354 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002355 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002356 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002357 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002358 line += " | ";
2359 }
Winson Chung892c74d2013-08-22 16:15:50 -07002360 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002361 ItemInfo[][] screen = occupied.get(screenId);
2362 if (x < screen.length && y < screen[x].length) {
2363 line += (screen[x][y] != null) ? "#" : ".";
2364 } else {
2365 line += "!";
2366 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002367 }
Joe Onorato36115782010-06-17 13:28:48 -04002368 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002369 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002370 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002371 }
Joe Onorato36115782010-06-17 13:28:48 -04002372 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002373 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002374 }
2375
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002376 /** Filters the set of items who are directly or indirectly (via another container) on the
2377 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002378 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 ArrayList<ItemInfo> allWorkspaceItems,
2380 ArrayList<ItemInfo> currentScreenItems,
2381 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002382 // Purge any null ItemInfos
2383 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2384 while (iter.hasNext()) {
2385 ItemInfo i = iter.next();
2386 if (i == null) {
2387 iter.remove();
2388 }
2389 }
2390
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002391 // Order the set of items by their containers first, this allows use to walk through the
2392 // list sequentially, build up a list of containers that are in the specified screen,
2393 // as well as all items in those containers.
2394 Set<Long> itemsOnScreen = new HashSet<Long>();
2395 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2396 @Override
2397 public int compare(ItemInfo lhs, ItemInfo rhs) {
2398 return (int) (lhs.container - rhs.container);
2399 }
2400 });
2401 for (ItemInfo info : allWorkspaceItems) {
2402 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002403 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002404 currentScreenItems.add(info);
2405 itemsOnScreen.add(info.id);
2406 } else {
2407 otherScreenItems.add(info);
2408 }
2409 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2410 currentScreenItems.add(info);
2411 itemsOnScreen.add(info.id);
2412 } else {
2413 if (itemsOnScreen.contains(info.container)) {
2414 currentScreenItems.add(info);
2415 itemsOnScreen.add(info.id);
2416 } else {
2417 otherScreenItems.add(info);
2418 }
2419 }
2420 }
2421 }
2422
2423 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002424 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002425 ArrayList<LauncherAppWidgetInfo> appWidgets,
2426 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2427 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002428
2429 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002430 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002431 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002432 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002433 currentScreenWidgets.add(widget);
2434 } else {
2435 otherScreenWidgets.add(widget);
2436 }
2437 }
2438 }
2439
2440 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002441 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002442 HashMap<Long, ItemInfo> itemsIdMap,
2443 HashMap<Long, FolderInfo> folders,
2444 HashMap<Long, FolderInfo> currentScreenFolders,
2445 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002446
2447 for (long id : folders.keySet()) {
2448 ItemInfo info = itemsIdMap.get(id);
2449 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002450 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002452 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453 currentScreenFolders.put(id, folder);
2454 } else {
2455 otherScreenFolders.put(id, folder);
2456 }
2457 }
2458 }
2459
2460 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2461 * right) */
2462 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002463 final LauncherAppState app = LauncherAppState.getInstance();
2464 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002465 // XXX: review this
2466 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002467 @Override
2468 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002469 int cellCountX = (int) grid.numColumns;
2470 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002471 int screenOffset = cellCountX * cellCountY;
2472 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002473 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002474 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002475 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002476 rhs.cellY * cellCountX + rhs.cellX);
2477 return (int) (lr - rr);
2478 }
2479 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002481
Adam Cohendcd297f2013-06-18 13:13:40 -07002482 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2483 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002484 final Runnable r = new Runnable() {
2485 @Override
2486 public void run() {
2487 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2488 if (callbacks != null) {
2489 callbacks.bindScreens(orderedScreens);
2490 }
2491 }
2492 };
2493 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2494 }
2495
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002496 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2497 final ArrayList<ItemInfo> workspaceItems,
2498 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2499 final HashMap<Long, FolderInfo> folders,
2500 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002501
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002502 final boolean postOnMainThread = (deferredBindRunnables != null);
2503
2504 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002505 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002506 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002507 final int start = i;
2508 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002509 final Runnable r = new Runnable() {
2510 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002511 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002512 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002513 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002514 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2515 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002516 }
2517 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002518 };
2519 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002520 synchronized (deferredBindRunnables) {
2521 deferredBindRunnables.add(r);
2522 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002524 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002525 }
Joe Onorato36115782010-06-17 13:28:48 -04002526 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002527
2528 // Bind the folders
2529 if (!folders.isEmpty()) {
2530 final Runnable r = new Runnable() {
2531 public void run() {
2532 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2533 if (callbacks != null) {
2534 callbacks.bindFolders(folders);
2535 }
2536 }
2537 };
2538 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002539 synchronized (deferredBindRunnables) {
2540 deferredBindRunnables.add(r);
2541 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002543 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544 }
2545 }
2546
2547 // Bind the widgets, one at a time
2548 N = appWidgets.size();
2549 for (int i = 0; i < N; i++) {
2550 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2551 final Runnable r = new Runnable() {
2552 public void run() {
2553 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2554 if (callbacks != null) {
2555 callbacks.bindAppWidget(widget);
2556 }
2557 }
2558 };
2559 if (postOnMainThread) {
2560 deferredBindRunnables.add(r);
2561 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002562 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002563 }
2564 }
2565 }
2566
2567 /**
2568 * Binds all loaded data to actual views on the main thread.
2569 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002570 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002571 final long t = SystemClock.uptimeMillis();
2572 Runnable r;
2573
2574 // Don't use these two variables in any of the callback runnables.
2575 // Otherwise we hold a reference to them.
2576 final Callbacks oldCallbacks = mCallbacks.get();
2577 if (oldCallbacks == null) {
2578 // This launcher has exited and nobody bothered to tell us. Just bail.
2579 Log.w(TAG, "LoaderTask running with no launcher");
2580 return;
2581 }
2582
Winson Chung9b9fb962013-11-15 15:39:34 -08002583 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2585 ArrayList<LauncherAppWidgetInfo> appWidgets =
2586 new ArrayList<LauncherAppWidgetInfo>();
2587 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2588 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002589 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002590 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 workspaceItems.addAll(sBgWorkspaceItems);
2592 appWidgets.addAll(sBgAppWidgets);
2593 folders.putAll(sBgFolders);
2594 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002595 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002596 }
2597
Derek Prothro7aff3992013-12-10 14:00:37 -05002598 final boolean isLoadingSynchronously =
2599 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002600 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002601 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002602 if (currScreen >= orderedScreenIds.size()) {
2603 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002604 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002605 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002606 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002607 final long currentScreenId = currentScreen < 0
2608 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002609
2610 // Load all the items that are on the current page first (and in the process, unbind
2611 // all the existing workspace items before we call startBinding() below.
2612 unbindWorkspaceItemsOnMainThread();
2613
2614 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2616 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2617 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2618 new ArrayList<LauncherAppWidgetInfo>();
2619 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2620 new ArrayList<LauncherAppWidgetInfo>();
2621 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2622 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2623
Winson Chung9b9fb962013-11-15 15:39:34 -08002624 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002625 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002626 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002628 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002629 otherFolders);
2630 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2631 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2632
2633 // Tell the workspace that we're about to start binding items
2634 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002635 public void run() {
2636 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2637 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002638 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002639 }
2640 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002641 };
Winson Chung81b52252012-08-27 15:34:29 -07002642 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002643
Adam Cohendcd297f2013-06-18 13:13:40 -07002644 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2645
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002646 // Load items on the current page
2647 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2648 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002649 if (isLoadingSynchronously) {
2650 r = new Runnable() {
2651 public void run() {
2652 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002653 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002654 callbacks.onPageBoundSynchronously(currentScreen);
2655 }
2656 }
2657 };
Winson Chung81b52252012-08-27 15:34:29 -07002658 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002659 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002660
Winson Chung4a2afa32012-07-19 14:53:05 -07002661 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2662 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002663 synchronized (mDeferredBindRunnables) {
2664 mDeferredBindRunnables.clear();
2665 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002667 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668
2669 // Tell the workspace that we're done binding items
2670 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002671 public void run() {
2672 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2673 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002674 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002675 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002676
Winson Chung98e030b2012-05-07 16:01:11 -07002677 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002678 if (DEBUG_LOADERS) {
2679 Log.d(TAG, "bound workspace in "
2680 + (SystemClock.uptimeMillis()-t) + "ms");
2681 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002682
2683 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002684 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002685 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002686 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002687 synchronized (mDeferredBindRunnables) {
2688 mDeferredBindRunnables.add(r);
2689 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002690 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002691 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002692 }
Joe Onorato36115782010-06-17 13:28:48 -04002693 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002694
Joe Onorato36115782010-06-17 13:28:48 -04002695 private void loadAndBindAllApps() {
2696 if (DEBUG_LOADERS) {
2697 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2698 }
2699 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002700 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002701 synchronized (LoaderTask.this) {
2702 if (mStopped) {
2703 return;
2704 }
2705 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002706 }
Joe Onorato36115782010-06-17 13:28:48 -04002707 } else {
2708 onlyBindAllApps();
2709 }
2710 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002711
Joe Onorato36115782010-06-17 13:28:48 -04002712 private void onlyBindAllApps() {
2713 final Callbacks oldCallbacks = mCallbacks.get();
2714 if (oldCallbacks == null) {
2715 // This launcher has exited and nobody bothered to tell us. Just bail.
2716 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2717 return;
2718 }
2719
2720 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002721 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002722 final ArrayList<AppInfo> list
2723 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002724 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002725 public void run() {
2726 final long t = SystemClock.uptimeMillis();
2727 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2728 if (callbacks != null) {
2729 callbacks.bindAllApplications(list);
2730 }
2731 if (DEBUG_LOADERS) {
2732 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2733 + (SystemClock.uptimeMillis()-t) + "ms");
2734 }
2735 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002736 };
2737 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002738 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002739 r.run();
2740 } else {
2741 mHandler.post(r);
2742 }
Joe Onorato36115782010-06-17 13:28:48 -04002743 }
2744
Winson Chung64359a52013-07-08 17:17:08 -07002745 private void loadAllApps() {
2746 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002747
Joe Onorato36115782010-06-17 13:28:48 -04002748 final Callbacks oldCallbacks = mCallbacks.get();
2749 if (oldCallbacks == null) {
2750 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002751 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002752 return;
2753 }
2754
2755 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2756 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2757
Kenny Guyed131872014-04-30 03:02:21 +01002758 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2759
Winson Chung64359a52013-07-08 17:17:08 -07002760 // Clear the list of apps
2761 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002762 for (UserHandleCompat user : profiles) {
2763 // Query for the set of apps
2764 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2765 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2766 if (DEBUG_LOADERS) {
2767 Log.d(TAG, "getActivityList took "
2768 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2769 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2770 }
2771 // Fail if we don't have any apps
2772 if (apps == null || apps.isEmpty()) {
2773 return;
2774 }
2775 // Sort the applications by name
2776 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2777 Collections.sort(apps,
2778 new LauncherModel.ShortcutNameComparator(mLabelCache));
2779 if (DEBUG_LOADERS) {
2780 Log.d(TAG, "sort took "
2781 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2782 }
Joe Onorato36115782010-06-17 13:28:48 -04002783
Kenny Guyed131872014-04-30 03:02:21 +01002784 // Create the ApplicationInfos
2785 for (int i = 0; i < apps.size(); i++) {
2786 LauncherActivityInfoCompat app = apps.get(i);
2787 // This builds the icon bitmaps.
2788 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2789 }
Winson Chung64359a52013-07-08 17:17:08 -07002790 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002791 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002792 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2793 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002794
2795 // Post callback on main thread
2796 mHandler.post(new Runnable() {
2797 public void run() {
2798 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002799 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002800 if (callbacks != null) {
2801 callbacks.bindAllApplications(added);
2802 if (DEBUG_LOADERS) {
2803 Log.d(TAG, "bound " + added.size() + " apps in "
2804 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2805 }
2806 } else {
2807 Log.i(TAG, "not binding apps: no Launcher activity");
2808 }
2809 }
2810 });
2811
Joe Onorato36115782010-06-17 13:28:48 -04002812 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002813 Log.d(TAG, "Icons processed in "
2814 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002815 }
2816 }
2817
2818 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002819 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002820 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2821 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2822 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2823 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2824 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2825 }
Joe Onorato36115782010-06-17 13:28:48 -04002826 }
2827 }
2828
2829 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002830 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002831 }
2832
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002833 private class AppsAvailabilityCheck extends BroadcastReceiver {
2834
2835 @Override
2836 public void onReceive(Context context, Intent intent) {
2837 synchronized (sBgLock) {
2838 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2839 .getInstance(mApp.getContext());
2840 ArrayList<String> packagesRemoved;
2841 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2842 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002843 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002844 for (String pkg : entry.getValue()) {
2845 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2846 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2847 packagesRemoved.add(pkg);
2848 }
2849 }
2850 if (!packagesRemoved.isEmpty()) {
2851 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2852 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2853 }
2854 }
2855 sPendingPackages.clear();
2856 }
2857 }
2858 }
2859
Joe Onorato36115782010-06-17 13:28:48 -04002860 private class PackageUpdatedTask implements Runnable {
2861 int mOp;
2862 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002863 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002864
2865 public static final int OP_NONE = 0;
2866 public static final int OP_ADD = 1;
2867 public static final int OP_UPDATE = 2;
2868 public static final int OP_REMOVE = 3; // uninstlled
2869 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2870
2871
Kenny Guyed131872014-04-30 03:02:21 +01002872 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002873 mOp = op;
2874 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002875 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002876 }
2877
2878 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002879 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002880
2881 final String[] packages = mPackages;
2882 final int N = packages.length;
2883 switch (mOp) {
2884 case OP_ADD:
2885 for (int i=0; i<N; i++) {
2886 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002887 mIconCache.remove(packages[i], mUser);
2888 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002889 }
2890 break;
2891 case OP_UPDATE:
2892 for (int i=0; i<N; i++) {
2893 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002894 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002895 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002896 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002897 }
2898 break;
2899 case OP_REMOVE:
2900 case OP_UNAVAILABLE:
2901 for (int i=0; i<N; i++) {
2902 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002903 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002904 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002905 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002906 }
2907 break;
2908 }
2909
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002910 ArrayList<AppInfo> added = null;
2911 ArrayList<AppInfo> modified = null;
2912 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002913
Adam Cohen487f7dd2012-06-28 18:12:10 -07002914 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002915 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002916 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002917 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002918 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002919 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002920 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002921 }
Winson Chung5d55f332012-07-16 20:45:03 -07002922 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002923 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002924 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002925 }
2926
Joe Onorato36115782010-06-17 13:28:48 -04002927 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2928 if (callbacks == null) {
2929 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2930 return;
2931 }
2932
2933 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002934 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002935 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002936 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002937 addAndBindAddedWorkspaceApps(context, addedInfos);
2938 } else {
2939 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002940 }
Joe Onorato36115782010-06-17 13:28:48 -04002941 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002942
Joe Onorato36115782010-06-17 13:28:48 -04002943 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002944 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002945
2946 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002947 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002948 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002949 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002950 for (ItemInfo i : infos) {
2951 if (isShortcutInfoUpdateable(i)) {
2952 ShortcutInfo info = (ShortcutInfo) i;
2953 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002954 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002955 updateItemInDatabase(context, info);
2956 }
2957 }
2958 }
2959
Joe Onorato36115782010-06-17 13:28:48 -04002960 mHandler.post(new Runnable() {
2961 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002962 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2963 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002964 callbacks.bindAppsUpdated(modifiedFinal);
2965 }
2966 }
2967 });
2968 }
Winson Chung83892cc2013-05-01 16:53:33 -07002969
Winson Chungdf95eb12013-10-16 14:57:07 -07002970 final ArrayList<String> removedPackageNames =
2971 new ArrayList<String>();
2972 if (mOp == OP_REMOVE) {
2973 // Mark all packages in the broadcast to be removed
2974 removedPackageNames.addAll(Arrays.asList(packages));
2975 } else if (mOp == OP_UPDATE) {
2976 // Mark disabled packages in the broadcast to be removed
2977 final PackageManager pm = context.getPackageManager();
2978 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002979 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002980 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002981 }
2982 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002983 }
2984 // Remove all the components associated with this package
2985 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002986 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002987 for (ItemInfo i : infos) {
2988 deleteItemFromDatabase(context, i);
2989 }
2990 }
2991 // Remove all the specific components
2992 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002993 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002994 for (ItemInfo i : infos) {
2995 deleteItemFromDatabase(context, i);
2996 }
2997 }
2998 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2999 // Remove any queued items from the install queue
3000 String spKey = LauncherAppState.getSharedPreferencesKey();
3001 SharedPreferences sp =
3002 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3003 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3004 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003005 mHandler.post(new Runnable() {
3006 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003007 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3008 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003009 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003010 }
3011 }
3012 });
Joe Onoratobe386092009-11-17 17:32:16 -08003013 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003014
Michael Jurkac402cd92013-05-20 15:49:32 +02003015 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003016 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003017 mHandler.post(new Runnable() {
3018 @Override
3019 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003020 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3021 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003022 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003023 }
3024 }
3025 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003026
3027 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003028 mHandler.post(new Runnable() {
3029 public void run() {
3030 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3031 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003032 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003033 }
3034 }
3035 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003036 }
3037 }
3038
Michael Jurkac402cd92013-05-20 15:49:32 +02003039 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3040 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3041 PackageManager packageManager = context.getPackageManager();
3042 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
3043 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
3044 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3045 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
3046 Collections.sort(widgetsAndShortcuts,
3047 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
3048 return widgetsAndShortcuts;
3049 }
3050
Kenny Guyed131872014-04-30 03:02:21 +01003051 private static boolean isPackageDisabled(Context context, String packageName,
3052 UserHandleCompat user) {
3053 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3054 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003055 }
Adam Cohen556f6132014-01-15 15:18:08 -08003056
Kenny Guyed131872014-04-30 03:02:21 +01003057 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3058 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003059 if (cn == null) {
3060 return false;
3061 }
Kenny Guyed131872014-04-30 03:02:21 +01003062 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3063 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003064 return false;
3065 }
Kenny Guyed131872014-04-30 03:02:21 +01003066 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003067 }
3068
Adam Cohena28b78e2014-05-20 17:03:04 -07003069 public static boolean isValidPackage(Context context, String packageName,
3070 UserHandleCompat user) {
3071 if (packageName == null) {
3072 return false;
3073 }
3074 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3075 return launcherApps.isPackageEnabledForProfile(packageName, user);
3076 }
3077
Joe Onorato9c1289c2009-08-17 11:03:03 -04003078 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003079 * Make an ShortcutInfo object for a restored application or shortcut item that points
3080 * to a package that is not yet installed on the system.
3081 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003082 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003083 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003084 if (cursor != null) {
3085 info.title = cursor.getString(titleIndex);
3086 } else {
3087 info.title = "";
3088 }
Kenny Guyed131872014-04-30 03:02:21 +01003089 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003090 info.contentDescription = mUserManager.getBadgedLabelForUser(
3091 info.title.toString(), info.user);
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003092 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user, false));
Chris Wrenf4d08112014-01-16 18:13:56 -05003093 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003094 info.restoredIntent = intent;
Sunny Goyal34846382014-07-09 00:09:28 -07003095 info.wasPromise = true;
Chris Wren40c5ed32014-06-24 18:24:23 -04003096 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003097 return info;
3098 }
3099
3100 /**
3101 * Make an Intent object for a restored application or shortcut item that points
3102 * to the market page for the item.
3103 */
3104 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003105 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05003106 ComponentName componentName = intent.getComponent();
3107 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
3108 Uri marketUri = new Uri.Builder()
3109 .scheme("market")
3110 .authority("details")
3111 .appendQueryParameter("id", componentName.getPackageName())
3112 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05003113 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05003114 marketIntent.setData(marketUri);
3115 return marketIntent;
3116 }
3117
3118 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003119 * This is called from the code that adds shortcuts from the intent receiver. This
3120 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003121 */
Kenny Guyed131872014-04-30 03:02:21 +01003122 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3123 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003124 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003125 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003126
Joe Onorato56d82912010-03-07 14:32:10 -05003127 /**
3128 * Make an ShortcutInfo object for a shortcut that is an application.
3129 *
3130 * If c is not null, then it will be used to fill in missing data like the title and icon.
3131 */
Kenny Guyed131872014-04-30 03:02:21 +01003132 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3133 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003134 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003135 if (user == null) {
3136 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003137 return null;
3138 }
3139
Kenny Guyed131872014-04-30 03:02:21 +01003140 ComponentName componentName = intent.getComponent();
3141 if (componentName == null) {
3142 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3143 return null;
3144 }
3145
3146 Intent newIntent = new Intent(intent.getAction(), null);
3147 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3148 newIntent.setComponent(componentName);
3149 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003150 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003151 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3152 return null;
3153 }
3154
3155 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003156
Joe Onorato56d82912010-03-07 14:32:10 -05003157 // the resource -- This may implicitly give us back the fallback icon,
3158 // but don't worry about that. All we're doing with usingFallbackIcon is
3159 // to avoid saving lots of copies of that in the database, and most apps
3160 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003161 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003162
Joe Onorato56d82912010-03-07 14:32:10 -05003163 // the db
3164 if (icon == null) {
3165 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003166 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003167 }
3168 }
3169 // the fallback icon
3170 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003171 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003172 info.usingFallbackIcon = true;
3173 }
3174 info.setIcon(icon);
3175
Kenny Guyed131872014-04-30 03:02:21 +01003176 // From the cache.
3177 if (labelCache != null) {
3178 info.title = labelCache.get(componentName);
3179 }
3180
Joe Onorato56d82912010-03-07 14:32:10 -05003181 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003182 if (info.title == null && lai != null) {
3183 info.title = lai.getLabel();
3184 if (labelCache != null) {
3185 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003186 }
Joe Onorato56d82912010-03-07 14:32:10 -05003187 }
3188 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003189 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003190 if (c != null) {
3191 info.title = c.getString(titleIndex);
3192 }
3193 }
3194 // fall back to the class name of the activity
3195 if (info.title == null) {
3196 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003197 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003198 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003199 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003200 info.contentDescription = mUserManager.getBadgedLabelForUser(
3201 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003202 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003203 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003204
Winson Chung64359a52013-07-08 17:17:08 -07003205 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3206 ItemInfoFilter f) {
3207 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3208 for (ItemInfo i : infos) {
3209 if (i instanceof ShortcutInfo) {
3210 ShortcutInfo info = (ShortcutInfo) i;
3211 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003212 if (info.restoredIntent != null) {
3213 cn = info.restoredIntent.getComponent();
3214 }
Winson Chung64359a52013-07-08 17:17:08 -07003215 if (cn != null && f.filterItem(null, info, cn)) {
3216 filtered.add(info);
3217 }
3218 } else if (i instanceof FolderInfo) {
3219 FolderInfo info = (FolderInfo) i;
3220 for (ShortcutInfo s : info.contents) {
3221 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003222 if (s.restoredIntent != null) {
3223 cn = s.restoredIntent.getComponent();
3224 }
Winson Chung64359a52013-07-08 17:17:08 -07003225 if (cn != null && f.filterItem(info, s, cn)) {
3226 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003227 }
3228 }
Winson Chung64359a52013-07-08 17:17:08 -07003229 } else if (i instanceof LauncherAppWidgetInfo) {
3230 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3231 ComponentName cn = info.providerName;
3232 if (cn != null && f.filterItem(null, info, cn)) {
3233 filtered.add(info);
3234 }
Winson Chung8a435102012-08-30 17:16:53 -07003235 }
3236 }
Winson Chung64359a52013-07-08 17:17:08 -07003237 return new ArrayList<ItemInfo>(filtered);
3238 }
3239
Kenny Guyed131872014-04-30 03:02:21 +01003240 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3241 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003242 ItemInfoFilter filter = new ItemInfoFilter() {
3243 @Override
3244 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003245 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003246 }
3247 };
3248 return filterItemInfos(sBgItemsIdMap.values(), filter);
3249 }
3250
Kenny Guyed131872014-04-30 03:02:21 +01003251 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3252 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003253 ItemInfoFilter filter = new ItemInfoFilter() {
3254 @Override
3255 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003256 if (info.user == null) {
3257 return cn.equals(cname);
3258 } else {
3259 return cn.equals(cname) && info.user.equals(user);
3260 }
Winson Chung64359a52013-07-08 17:17:08 -07003261 }
3262 };
3263 return filterItemInfos(sBgItemsIdMap.values(), filter);
3264 }
3265
3266 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3267 if (i instanceof ShortcutInfo) {
3268 ShortcutInfo info = (ShortcutInfo) i;
3269 // We need to check for ACTION_MAIN otherwise getComponent() might
3270 // return null for some shortcuts (for instance, for shortcuts to
3271 // web pages.)
3272 Intent intent = info.intent;
3273 ComponentName name = intent.getComponent();
3274 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3275 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3276 return true;
3277 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003278 // placeholder shortcuts get special treatment, let them through too.
3279 if (info.getRestoredIntent() != null) {
3280 return true;
3281 }
Winson Chung64359a52013-07-08 17:17:08 -07003282 }
3283 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003284 }
3285
3286 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003287 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003288 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003289 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003290 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3291 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003292
Joe Onorato56d82912010-03-07 14:32:10 -05003293 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003294 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003295 // Non-app shortcuts are only supported for current user.
3296 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003297 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003298
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003299 // TODO: If there's an explicit component and we can't install that, delete it.
3300
Joe Onorato56d82912010-03-07 14:32:10 -05003301 info.title = c.getString(titleIndex);
3302
Joe Onorato9c1289c2009-08-17 11:03:03 -04003303 int iconType = c.getInt(iconTypeIndex);
3304 switch (iconType) {
3305 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3306 String packageName = c.getString(iconPackageIndex);
3307 String resourceName = c.getString(iconResourceIndex);
3308 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003309 info.customIcon = false;
3310 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003311 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003312 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003313 if (resources != null) {
3314 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003315 icon = Utilities.createIconBitmap(
3316 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003317 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003318 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003319 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003320 }
Joe Onorato56d82912010-03-07 14:32:10 -05003321 // the db
3322 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003323 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003324 }
3325 // the fallback icon
3326 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003327 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003328 info.usingFallbackIcon = true;
3329 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003330 break;
3331 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003332 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003333 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003334 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003335 info.customIcon = false;
3336 info.usingFallbackIcon = true;
3337 } else {
3338 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003339 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003340 break;
3341 default:
Kenny Guyed131872014-04-30 03:02:21 +01003342 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003343 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003344 info.customIcon = false;
3345 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003346 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003347 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003348 return info;
3349 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003350
Michael Jurka931dc972011-08-05 15:08:15 -07003351 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003352 @SuppressWarnings("all") // suppress dead code warning
3353 final boolean debug = false;
3354 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003355 Log.d(TAG, "getIconFromCursor app="
3356 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3357 }
3358 byte[] data = c.getBlob(iconIndex);
3359 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003360 return Utilities.createIconBitmap(
3361 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003362 } catch (Exception e) {
3363 return null;
3364 }
3365 }
3366
Winson Chung3d503fb2011-07-13 17:25:49 -07003367 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3368 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003369 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003370 if (info == null) {
3371 return null;
3372 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003373 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003374
3375 return info;
3376 }
3377
Winson Chunga9abd0e2010-10-27 17:18:37 -07003378 /**
Winson Chung55cef262010-10-28 14:14:18 -07003379 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3380 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003381 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003382 ComponentName component) {
3383 List<AppWidgetProviderInfo> widgets =
3384 AppWidgetManager.getInstance(context).getInstalledProviders();
3385 for (AppWidgetProviderInfo info : widgets) {
3386 if (info.provider.equals(component)) {
3387 return info;
3388 }
3389 }
3390 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003391 }
3392
Winson Chung68846fd2010-10-29 11:00:27 -07003393 /**
3394 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3395 */
3396 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3397 final PackageManager packageManager = context.getPackageManager();
3398 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3399 new ArrayList<WidgetMimeTypeHandlerData>();
3400
3401 final Intent supportsIntent =
3402 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3403 supportsIntent.setType(mimeType);
3404
3405 // Create a set of widget configuration components that we can test against
3406 final List<AppWidgetProviderInfo> widgets =
3407 AppWidgetManager.getInstance(context).getInstalledProviders();
3408 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3409 new HashMap<ComponentName, AppWidgetProviderInfo>();
3410 for (AppWidgetProviderInfo info : widgets) {
3411 configurationComponentToWidget.put(info.configure, info);
3412 }
3413
3414 // Run through each of the intents that can handle this type of clip data, and cross
3415 // reference them with the components that are actual configuration components
3416 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3417 PackageManager.MATCH_DEFAULT_ONLY);
3418 for (ResolveInfo info : activities) {
3419 final ActivityInfo activityInfo = info.activityInfo;
3420 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3421 activityInfo.name);
3422 if (configurationComponentToWidget.containsKey(infoComponent)) {
3423 supportedConfigurationActivities.add(
3424 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3425 configurationComponentToWidget.get(infoComponent)));
3426 }
3427 }
3428 return supportedConfigurationActivities;
3429 }
3430
Winson Chunga9abd0e2010-10-27 17:18:37 -07003431 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003432 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3433 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3434 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3435
Adam Cohend9198822011-11-22 16:42:47 -08003436 if (intent == null) {
3437 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3438 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3439 return null;
3440 }
3441
Joe Onorato0589f0f2010-02-08 13:44:00 -08003442 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003443 boolean customIcon = false;
3444 ShortcutIconResource iconResource = null;
3445
3446 if (bitmap != null && bitmap instanceof Bitmap) {
3447 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003448 customIcon = true;
3449 } else {
3450 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3451 if (extra != null && extra instanceof ShortcutIconResource) {
3452 try {
3453 iconResource = (ShortcutIconResource) extra;
3454 final PackageManager packageManager = context.getPackageManager();
3455 Resources resources = packageManager.getResourcesForApplication(
3456 iconResource.packageName);
3457 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003458 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003459 mIconCache.getFullResIcon(resources, id),
3460 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003461 } catch (Exception e) {
3462 Log.w(TAG, "Could not load shortcut icon: " + extra);
3463 }
3464 }
3465 }
3466
Michael Jurkac9d95c52011-08-29 14:03:34 -07003467 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003468
Kenny Guyed131872014-04-30 03:02:21 +01003469 // Only support intents for current user for now. Intents sent from other
3470 // users wouldn't get here without intent forwarding anyway.
3471 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003472 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003473 if (fallbackIcon != null) {
3474 icon = fallbackIcon;
3475 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003476 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003477 info.usingFallbackIcon = true;
3478 }
Joe Onorato56d82912010-03-07 14:32:10 -05003479 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003480 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003481
Joe Onorato0589f0f2010-02-08 13:44:00 -08003482 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003483 info.contentDescription = mUserManager.getBadgedLabelForUser(
3484 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003485 info.intent = intent;
3486 info.customIcon = customIcon;
3487 info.iconResource = iconResource;
3488
3489 return info;
3490 }
3491
Winson Chungaac01e12011-08-17 10:37:13 -07003492 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3493 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003494 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003495 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003496 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003497 }
Joe Onorato56d82912010-03-07 14:32:10 -05003498 // If this icon doesn't have a custom icon, check to see
3499 // what's stored in the DB, and if it doesn't match what
3500 // we're going to show, store what we are going to show back
3501 // into the DB. We do this so when we're loading, if the
3502 // package manager can't find an icon (for example because
3503 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003504 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003505 cache.put(info, c.getBlob(iconIndex));
3506 return true;
3507 }
3508 return false;
3509 }
3510 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3511 boolean needSave = false;
3512 try {
3513 if (data != null) {
3514 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3515 Bitmap loaded = info.getIcon(mIconCache);
3516 needSave = !saved.sameAs(loaded);
3517 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003518 needSave = true;
3519 }
Winson Chungaac01e12011-08-17 10:37:13 -07003520 } catch (Exception e) {
3521 needSave = true;
3522 }
3523 if (needSave) {
3524 Log.d(TAG, "going to save icon bitmap for info=" + info);
3525 // This is slower than is ideal, but this only happens once
3526 // or when the app is updated with a new icon.
3527 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003528 }
3529 }
3530
Joe Onorato9c1289c2009-08-17 11:03:03 -04003531 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003532 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003533 * or make a new one.
3534 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003535 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003536 // See if a placeholder was created for us already
3537 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003538 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003539 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003540 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003541 folders.put(id, folderInfo);
3542 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003543 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003544 }
3545
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003546 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003547 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003548 return new Comparator<AppInfo>() {
3549 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003550 if (a.user.equals(b.user)) {
3551 int result = collator.compare(a.title.toString().trim(),
3552 b.title.toString().trim());
3553 if (result == 0) {
3554 result = a.componentName.compareTo(b.componentName);
3555 }
3556 return result;
3557 } else {
3558 // TODO Need to figure out rules for sorting
3559 // profiles, this puts work second.
3560 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003561 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003562 }
Winson Chung11904872012-09-17 16:58:46 -07003563 };
3564 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003565 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3566 = new Comparator<AppInfo>() {
3567 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003568 if (a.firstInstallTime < b.firstInstallTime) return 1;
3569 if (a.firstInstallTime > b.firstInstallTime) return -1;
3570 return 0;
3571 }
3572 };
Winson Chung11904872012-09-17 16:58:46 -07003573 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3574 final Collator collator = Collator.getInstance();
3575 return new Comparator<AppWidgetProviderInfo>() {
3576 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003577 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003578 }
3579 };
3580 }
Winson Chung5308f242011-08-18 12:12:41 -07003581 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3582 if (info.activityInfo != null) {
3583 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3584 } else {
3585 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3586 }
3587 }
Kenny Guyed131872014-04-30 03:02:21 +01003588 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003589 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003590 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003591 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003592 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003593 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003594 }
Kenny Guyed131872014-04-30 03:02:21 +01003595 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003596 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003597 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003598 }
Kenny Guyed131872014-04-30 03:02:21 +01003599 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003600 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003601 ComponentName keyA = a.getComponentName();
3602 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003603 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003604 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003605 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003606 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003607
Winson Chung5308f242011-08-18 12:12:41 -07003608 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003609 }
Winson Chung5308f242011-08-18 12:12:41 -07003610 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003611 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003612 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003613 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003614
Winson Chung5308f242011-08-18 12:12:41 -07003615 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003616 }
Winson Chung11904872012-09-17 16:58:46 -07003617 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003618 }
3619 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003620 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003621 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003622 private PackageManager mPackageManager;
3623 private HashMap<Object, String> mLabelCache;
3624 WidgetAndShortcutNameComparator(PackageManager pm) {
3625 mPackageManager = pm;
3626 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003627 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003628 }
3629 public final int compare(Object a, Object b) {
3630 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003631 if (mLabelCache.containsKey(a)) {
3632 labelA = mLabelCache.get(a);
3633 } else {
3634 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003635 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003636 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003637 mLabelCache.put(a, labelA);
3638 }
3639 if (mLabelCache.containsKey(b)) {
3640 labelB = mLabelCache.get(b);
3641 } else {
3642 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003643 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003644 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003645 mLabelCache.put(b, labelB);
3646 }
Winson Chung11904872012-09-17 16:58:46 -07003647 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003648 }
3649 };
Joe Onoratobe386092009-11-17 17:32:16 -08003650
Sunny Goyal651077b2014-06-30 14:15:31 -07003651 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3652 return (provider != null) && (provider.provider != null)
3653 && (provider.provider.getPackageName() != null);
3654 }
3655
Joe Onoratobe386092009-11-17 17:32:16 -08003656 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003657 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003658 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3659 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3660 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3661 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003662 if (mLoaderTask != null) {
3663 mLoaderTask.dumpState();
3664 } else {
3665 Log.d(TAG, "mLoaderTask=null");
3666 }
Joe Onoratobe386092009-11-17 17:32:16 -08003667 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003668}