blob: e115bf11c7db0162f10966dd612cf1b502cbee83 [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;
58import com.android.launcher3.compat.UserHandleCompat;
59import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080060
Michael Jurkac2f801e2011-07-12 14:19:46 -070061import java.lang.ref.WeakReference;
62import java.net.URISyntaxException;
63import java.text.Collator;
64import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070065import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070066import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070067import java.util.Collections;
68import java.util.Comparator;
69import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070070import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070071import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070072import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070073import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070074import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070075import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070076import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040086 private static final boolean DEBUG_RECEIVER = true; // STOPSHIP(cwren) temporary for debugging
87
Joe Onorato9c1289c2009-08-17 11:03:03 -040088 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070089
Daniel Sandler8707e0f2013-08-15 15:54:18 -070090 // true = use a "More Apps" folder for non-workspace apps on upgrade
91 // false = strew non-workspace apps across the workspace on upgrade
92 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050093 public static final int LOADER_FLAG_NONE = 0;
94 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
95 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
96
Joe Onorato36115782010-06-17 13:28:48 -040097 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050098 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080099
Winson Chungee055712013-07-30 14:46:24 -0700100 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800101 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400102
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400103 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private final Object mLock = new Object();
105 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400106 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700107 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200108 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Winson Chung81b52252012-08-27 15:34:29 -0700110 // Specific runnable types that are run on the main thread deferred handler, this allows us to
111 // clear all queued binding runnables when the Launcher activity is destroyed.
112 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
113 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
114
Jason Monkbbe1e242014-05-16 17:37:34 -0400115 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700116
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700117 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
118 static {
119 sWorkerThread.start();
120 }
121 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
122
Joe Onoratocc67f472010-06-08 10:54:30 -0700123 // We start off with everything not loaded. After that, we assume that
124 // our monitoring of the package manager provides all updates and we never
125 // need to do a requery. These are only ever touched from the loader thread.
126 private boolean mWorkspaceLoaded;
127 private boolean mAllAppsLoaded;
128
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700129 // When we are loading pages synchronously, we can't just post the binding of items on the side
130 // pages as this delays the rotation process. Instead, we wait for a callback from the first
131 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
132 // a normal load, we also clear this set of Runnables.
133 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
134
Joe Onorato9c1289c2009-08-17 11:03:03 -0400135 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700138 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800139
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700140 // The lock that must be acquired before referencing any static bg data structures. Unlike
141 // other locks, this one can generally be held long-term because we never expect any of these
142 // static data structures to be referenced outside of the worker thread except on the first
143 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700144 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
151 // created by LauncherModel that are directly on the home screen (however, no widgets or
152 // shortcuts within folders).
153 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
156 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 new ArrayList<LauncherAppWidgetInfo>();
158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
160 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
163 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700164
165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700168 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700169 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
170 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700172 // </ only access in worker thread >
173
174 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175
Reena Lee99a73f32011-10-24 17:27:37 -0700176 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700177
Kenny Guyed131872014-04-30 03:02:21 +0100178 private final LauncherAppsCompat mLauncherApps;
179 private final UserManagerCompat mUserManager;
180
Joe Onorato9c1289c2009-08-17 11:03:03 -0400181 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700182 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public int getCurrentWorkspaceScreen();
184 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700185 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
186 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700187 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500189 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700190 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400191 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200192 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700193 public void bindAppsAdded(ArrayList<Long> newScreens,
194 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700195 ArrayList<ItemInfo> addAnimated,
196 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200197 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500198 public void updatePackageState(String pkgName, int state);
Winson Chung83892cc2013-05-01 16:53:33 -0700199 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100200 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200201 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100202 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700203 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700204 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700205 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400206 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800207
Winson Chung64359a52013-07-08 17:17:08 -0700208 public interface ItemInfoFilter {
209 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
210 }
211
Bjorn Bringert1307f632013-10-03 22:31:03 +0100212 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800213 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400214
Winson Chungee055712013-07-30 14:46:24 -0700215 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700216 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400217 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
218 // resource string.
219 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
220 ProviderInfo providerInfo =
221 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
222 ProviderInfo redirectProvider =
223 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700224
225 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400226 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700227
228 if (mOldContentProviderExists) {
229 Log.d(TAG, "Old launcher provider exists.");
230 } else {
231 Log.d(TAG, "Old launcher provider does not exist.");
232 }
233
Daniel Sandlere4f98912013-06-25 15:13:26 -0400234 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100235 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800236 mIconCache = iconCache;
237
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400238 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700239 Configuration config = res.getConfiguration();
240 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100241 mLauncherApps = LauncherAppsCompat.getInstance(context);
242 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800243 }
244
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700245 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
246 * posted on the main thread handler. */
247 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700248 runOnMainThread(r, 0);
249 }
250 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700251 if (sWorkerThread.getThreadId() == Process.myTid()) {
252 // If we are on the worker thread, post onto the main handler
253 mHandler.post(r);
254 } else {
255 r.run();
256 }
257 }
258
259 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
260 * posted on the worker thread handler. */
261 private static void runOnWorkerThread(Runnable r) {
262 if (sWorkerThread.getThreadId() == Process.myTid()) {
263 r.run();
264 } else {
265 // If we are not on the worker thread, then post to the worker handler
266 sWorker.post(r);
267 }
268 }
269
Winson Chunge43a1e72014-01-15 10:33:02 -0800270 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
271 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800272 }
273
Winson Chungc9168342013-06-26 14:54:55 -0700274 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
275 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700276 LauncherAppState app = LauncherAppState.getInstance();
277 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
278 final int xCount = (int) grid.numColumns;
279 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700280 boolean[][] occupied = new boolean[xCount][yCount];
281
282 int cellX, cellY, spanX, spanY;
283 for (int i = 0; i < items.size(); ++i) {
284 final ItemInfo item = items.get(i);
285 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
286 if (item.screenId == screen) {
287 cellX = item.cellX;
288 cellY = item.cellY;
289 spanX = item.spanX;
290 spanY = item.spanY;
291 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
292 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
293 occupied[x][y] = true;
294 }
295 }
296 }
297 }
298 }
299
300 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
301 }
302 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700303 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700304 int firstScreenIndex,
305 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700306 // Lock on the app so that we don't try and get the items while apps are being added
307 LauncherAppState app = LauncherAppState.getInstance();
308 LauncherModel model = app.getModel();
309 boolean found = false;
310 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700311 if (sWorkerThread.getThreadId() != Process.myTid()) {
312 // Flush the LauncherModel worker thread, so that if we just did another
313 // processInstallShortcut, we give it time for its shortcut to get added to the
314 // database (getItemsInLocalCoordinates reads the database)
315 model.flushWorkerThread();
316 }
Winson Chungc9168342013-06-26 14:54:55 -0700317 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700318
319 // Try adding to the workspace screens incrementally, starting at the default or center
320 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700321 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
322 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700323 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700324 int[] tmpCoordinates = new int[2];
325 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700326 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700327 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700328 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700329 }
330 }
331 }
Winson Chungc9168342013-06-26 14:54:55 -0700332 return null;
333 }
334
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500335 public void setPackageState(final String pkgName, final int state) {
336 // Process the updated package state
337 Runnable r = new Runnable() {
338 public void run() {
339 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
340 if (callbacks != null) {
341 callbacks.updatePackageState(pkgName, state);
342 }
343 }
344 };
345 mHandler.post(r);
346 }
347
Adam Cohen76a47a12014-02-05 11:47:43 -0800348 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
349 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
350
351 if (allAppsApps == null) {
352 throw new RuntimeException("allAppsApps must not be null");
353 }
354 if (allAppsApps.isEmpty()) {
355 return;
356 }
357
Chris Wrenb6d4c282014-01-27 14:17:08 -0500358 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
359 Iterator<AppInfo> iter = allAppsApps.iterator();
360 while (iter.hasNext()) {
361 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100362 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500363 restoredAppsFinal.add((AppInfo) a);
364 }
365 }
366
Adam Cohen76a47a12014-02-05 11:47:43 -0800367 // Process the newly added applications and add them to the database first
368 Runnable r = new Runnable() {
369 public void run() {
370 runOnMainThread(new Runnable() {
371 public void run() {
372 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
373 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500374 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500375 for (AppInfo info : restoredAppsFinal) {
376 final Intent intent = info.getIntent();
377 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100378 mIconCache.deletePreloadedIcon(intent.getComponent(),
379 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500380 }
381 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500382 callbacks.bindAppsUpdated(restoredAppsFinal);
383 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500384 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800385 }
386 }
387 });
388 }
389 };
390 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700391 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800392
393 public void addAndBindAddedWorkspaceApps(final Context context,
394 final ArrayList<ItemInfo> workspaceApps) {
395 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
396
397 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800398 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
399 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800400 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700401 return;
Winson Chung997a9232013-07-24 15:33:46 -0700402 }
Winson Chung64359a52013-07-08 17:17:08 -0700403 // Process the newly added applications and add them to the database first
404 Runnable r = new Runnable() {
405 public void run() {
406 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
407 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500408 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700409
Winson Chung76828c82013-08-19 15:43:29 -0700410 // Get the list of workspace screens. We need to append to this list and
411 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
412 // called.
413 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
414 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
415 for (Integer i : orderedScreens.keySet()) {
416 long screenId = orderedScreens.get(i);
417 workspaceScreens.add(screenId);
418 }
419
Winson Chung64359a52013-07-08 17:17:08 -0700420 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700421 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700422 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700423 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700424 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700425 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700426
427 // Short-circuit this logic if the icon exists somewhere on the workspace
428 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500429 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
430 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100431 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500432 restoredAppsFinal.add((AppInfo) a);
433 }
Winson Chung64359a52013-07-08 17:17:08 -0700434 continue;
435 }
436
Winson Chung87412982013-10-03 18:34:14 -0700437 // Add this icon to the db, creating a new page if necessary. If there
438 // is only the empty page then we just add items to the first page.
439 // Otherwise, we add them to the next pages.
440 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700441 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700442 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700443 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200444 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700445
446 // If we can't find a valid position, then just add a new screen.
447 // This takes time so we need to re-queue the add until the new
448 // page is added. Create as many screens as necessary to satisfy
449 // the startSearchPageIndex.
450 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700451 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700452 while (numPagesToAdd > 0) {
453 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700454 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700455 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 addedWorkspaceScreensFinal.add(screenId);
457 numPagesToAdd--;
458 }
Winson Chung76828c82013-08-19 15:43:29 -0700459
Winson Chung64359a52013-07-08 17:17:08 -0700460 // Find the coordinate again
461 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700462 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700463 }
464 if (coords == null) {
465 throw new RuntimeException("Coordinates should not be null");
466 }
467
Winson Chung997a9232013-07-24 15:33:46 -0700468 ShortcutInfo shortcutInfo;
469 if (a instanceof ShortcutInfo) {
470 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200471 } else if (a instanceof AppInfo) {
472 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700473 } else {
474 throw new RuntimeException("Unexpected info type");
475 }
Winson Chung94d67682013-09-25 16:29:40 -0700476
Winson Chung64359a52013-07-08 17:17:08 -0700477 // Add the shortcut to the db
478 addItemToDatabase(context, shortcutInfo,
479 LauncherSettings.Favorites.CONTAINER_DESKTOP,
480 coords.first, coords.second[0], coords.second[1], false);
481 // Save the ShortcutInfo for binding in the workspace
482 addedShortcutsFinal.add(shortcutInfo);
483 }
484 }
485
Winson Chung76828c82013-08-19 15:43:29 -0700486 // Update the workspace screens
487 updateWorkspaceScreenOrder(context, workspaceScreens);
488
Adam Cohen76a47a12014-02-05 11:47:43 -0800489 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700490 runOnMainThread(new Runnable() {
491 public void run() {
492 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
493 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700494 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
495 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700496 if (!addedShortcutsFinal.isEmpty()) {
497 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
498 long lastScreenId = info.screenId;
499 for (ItemInfo i : addedShortcutsFinal) {
500 if (i.screenId == lastScreenId) {
501 addAnimated.add(i);
502 } else {
503 addNotAnimated.add(i);
504 }
Winson Chung997a9232013-07-24 15:33:46 -0700505 }
506 }
Winson Chungd64d1762013-08-20 14:37:16 -0700507 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800508 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500509 if (!restoredAppsFinal.isEmpty()) {
510 callbacks.bindAppsUpdated(restoredAppsFinal);
511 }
Winson Chung997a9232013-07-24 15:33:46 -0700512 }
Winson Chung64359a52013-07-08 17:17:08 -0700513 }
Winson Chung997a9232013-07-24 15:33:46 -0700514 });
515 }
Winson Chung64359a52013-07-08 17:17:08 -0700516 }
517 };
518 runOnWorkerThread(r);
519 }
520
Winson Chung81b52252012-08-27 15:34:29 -0700521 public void unbindItemInfosAndClearQueuedBindRunnables() {
522 if (sWorkerThread.getThreadId() == Process.myTid()) {
523 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
524 "main thread");
525 }
526
527 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400528 synchronized (mDeferredBindRunnables) {
529 mDeferredBindRunnables.clear();
530 }
Winson Chung81b52252012-08-27 15:34:29 -0700531 // Remove any queued bind runnables
532 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
533 // Unbind all the workspace items
534 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700535 }
536
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700537 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700538 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700539 // Ensure that we don't use the same workspace items data structure on the main thread
540 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700541 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
542 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700543 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700544 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
545 tmpAppWidgets.addAll(sBgAppWidgets);
546 }
547 Runnable r = new Runnable() {
548 @Override
549 public void run() {
550 for (ItemInfo item : tmpWorkspaceItems) {
551 item.unbind();
552 }
553 for (ItemInfo item : tmpAppWidgets) {
554 item.unbind();
555 }
556 }
557 };
558 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700559 }
560
Joe Onorato9c1289c2009-08-17 11:03:03 -0400561 /**
562 * Adds an item to the DB if it was not created previously, or move it to a new
563 * <container, screen, cellX, cellY>
564 */
565 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700566 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400567 if (item.container == ItemInfo.NO_ID) {
568 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700569 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400570 } else {
571 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700572 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 }
574 }
575
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700576 static void checkItemInfoLocked(
577 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
578 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
579 if (modelItem != null && item != modelItem) {
580 // check all the data is consistent
581 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
582 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
583 ShortcutInfo shortcut = (ShortcutInfo) item;
584 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
585 modelShortcut.intent.filterEquals(shortcut.intent) &&
586 modelShortcut.id == shortcut.id &&
587 modelShortcut.itemType == shortcut.itemType &&
588 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700589 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700590 modelShortcut.cellX == shortcut.cellX &&
591 modelShortcut.cellY == shortcut.cellY &&
592 modelShortcut.spanX == shortcut.spanX &&
593 modelShortcut.spanY == shortcut.spanY &&
594 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
595 (modelShortcut.dropPos != null &&
596 shortcut.dropPos != null &&
597 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
598 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
599 // For all intents and purposes, this is the same object
600 return;
601 }
602 }
603
604 // the modelItem needs to match up perfectly with item if our model is
605 // to be consistent with the database-- for now, just require
606 // modelItem == item or the equality check above
607 String msg = "item: " + ((item != null) ? item.toString() : "null") +
608 "modelItem: " +
609 ((modelItem != null) ? modelItem.toString() : "null") +
610 "Error: ItemInfo passed to checkItemInfo doesn't match original";
611 RuntimeException e = new RuntimeException(msg);
612 if (stackTrace != null) {
613 e.setStackTrace(stackTrace);
614 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800615 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700616 }
617 }
618
Michael Jurka816474f2012-06-25 14:49:02 -0700619 static void checkItemInfo(final ItemInfo item) {
620 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
621 final long itemId = item.id;
622 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700623 public void run() {
624 synchronized (sBgLock) {
625 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700626 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700627 }
628 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700629 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700630 }
631
Michael Jurkac9d95c52011-08-29 14:03:34 -0700632 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
633 final ItemInfo item, final String callingFunction) {
634 final long itemId = item.id;
635 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
636 final ContentResolver cr = context.getContentResolver();
637
Adam Cohen487f7dd2012-06-28 18:12:10 -0700638 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700639 Runnable r = new Runnable() {
640 public void run() {
641 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700642 updateItemArrays(item, itemId, stackTrace);
643 }
644 };
645 runOnWorkerThread(r);
646 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700647
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700648 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
649 final ArrayList<ItemInfo> items, final String callingFunction) {
650 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700651
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700652 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
653 Runnable r = new Runnable() {
654 public void run() {
655 ArrayList<ContentProviderOperation> ops =
656 new ArrayList<ContentProviderOperation>();
657 int count = items.size();
658 for (int i = 0; i < count; i++) {
659 ItemInfo item = items.get(i);
660 final long itemId = item.id;
661 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
662 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700663
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700664 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
665 updateItemArrays(item, itemId, stackTrace);
666
667 }
668 try {
669 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
670 } catch (Exception e) {
671 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700672 }
673 }
674 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700675 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700676 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700677
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700678 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
679 // Lock on mBgLock *after* the db operation
680 synchronized (sBgLock) {
681 checkItemInfoLocked(itemId, item, stackTrace);
682
683 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
684 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
685 // Item is in a folder, make sure this folder exists
686 if (!sBgFolders.containsKey(item.container)) {
687 // An items container is being set to a that of an item which is not in
688 // the list of Folders.
689 String msg = "item: " + item + " container being set to: " +
690 item.container + ", not in the list of folders";
691 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700692 }
693 }
694
695 // Items are added/removed from the corresponding FolderInfo elsewhere, such
696 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
697 // that are on the desktop, as appropriate
698 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800699 if (modelItem != null &&
700 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
701 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700702 switch (modelItem.itemType) {
703 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
704 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
705 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
706 if (!sBgWorkspaceItems.contains(modelItem)) {
707 sBgWorkspaceItems.add(modelItem);
708 }
709 break;
710 default:
711 break;
712 }
713 } else {
714 sBgWorkspaceItems.remove(modelItem);
715 }
716 }
717 }
718
Michael Jurkac7700af2013-05-14 20:17:58 +0200719 public void flushWorkerThread() {
720 mFlushingWorkerThread = true;
721 Runnable waiter = new Runnable() {
722 public void run() {
723 synchronized (this) {
724 notifyAll();
725 mFlushingWorkerThread = false;
726 }
727 }
728 };
729
730 synchronized(waiter) {
731 runOnWorkerThread(waiter);
732 if (mLoaderTask != null) {
733 synchronized(mLoaderTask) {
734 mLoaderTask.notify();
735 }
736 }
737 boolean success = false;
738 while (!success) {
739 try {
740 waiter.wait();
741 success = true;
742 } catch (InterruptedException e) {
743 }
744 }
745 }
746 }
747
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800748 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400749 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700750 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700751 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700752 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400753 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 item.cellX = cellX;
755 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700756
Winson Chung3d503fb2011-07-13 17:25:49 -0700757 // We store hotseat items in canonical form which is this orientation invariant position
758 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700759 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700760 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700761 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700762 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700763 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700764 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400765
766 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700768 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
769 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400771
Michael Jurkac9d95c52011-08-29 14:03:34 -0700772 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700773 }
774
775 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700776 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
777 * cellX, cellY have already been updated on the ItemInfos.
778 */
779 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
780 final long container, final int screen) {
781
782 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
783 int count = items.size();
784
785 for (int i = 0; i < count; i++) {
786 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700787 item.container = container;
788
789 // We store hotseat items in canonical form which is this orientation invariant position
790 // in the hotseat
791 if (context instanceof Launcher && screen < 0 &&
792 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700793 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700794 item.cellY);
795 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700796 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700797 }
798
799 final ContentValues values = new ContentValues();
800 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
801 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
802 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700803 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700804
805 contentValues.add(values);
806 }
807 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
808 }
809
810 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700811 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800812 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700813 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700815 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800816 item.cellX = cellX;
817 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700818 item.spanX = spanX;
819 item.spanY = spanY;
820
821 // We store hotseat items in canonical form which is this orientation invariant position
822 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700823 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700824 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700825 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700826 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700828 }
Adam Cohend4844c32011-02-18 19:25:06 -0800829
Adam Cohend4844c32011-02-18 19:25:06 -0800830 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800831 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700832 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
833 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
834 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
835 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700836 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800837
Michael Jurka816474f2012-06-25 14:49:02 -0700838 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700839 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700840
841 /**
842 * Update an item to the database in a specified container.
843 */
844 static void updateItemInDatabase(Context context, final ItemInfo item) {
845 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100846 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700847 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
848 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800849 }
850
851 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852 * Returns true if the shortcuts already exists in the database.
853 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800854 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400855 static boolean shortcutExists(Context context, String title, Intent intent) {
856 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700857 final Intent intentWithPkg, intentWithoutPkg;
858
859 if (intent.getComponent() != null) {
860 // If component is not null, an intent with null package will produce
861 // the same result and should also be a match.
862 if (intent.getPackage() != null) {
863 intentWithPkg = intent;
864 intentWithoutPkg = new Intent(intent).setPackage(null);
865 } else {
866 intentWithPkg = new Intent(intent).setPackage(
867 intent.getComponent().getPackageName());
868 intentWithoutPkg = intent;
869 }
870 } else {
871 intentWithPkg = intent;
872 intentWithoutPkg = intent;
873 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400874 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700875 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
876 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400877 boolean result = false;
878 try {
879 result = c.moveToFirst();
880 } finally {
881 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800882 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400883 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700884 }
885
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500887 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100888 * we identify a shortcut by the component name of the intent
889 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500890 */
Kenny Guyed131872014-04-30 03:02:21 +0100891 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500892 final ContentResolver cr = context.getContentResolver();
893 final ComponentName component = intent.getComponent();
894 if (component == null) {
895 return false;
896 }
897 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400898 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100899 long serialNumber = UserManagerCompat.getInstance(context)
900 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400901 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
902 "intent glob \"*component=" + shortName + "*\")" +
903 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500904 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100905 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500906 boolean result = false;
907 try {
908 result = c.moveToFirst();
909 } finally {
910 c.close();
911 }
912 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
913 return result;
914 }
915
916 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700917 * Returns an ItemInfo array containing all the items in the LauncherModel.
918 * The ItemInfo.id is not set through this function.
919 */
920 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
921 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
922 final ContentResolver cr = context.getContentResolver();
923 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
924 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100925 LauncherSettings.Favorites.SCREEN,
926 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
927 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
928 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700929
930 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
931 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
932 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
933 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
934 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
935 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
936 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100937 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
938 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700939 try {
940 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700941 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700942 item.cellX = c.getInt(cellXIndex);
943 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700944 item.spanX = Math.max(1, c.getInt(spanXIndex));
945 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700946 item.container = c.getInt(containerIndex);
947 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100949 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100950 item.user = userManager.getUserForSerialNumber(serialNumber);
951 // Skip if user has been deleted.
952 if (item.user != null) {
953 items.add(item);
954 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700955 }
956 } catch (Exception e) {
957 items.clear();
958 } finally {
959 c.close();
960 }
961
962 return items;
963 }
964
965 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400966 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
967 */
968 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
969 final ContentResolver cr = context.getContentResolver();
970 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
971 "_id=? and (itemType=? or itemType=?)",
972 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700973 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700974
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975 try {
976 if (c.moveToFirst()) {
977 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
978 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
979 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
980 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
981 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
982 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800983
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 FolderInfo folderInfo = null;
985 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700986 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
987 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700989 }
990
Joe Onorato9c1289c2009-08-17 11:03:03 -0400991 folderInfo.title = c.getString(titleIndex);
992 folderInfo.id = id;
993 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700995 folderInfo.cellX = c.getInt(cellXIndex);
996 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997
998 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700999 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001000 } finally {
1001 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001002 }
1003
1004 return null;
1005 }
1006
Joe Onorato9c1289c2009-08-17 11:03:03 -04001007 /**
1008 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1009 * cellY fields of the item. Also assigns an ID to the item.
1010 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001011 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001012 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001014 item.cellX = cellX;
1015 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001016 // We store hotseat items in canonical form which is this orientation invariant position
1017 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001018 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001019 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001021 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001023 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001024
1025 final ContentValues values = new ContentValues();
1026 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001027 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001028
Michael Jurka414300a2013-08-27 15:42:35 +02001029 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001030 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001031 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001032
Jason Monk8e19cf22014-03-20 15:06:57 -04001033 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001034 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001035 public void run() {
1036 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1037 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001038
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001040 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001041 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 sBgItemsIdMap.put(item.id, item);
1043 switch (item.itemType) {
1044 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1045 sBgFolders.put(item.id, (FolderInfo) item);
1046 // Fall through
1047 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1048 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1049 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1050 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1051 sBgWorkspaceItems.add(item);
1052 } else {
1053 if (!sBgFolders.containsKey(item.container)) {
1054 // Adding an item to a folder that doesn't exist.
1055 String msg = "adding item: " + item + " to a folder that " +
1056 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001057 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001058 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001059 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001060 break;
1061 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1062 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1063 break;
1064 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001065 }
1066 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001067 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001068 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001069 }
1070
Joe Onorato9c1289c2009-08-17 11:03:03 -04001071 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001072 * Creates a new unique child id, for a given cell span across all layouts.
1073 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001074 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001076 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001077 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001078 }
1079
Winson Chungaafa03c2010-06-11 17:34:16 -07001080 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001081 * Removes the specified item from the database
1082 * @param context
1083 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001084 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001085 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001087 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001088
Michael Jurka83df1882011-08-31 20:59:26 -07001089 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001091 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001092
1093 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001094 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001095 switch (item.itemType) {
1096 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1097 sBgFolders.remove(item.id);
1098 for (ItemInfo info: sBgItemsIdMap.values()) {
1099 if (info.container == item.id) {
1100 // We are deleting a folder which still contains items that
1101 // think they are contained by that folder.
1102 String msg = "deleting a folder (" + item + ") which still " +
1103 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001104 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001105 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001106 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001107 sBgWorkspaceItems.remove(item);
1108 break;
1109 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1110 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1111 sBgWorkspaceItems.remove(item);
1112 break;
1113 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1114 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1115 break;
1116 }
1117 sBgItemsIdMap.remove(item.id);
1118 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001119 }
1120 }
Michael Jurka83df1882011-08-31 20:59:26 -07001121 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001122 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001123 }
1124
1125 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001126 * Update the order of the workspace screens in the database. The array list contains
1127 * a list of screen ids in the order that they should appear.
1128 */
Winson Chungc9168342013-06-26 14:54:55 -07001129 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001130 // Log to disk
1131 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1132 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1133
Winson Chung64359a52013-07-08 17:17:08 -07001134 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001135 final ContentResolver cr = context.getContentResolver();
1136 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1137
1138 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001139 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 while (iter.hasNext()) {
1141 long id = iter.next();
1142 if (id < 0) {
1143 iter.remove();
1144 }
1145 }
1146
1147 Runnable r = new Runnable() {
1148 @Override
1149 public void run() {
Yura085c8532014-02-11 15:15:29 +00001150 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001151 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001152 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001153 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 for (int i = 0; i < count; i++) {
1155 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001156 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001157 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1158 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001159 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 }
Yura085c8532014-02-11 15:15:29 +00001161
1162 try {
1163 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1164 } catch (Exception ex) {
1165 throw new RuntimeException(ex);
1166 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001167
Winson Chungba9c37f2013-08-30 14:11:37 -07001168 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001169 sBgWorkspaceScreens.clear();
1170 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001171 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 }
1173 };
1174 runOnWorkerThread(r);
1175 }
1176
1177 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001178 * Remove the contents of the specified folder from the database
1179 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001180 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001181 final ContentResolver cr = context.getContentResolver();
1182
Michael Jurkac9d95c52011-08-29 14:03:34 -07001183 Runnable r = new Runnable() {
1184 public void run() {
1185 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001186 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001187 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001188 sBgItemsIdMap.remove(info.id);
1189 sBgFolders.remove(info.id);
1190 sBgDbIconCache.remove(info);
1191 sBgWorkspaceItems.remove(info);
1192 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001193
Michael Jurkac9d95c52011-08-29 14:03:34 -07001194 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1195 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001196 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001197 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001198 for (ItemInfo childInfo : info.contents) {
1199 sBgItemsIdMap.remove(childInfo.id);
1200 sBgDbIconCache.remove(childInfo);
1201 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001202 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001203 }
1204 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001206 }
1207
1208 /**
1209 * Set this as the current Launcher activity object for the loader.
1210 */
1211 public void initialize(Callbacks callbacks) {
1212 synchronized (mLock) {
1213 mCallbacks = new WeakReference<Callbacks>(callbacks);
1214 }
1215 }
1216
Kenny Guyed131872014-04-30 03:02:21 +01001217 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001218 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001219 int op = PackageUpdatedTask.OP_UPDATE;
1220 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1221 user));
1222 }
1223
1224 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001225 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001226 int op = PackageUpdatedTask.OP_REMOVE;
1227 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1228 user));
1229 }
1230
1231 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001232 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001233 int op = PackageUpdatedTask.OP_ADD;
1234 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1235 user));
1236 }
1237
1238 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001239 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001240 boolean replacing) {
1241 if (!replacing) {
1242 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1243 user));
1244 if (mAppsCanBeOnRemoveableStorage) {
1245 // Only rebind if we support removable storage. It catches the
1246 // case where
1247 // apps on the external sd card need to be reloaded
1248 startLoaderFromBackground();
1249 }
1250 } else {
1251 // If we are replacing then just update the packages in the list
1252 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1253 packageNames, user));
1254 }
1255 }
1256
1257 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001258 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001259 boolean replacing) {
1260 if (!replacing) {
1261 enqueuePackageUpdated(new PackageUpdatedTask(
1262 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1263 user));
1264 }
1265
1266 }
1267
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001268 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001269 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1270 * ACTION_PACKAGE_CHANGED.
1271 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001272 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001273 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001274 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001275
Joe Onorato36115782010-06-17 13:28:48 -04001276 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001277 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001278 // If we have changed locale we need to clear out the labels in all apps/workspace.
1279 forceReload();
1280 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1281 // Check if configuration change was an mcc/mnc change which would affect app resources
1282 // and we would need to clear out the labels in all apps/workspace. Same handling as
1283 // above for ACTION_LOCALE_CHANGED
1284 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001285 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001286 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001287 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001288 forceReload();
1289 }
1290 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001291 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001292 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1293 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001294 if (mCallbacks != null) {
1295 Callbacks callbacks = mCallbacks.get();
1296 if (callbacks != null) {
1297 callbacks.bindSearchablesChanged();
1298 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001299 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001300 }
1301 }
1302
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001303 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001304 resetLoadedState(true, true);
1305
Reena Lee93f824a2011-09-23 17:20:28 -07001306 // Do this here because if the launcher activity is running it will be restarted.
1307 // If it's not running startLoaderFromBackground will merely tell it that it needs
1308 // to reload.
1309 startLoaderFromBackground();
1310 }
1311
Winson Chungf0c6ae02012-03-21 16:10:31 -07001312 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1313 synchronized (mLock) {
1314 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1315 // mWorkspaceLoaded to true later
1316 stopLoaderLocked();
1317 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1318 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1319 }
1320 }
1321
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001322 /**
1323 * When the launcher is in the background, it's possible for it to miss paired
1324 * configuration changes. So whenever we trigger the loader from the background
1325 * tell the launcher that it needs to re-run the loader when it comes back instead
1326 * of doing it now.
1327 */
1328 public void startLoaderFromBackground() {
1329 boolean runLoader = false;
1330 if (mCallbacks != null) {
1331 Callbacks callbacks = mCallbacks.get();
1332 if (callbacks != null) {
1333 // Only actually run the loader if they're not paused.
1334 if (!callbacks.setLoadOnResume()) {
1335 runLoader = true;
1336 }
1337 }
1338 }
1339 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001340 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001341 }
Joe Onorato36115782010-06-17 13:28:48 -04001342 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001343
Reena Lee93f824a2011-09-23 17:20:28 -07001344 // If there is already a loader task running, tell it to stop.
1345 // returns true if isLaunching() was true on the old task
1346 private boolean stopLoaderLocked() {
1347 boolean isLaunching = false;
1348 LoaderTask oldTask = mLoaderTask;
1349 if (oldTask != null) {
1350 if (oldTask.isLaunching()) {
1351 isLaunching = true;
1352 }
1353 oldTask.stopLocked();
1354 }
1355 return isLaunching;
1356 }
1357
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001358 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001359 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1360 }
1361
1362 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001363 synchronized (mLock) {
1364 if (DEBUG_LOADERS) {
1365 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1366 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001367
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001368 // Clear any deferred bind-runnables from the synchronized load process
1369 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001370 synchronized (mDeferredBindRunnables) {
1371 mDeferredBindRunnables.clear();
1372 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373
Joe Onorato36115782010-06-17 13:28:48 -04001374 // Don't bother to start the thread if we know it's not going to do anything
1375 if (mCallbacks != null && mCallbacks.get() != null) {
1376 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001377 // also, don't downgrade isLaunching if we're already running
1378 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001379 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001380 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1381 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001382 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1383 } else {
1384 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1385 sWorker.post(mLoaderTask);
1386 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001387 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001388 }
1389 }
1390
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001391 void bindRemainingSynchronousPages() {
1392 // Post the remaining side pages to be loaded
1393 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001394 Runnable[] deferredBindRunnables = null;
1395 synchronized (mDeferredBindRunnables) {
1396 deferredBindRunnables = mDeferredBindRunnables.toArray(
1397 new Runnable[mDeferredBindRunnables.size()]);
1398 mDeferredBindRunnables.clear();
1399 }
1400 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001401 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 }
1404 }
1405
Joe Onorato36115782010-06-17 13:28:48 -04001406 public void stopLoader() {
1407 synchronized (mLock) {
1408 if (mLoaderTask != null) {
1409 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001410 }
1411 }
Joe Onorato36115782010-06-17 13:28:48 -04001412 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001413
Winson Chung76828c82013-08-19 15:43:29 -07001414 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1415 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1416 final ContentResolver contentResolver = context.getContentResolver();
1417 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1418 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1419 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1420
1421 try {
1422 final int idIndex = sc.getColumnIndexOrThrow(
1423 LauncherSettings.WorkspaceScreens._ID);
1424 final int rankIndex = sc.getColumnIndexOrThrow(
1425 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1426 while (sc.moveToNext()) {
1427 try {
1428 long screenId = sc.getLong(idIndex);
1429 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001430 orderedScreens.put(rank, screenId);
1431 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001432 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001433 }
1434 }
1435 } finally {
1436 sc.close();
1437 }
Winson Chunga90303b2013-11-15 13:05:06 -08001438
1439 // Log to disk
1440 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1441 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1442 for (Integer i : orderedScreens.keySet()) {
1443 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1444 }
1445 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1446 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001447 return orderedScreens;
1448 }
1449
Michael Jurkac57b7a82011-08-09 22:02:20 -07001450 public boolean isAllAppsLoaded() {
1451 return mAllAppsLoaded;
1452 }
1453
Winson Chung36a62fe2012-05-06 18:04:42 -07001454 boolean isLoadingWorkspace() {
1455 synchronized (mLock) {
1456 if (mLoaderTask != null) {
1457 return mLoaderTask.isLoadingWorkspace();
1458 }
1459 }
1460 return false;
1461 }
1462
Joe Onorato36115782010-06-17 13:28:48 -04001463 /**
1464 * Runnable for the thread that loads the contents of the launcher:
1465 * - workspace icons
1466 * - widgets
1467 * - all apps icons
1468 */
1469 private class LoaderTask implements Runnable {
1470 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001471 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001472 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mStopped;
1474 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001475 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001476
Winson Chungc3eecff2011-07-11 17:44:15 -07001477 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001478
Dan Sandlerd5024042014-01-09 15:01:33 -05001479 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001480 mContext = context;
1481 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001482 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001483 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001484 }
1485
Joe Onorato36115782010-06-17 13:28:48 -04001486 boolean isLaunching() {
1487 return mIsLaunching;
1488 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Winson Chung36a62fe2012-05-06 18:04:42 -07001490 boolean isLoadingWorkspace() {
1491 return mIsLoadingAndBindingWorkspace;
1492 }
1493
Winson Chungc763c4e2013-07-19 13:49:06 -07001494 /** Returns whether this is an upgrade path */
1495 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001496 mIsLoadingAndBindingWorkspace = true;
1497
Joe Onorato36115782010-06-17 13:28:48 -04001498 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001499 if (DEBUG_LOADERS) {
1500 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001501 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001502
Winson Chungc763c4e2013-07-19 13:49:06 -07001503 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001504 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001505 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001506 synchronized (LoaderTask.this) {
1507 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001508 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001509 }
1510 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001511 }
1512 }
1513
Joe Onorato36115782010-06-17 13:28:48 -04001514 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001515 bindWorkspace(-1, isUpgradePath);
1516 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001517 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001518
Joe Onorato36115782010-06-17 13:28:48 -04001519 private void waitForIdle() {
1520 // Wait until the either we're stopped or the other threads are done.
1521 // This way we don't start loading all apps until the workspace has settled
1522 // down.
1523 synchronized (LoaderTask.this) {
1524 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001525
Joe Onorato36115782010-06-17 13:28:48 -04001526 mHandler.postIdle(new Runnable() {
1527 public void run() {
1528 synchronized (LoaderTask.this) {
1529 mLoadAndBindStepFinished = true;
1530 if (DEBUG_LOADERS) {
1531 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001532 }
Joe Onorato36115782010-06-17 13:28:48 -04001533 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001534 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001535 }
Joe Onorato36115782010-06-17 13:28:48 -04001536 });
1537
Michael Jurkac7700af2013-05-14 20:17:58 +02001538 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001539 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001540 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1541 // wait no longer than 1sec at a time
1542 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001543 } catch (InterruptedException ex) {
1544 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001545 }
1546 }
Joe Onorato36115782010-06-17 13:28:48 -04001547 if (DEBUG_LOADERS) {
1548 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001549 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001550 + "ms for previous step to finish binding");
1551 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001552 }
Joe Onorato36115782010-06-17 13:28:48 -04001553 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001554
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001555 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001556 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001557 // Ensure that we have a valid page index to load synchronously
1558 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1559 "valid page index");
1560 }
1561 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1562 // Ensure that we don't try and bind a specified page when the pages have not been
1563 // loaded already (we should load everything asynchronously in that case)
1564 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1565 }
1566 synchronized (mLock) {
1567 if (mIsLoaderTaskRunning) {
1568 // Ensure that we are never running the background loading at this point since
1569 // we also touch the background collections
1570 throw new RuntimeException("Error! Background loading is already running");
1571 }
1572 }
1573
1574 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1575 // data structures, we can't allow any other thread to touch that data, but because
1576 // this call is synchronous, we can get away with not locking).
1577
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001578 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001579 // operations from the previous activity. We need to ensure that all queued operations
1580 // are executed before any synchronous binding work is done.
1581 mHandler.flush();
1582
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 // Divide the set of loaded items into those that we are binding synchronously, and
1584 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001585 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1587 // arise from that.
1588 onlyBindAllApps();
1589 }
1590
Joe Onorato36115782010-06-17 13:28:48 -04001591 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001592 boolean isUpgrade = false;
1593
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001594 synchronized (mLock) {
1595 mIsLoaderTaskRunning = true;
1596 }
Joe Onorato36115782010-06-17 13:28:48 -04001597 // Optimize for end-user experience: if the Launcher is up and // running with the
1598 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1599 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001600 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001601 // Elevate priority when Home launches for the first time to avoid
1602 // starving at boot time. Staring at a blank home is not cool.
1603 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001604 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1605 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001606 android.os.Process.setThreadPriority(mIsLaunching
1607 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1608 }
Winson Chung64359a52013-07-08 17:17:08 -07001609 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001610 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001611
Joe Onorato36115782010-06-17 13:28:48 -04001612 if (mStopped) {
1613 break keep_running;
1614 }
1615
1616 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1617 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001618 synchronized (mLock) {
1619 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001620 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001621 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1622 }
1623 }
Joe Onorato36115782010-06-17 13:28:48 -04001624 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001625
1626 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001627 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1628 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001629
1630 // Restore the default thread priority after we are done loading items
1631 synchronized (mLock) {
1632 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1633 }
Joe Onorato36115782010-06-17 13:28:48 -04001634 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001635
Winson Chungaac01e12011-08-17 10:37:13 -07001636 // Update the saved icons if necessary
1637 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001638 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001639 for (Object key : sBgDbIconCache.keySet()) {
1640 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1641 }
1642 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001643 }
Winson Chungaac01e12011-08-17 10:37:13 -07001644
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001645 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001646 // Ensure that all the applications that are in the system are
1647 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001648 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001649 verifyApplications();
1650 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001651 }
1652
Joe Onorato36115782010-06-17 13:28:48 -04001653 // Clear out this reference, otherwise we end up holding it until all of the
1654 // callback runnables are done.
1655 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001656
Joe Onorato36115782010-06-17 13:28:48 -04001657 synchronized (mLock) {
1658 // If we are still the last one to be scheduled, remove ourselves.
1659 if (mLoaderTask == this) {
1660 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001661 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001662 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001663 }
Joe Onorato36115782010-06-17 13:28:48 -04001664 }
1665
1666 public void stopLocked() {
1667 synchronized (LoaderTask.this) {
1668 mStopped = true;
1669 this.notify();
1670 }
1671 }
1672
1673 /**
1674 * Gets the callbacks object. If we've been stopped, or if the launcher object
1675 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1676 * object that was around when the deferred message was scheduled, and if there's
1677 * a new Callbacks object around then also return null. This will save us from
1678 * calling onto it with data that will be ignored.
1679 */
1680 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1681 synchronized (mLock) {
1682 if (mStopped) {
1683 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001684 }
Joe Onorato36115782010-06-17 13:28:48 -04001685
1686 if (mCallbacks == null) {
1687 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001688 }
Joe Onorato36115782010-06-17 13:28:48 -04001689
1690 final Callbacks callbacks = mCallbacks.get();
1691 if (callbacks != oldCallbacks) {
1692 return null;
1693 }
1694 if (callbacks == null) {
1695 Log.w(TAG, "no mCallbacks");
1696 return null;
1697 }
1698
1699 return callbacks;
1700 }
1701 }
1702
Winson Chungc763c4e2013-07-19 13:49:06 -07001703 private void verifyApplications() {
1704 final Context context = mApp.getContext();
1705
1706 // Cross reference all the applications in our apps list with items in the workspace
1707 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001708 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001709 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001710 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001711 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001712 if (tmpInfos.isEmpty()) {
1713 // We are missing an application icon, so add this to the workspace
1714 added.add(app);
1715 // This is a rare event, so lets log it
1716 Log.e(TAG, "Missing Application on load: " + app);
1717 }
1718 }
1719 }
1720 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001721 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001722 }
1723 }
1724
Joe Onorato36115782010-06-17 13:28:48 -04001725 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001726 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001727 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001728 LauncherAppState app = LauncherAppState.getInstance();
1729 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001730 final int countX = (int) grid.numColumns;
1731 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001732
Adam Cohendcd297f2013-06-18 13:13:40 -07001733 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001734 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001735 // Return early if we detect that an item is under the hotseat button
1736 if (mCallbacks == null ||
1737 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001738 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001739 Log.e(TAG, "Error loading shortcut into hotseat " + item
1740 + " into position (" + item.screenId + ":" + item.cellX + ","
1741 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001742 return false;
1743 }
1744
Dan Sandler295ae182013-12-10 16:05:47 -05001745 final ItemInfo[][] hotseatItems =
1746 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1747
Adam Cohenae4409d2013-11-26 10:34:59 -08001748 if (item.screenId >= grid.numHotseatIcons) {
1749 Log.e(TAG, "Error loading shortcut " + item
1750 + " into hotseat position " + item.screenId
1751 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1752 + ")");
1753 return false;
1754 }
1755
Dan Sandler295ae182013-12-10 16:05:47 -05001756 if (hotseatItems != null) {
1757 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001758 Log.e(TAG, "Error loading shortcut into hotseat " + item
1759 + " into position (" + item.screenId + ":" + item.cellX + ","
1760 + item.cellY + ") occupied by "
1761 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1762 [(int) item.screenId][0]);
1763 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001764 } else {
1765 hotseatItems[(int) item.screenId][0] = item;
1766 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001768 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001769 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001770 items[(int) item.screenId][0] = item;
1771 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001772 return true;
1773 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001774 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1775 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001776 return true;
1777 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001778
Adam Cohendcd297f2013-06-18 13:13:40 -07001779 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001780 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001781 occupied.put(item.screenId, items);
1782 }
1783
Dan Sandler295ae182013-12-10 16:05:47 -05001784 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001785 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1786 item.cellX < 0 || item.cellY < 0 ||
1787 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1788 Log.e(TAG, "Error loading shortcut " + item
1789 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1790 + item.cellX + "," + item.cellY
1791 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1792 return false;
1793 }
1794
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001795 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001796 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1797 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001798 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001799 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001801 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001802 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001804 return false;
1805 }
1806 }
1807 }
1808 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1809 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001811 }
1812 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001813
Joe Onorato36115782010-06-17 13:28:48 -04001814 return true;
1815 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001816
Winson Chungba9c37f2013-08-30 14:11:37 -07001817 /** Clears all the sBg data structures */
1818 private void clearSBgDataStructures() {
1819 synchronized (sBgLock) {
1820 sBgWorkspaceItems.clear();
1821 sBgAppWidgets.clear();
1822 sBgFolders.clear();
1823 sBgItemsIdMap.clear();
1824 sBgDbIconCache.clear();
1825 sBgWorkspaceScreens.clear();
1826 }
1827 }
1828
Dan Sandlerd5024042014-01-09 15:01:33 -05001829 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001830 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001831 // Log to disk
1832 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1833
Joe Onorato36115782010-06-17 13:28:48 -04001834 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001835
Joe Onorato36115782010-06-17 13:28:48 -04001836 final Context context = mContext;
1837 final ContentResolver contentResolver = context.getContentResolver();
1838 final PackageManager manager = context.getPackageManager();
1839 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1840 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001841 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1842 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001843 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001844
Winson Chung892c74d2013-08-22 16:15:50 -07001845 LauncherAppState app = LauncherAppState.getInstance();
1846 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1847 int countX = (int) grid.numColumns;
1848 int countY = (int) grid.numRows;
1849
Dan Sandlerd5024042014-01-09 15:01:33 -05001850 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1851 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1852 LauncherAppState.getLauncherProvider().deleteDatabase();
1853 }
1854
1855 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1856 // append the user's Launcher2 shortcuts
1857 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1858 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1859 } else {
1860 // Make sure the default workspace is loaded
1861 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1862 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1863 }
Adam Cohene25af792013-06-06 23:08:25 -07001864
Adam Cohen71483f42014-05-15 14:04:01 -07001865 // This code path is for our old migration code and should no longer be exercised
1866 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001867
Winson Chung9f9f00b2013-11-15 13:27:00 -08001868 // Log to disk
1869 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001870
Winson Chung2abf94d2012-07-18 18:16:38 -07001871 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001872 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001873
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001874 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001875 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001876 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001877 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001878 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001879
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001880 // +1 for the hotseat (it can be larger than the workspace)
1881 // Load workspace in reverse order to ensure that latest items are loaded first (and
1882 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001883 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001884
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001885 try {
1886 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1887 final int intentIndex = c.getColumnIndexOrThrow
1888 (LauncherSettings.Favorites.INTENT);
1889 final int titleIndex = c.getColumnIndexOrThrow
1890 (LauncherSettings.Favorites.TITLE);
1891 final int iconTypeIndex = c.getColumnIndexOrThrow(
1892 LauncherSettings.Favorites.ICON_TYPE);
1893 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1894 final int iconPackageIndex = c.getColumnIndexOrThrow(
1895 LauncherSettings.Favorites.ICON_PACKAGE);
1896 final int iconResourceIndex = c.getColumnIndexOrThrow(
1897 LauncherSettings.Favorites.ICON_RESOURCE);
1898 final int containerIndex = c.getColumnIndexOrThrow(
1899 LauncherSettings.Favorites.CONTAINER);
1900 final int itemTypeIndex = c.getColumnIndexOrThrow(
1901 LauncherSettings.Favorites.ITEM_TYPE);
1902 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1903 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001904 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1905 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 final int screenIndex = c.getColumnIndexOrThrow(
1907 LauncherSettings.Favorites.SCREEN);
1908 final int cellXIndex = c.getColumnIndexOrThrow
1909 (LauncherSettings.Favorites.CELLX);
1910 final int cellYIndex = c.getColumnIndexOrThrow
1911 (LauncherSettings.Favorites.CELLY);
1912 final int spanXIndex = c.getColumnIndexOrThrow
1913 (LauncherSettings.Favorites.SPANX);
1914 final int spanYIndex = c.getColumnIndexOrThrow(
1915 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001916 final int restoredIndex = c.getColumnIndexOrThrow(
1917 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001918 final int profileIdIndex = c.getColumnIndexOrThrow(
1919 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1921 //final int displayModeIndex = c.getColumnIndexOrThrow(
1922 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001923
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001924 ShortcutInfo info;
1925 String intentDescription;
1926 LauncherAppWidgetInfo appWidgetInfo;
1927 int container;
1928 long id;
1929 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001930 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001931
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001932 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001933 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001934 try {
1935 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001936 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001937 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001938
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001939 switch (itemType) {
1940 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1941 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001942 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001944 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001945 user = mUserManager.getUserForSerialNumber(serialNumber);
1946 if (user == null) {
1947 // User has been deleted remove the item.
1948 itemsToRemove.add(id);
1949 continue;
1950 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001951 try {
1952 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001953 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001954 if (cn != null && cn.getPackageName() != null) {
1955 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1956 cn.getPackageName(), user);
1957 boolean validComponent = validPkg &&
1958 launcherApps.isActivityEnabledForProfile(cn, user);
1959
1960 if (validComponent) {
1961 if (restored) {
1962 // no special handling necessary for this item
1963 restoredRows.add(id);
1964 restored = false;
1965 }
1966 } else if (validPkg) {
1967 // The app is installed but the component is no
1968 // longer available.
1969 Launcher.addDumpLog(TAG,
1970 "Invalid component removed: " + cn, true);
1971 itemsToRemove.add(id);
1972 continue;
1973 } else if (restored) {
1974 // Package is not yet available but might be
1975 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001976 Launcher.addDumpLog(TAG,
1977 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001978 } else if (isSdCardReady) {
1979 // Do not wait for external media load anymore.
1980 // Log the invalid package, and remove it
1981 Launcher.addDumpLog(TAG,
1982 "Invalid package removed: " + cn, true);
1983 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05001984 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001985 } else {
1986 // SdCard is not ready yet. Package might get available,
1987 // once it is ready.
1988 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1989 + " (check again later)", true);
1990 HashSet<String> pkgs = sPendingPackages.get(user);
1991 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001992 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001993 sPendingPackages.put(user, pkgs);
1994 }
1995 pkgs.add(cn.getPackageName());
1996 allowMissingTarget = true;
1997 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07001998 }
Winson Chungee055712013-07-30 14:46:24 -07001999 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002000 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002001 Launcher.addDumpLog(TAG,
2002 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002003 continue;
2004 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002005
Chris Wrenf4d08112014-01-16 18:13:56 -05002006 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002007 if (user.equals(UserHandleCompat.myUserHandle())) {
2008 Launcher.addDumpLog(TAG,
2009 "constructing info for partially restored package",
2010 true);
2011 info = getRestoredItemInfo(c, titleIndex, intent);
2012 intent = getRestoredItemIntent(c, context, intent);
2013 } else {
2014 // Don't restore items for other profiles.
2015 itemsToRemove.add(id);
2016 continue;
2017 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002018 } else if (itemType ==
2019 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002020 info = getShortcutInfo(manager, intent, user, context, c,
2021 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002022 } else {
2023 info = getShortcutInfo(c, context, iconTypeIndex,
2024 iconPackageIndex, iconResourceIndex, iconIndex,
2025 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002026
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002027 // App shortcuts that used to be automatically added to Launcher
2028 // didn't always have the correct intent flags set, so do that
2029 // here
2030 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002031 intent.getCategories() != null &&
2032 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002033 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002034 intent.addFlags(
2035 Intent.FLAG_ACTIVITY_NEW_TASK |
2036 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2037 }
Michael Jurka96879562012-03-22 05:54:33 -07002038 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002039
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002040 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002041 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002043 container = c.getInt(containerIndex);
2044 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002045 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002046 info.cellX = c.getInt(cellXIndex);
2047 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002048 info.spanX = 1;
2049 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002050 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002051 info.isDisabled = isSafeMode
2052 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002053
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002055 deleteOnInvalidPlacement.set(false);
2056 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2057 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002058 itemsToRemove.add(id);
2059 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002060 break;
2061 }
2062
2063 switch (container) {
2064 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2065 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2066 sBgWorkspaceItems.add(info);
2067 break;
2068 default:
2069 // Item is in a user folder
2070 FolderInfo folderInfo =
2071 findOrMakeFolder(sBgFolders, container);
2072 folderInfo.add(info);
2073 break;
2074 }
2075 sBgItemsIdMap.put(info.id, info);
2076
2077 // now that we've loaded everthing re-save it with the
2078 // icon in case it disappears somehow.
2079 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002080 } else {
2081 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 }
2083 break;
2084
2085 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2086 id = c.getLong(idIndex);
2087 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2088
2089 folderInfo.title = c.getString(titleIndex);
2090 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002091 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002092 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002093 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002094 folderInfo.cellX = c.getInt(cellXIndex);
2095 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002096 folderInfo.spanX = 1;
2097 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002098
Daniel Sandler8802e962010-05-26 16:28:16 -04002099 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002100 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002101 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002102 deleteOnInvalidPlacement)) {
2103 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002104 itemsToRemove.add(id);
2105 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002106 break;
2107 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002108
Joe Onorato9c1289c2009-08-17 11:03:03 -04002109 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2111 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2112 sBgWorkspaceItems.add(folderInfo);
2113 break;
Joe Onorato36115782010-06-17 13:28:48 -04002114 }
Joe Onorato17a89222011-02-08 17:26:11 -08002115
Chris Wrenf4d08112014-01-16 18:13:56 -05002116 if (restored) {
2117 // no special handling required for restored folders
2118 restoredRows.add(id);
2119 }
2120
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2122 sBgFolders.put(folderInfo.id, folderInfo);
2123 break;
2124
2125 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2126 // Read all Launcher-specific widget details
2127 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002128 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002129 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002130
Sunny Goyal651077b2014-06-30 14:15:31 -07002131 final int restoreStatus = c.getInt(restoredIndex);
2132 final boolean restorePending = Utilities.isLmp()
2133 && (restoreStatus ==
2134 LauncherAppWidgetInfo.RESTORE_REMAP_PENDING);
2135 final boolean providerPending = Utilities.isLmp()
2136 && (restoreStatus ==
2137 LauncherAppWidgetInfo.RESTORE_PROVIDER_PENDING);
Joe Onorato36115782010-06-17 13:28:48 -04002138
Sunny Goyal651077b2014-06-30 14:15:31 -07002139 // Do not try to get the provider if restore is pending, as the
2140 // widget id is invalid, and it might point to some other provider.
2141 final AppWidgetProviderInfo provider = restorePending ? null
2142 : widgets.getAppWidgetInfo(appWidgetId);
2143 boolean providerValid = isValidProvider(provider);
2144
2145 // Skip provider check,
2146 // 1. when the widget id re-map is pending
2147 // 2. provider is pending install for a restored widget
2148 if (!isSafeMode && !providerPending && !restorePending
2149 && !providerValid) {
2150 String log = "Deleting widget that isn't installed anymore: "
2151 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002152 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002153 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 itemsToRemove.add(id);
2155 } else {
Sunny Goyal651077b2014-06-30 14:15:31 -07002156 if (providerValid) {
2157 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2158 provider.provider);
2159 int[] minSpan =
2160 Launcher.getMinSpanForWidget(context, provider);
2161 appWidgetInfo.minSpanX = minSpan[0];
2162 appWidgetInfo.minSpanY = minSpan[1];
2163 } else {
2164 Log.v(TAG, "Widget restore pending id=" + id
2165 + " appWidgetId=" + appWidgetId
2166 + " status =" + restoreStatus);
2167 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2168 ComponentName.unflattenFromString(savedProvider));
2169 appWidgetInfo.restoreStatus = restoreStatus;
2170 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002171 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002172 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002173 appWidgetInfo.cellX = c.getInt(cellXIndex);
2174 appWidgetInfo.cellY = c.getInt(cellYIndex);
2175 appWidgetInfo.spanX = c.getInt(spanXIndex);
2176 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002177
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002178 container = c.getInt(containerIndex);
2179 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2180 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2181 Log.e(TAG, "Widget found where container != " +
2182 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2183 continue;
2184 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002185
Adam Cohene25af792013-06-06 23:08:25 -07002186 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002188 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002189 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002190 deleteOnInvalidPlacement)) {
2191 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002192 itemsToRemove.add(id);
2193 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002194 break;
2195 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002196
2197 if (providerValid) {
2198 String providerName = provider.provider.flattenToString();
2199
2200 if (!providerName.equals(savedProvider) || providerPending) {
2201 ContentValues values = new ContentValues();
2202 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2203 providerName);
2204 values.put(LauncherSettings.Favorites.RESTORED,
2205 LauncherAppWidgetInfo.RESTORE_COMPLETED);
2206 String where = BaseColumns._ID + "= ?";
2207 String[] args = {Long.toString(id)};
2208 contentResolver.update(contentUri, values, where, args);
2209 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002210 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002211 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2212 sBgAppWidgets.add(appWidgetInfo);
2213 }
Joe Onorato36115782010-06-17 13:28:48 -04002214 break;
2215 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002217 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002218 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002219 }
2220 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002221 if (c != null) {
2222 c.close();
2223 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002224 }
2225
Winson Chungba9c37f2013-08-30 14:11:37 -07002226 // Break early if we've stopped loading
2227 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002228 clearSBgDataStructures();
2229 return false;
2230 }
2231
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 if (itemsToRemove.size() > 0) {
2233 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002234 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002235 // Remove dead items
2236 for (long id : itemsToRemove) {
2237 if (DEBUG_LOADERS) {
2238 Log.d(TAG, "Removed id = " + id);
2239 }
2240 // Don't notify content observers
2241 try {
2242 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2243 null, null);
2244 } catch (RemoteException e) {
2245 Log.w(TAG, "Could not remove id = " + id);
2246 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002247 }
2248 }
2249
Chris Wrenf4d08112014-01-16 18:13:56 -05002250 if (restoredRows.size() > 0) {
2251 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2252 LauncherSettings.Favorites.CONTENT_URI);
2253 // Update restored items that no longer require special handling
2254 try {
2255 StringBuilder selectionBuilder = new StringBuilder();
2256 selectionBuilder.append(LauncherSettings.Favorites._ID);
2257 selectionBuilder.append(" IN (");
2258 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2259 selectionBuilder.append(")");
2260 ContentValues values = new ContentValues();
2261 values.put(LauncherSettings.Favorites.RESTORED, 0);
2262 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2263 values, selectionBuilder.toString(), null);
2264 } catch (RemoteException e) {
2265 Log.w(TAG, "Could not update restored rows");
2266 }
2267 }
2268
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002269 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2270 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002271 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002272 null, sWorker);
2273 }
2274
Winson Chungc763c4e2013-07-19 13:49:06 -07002275 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002276 long maxScreenId = 0;
2277 // If we're importing we use the old screen order.
2278 for (ItemInfo item: sBgItemsIdMap.values()) {
2279 long screenId = item.screenId;
2280 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2281 !sBgWorkspaceScreens.contains(screenId)) {
2282 sBgWorkspaceScreens.add(screenId);
2283 if (screenId > maxScreenId) {
2284 maxScreenId = screenId;
2285 }
2286 }
2287 }
2288 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002289 // Log to disk
2290 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2291 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2292 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002293
Michael Jurka414300a2013-08-27 15:42:35 +02002294 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002295 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002296
2297 // Update the max item id after we load an old db
2298 long maxItemId = 0;
2299 // If we're importing we use the old screen order.
2300 for (ItemInfo item: sBgItemsIdMap.values()) {
2301 maxItemId = Math.max(maxItemId, item.id);
2302 }
Michael Jurka414300a2013-08-27 15:42:35 +02002303 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002304 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002305 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2306 for (Integer i : orderedScreens.keySet()) {
2307 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002308 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002309 // Log to disk
2310 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2311 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002312
2313 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002314 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002315 for (ItemInfo item: sBgItemsIdMap.values()) {
2316 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002317 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2318 unusedScreens.contains(screenId)) {
2319 unusedScreens.remove(screenId);
2320 }
2321 }
2322
2323 // If there are any empty screens remove them, and update.
2324 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002325 // Log to disk
2326 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2327 TextUtils.join(", ", unusedScreens), true);
2328
Winson Chung933bae62013-08-29 11:42:30 -07002329 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002330 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2331 }
2332 }
2333
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002334 if (DEBUG_LOADERS) {
2335 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2336 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002337 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002338 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002339 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002340
Daniel Sandler566da102013-06-25 23:43:45 -04002341 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002342 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002343 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002344 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002345 line += " | ";
2346 }
Winson Chung892c74d2013-08-22 16:15:50 -07002347 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002348 ItemInfo[][] screen = occupied.get(screenId);
2349 if (x < screen.length && y < screen[x].length) {
2350 line += (screen[x][y] != null) ? "#" : ".";
2351 } else {
2352 line += "!";
2353 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002354 }
Joe Onorato36115782010-06-17 13:28:48 -04002355 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002356 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002357 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002358 }
Joe Onorato36115782010-06-17 13:28:48 -04002359 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002360 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002361 }
2362
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002363 /** Filters the set of items who are directly or indirectly (via another container) on the
2364 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002365 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002366 ArrayList<ItemInfo> allWorkspaceItems,
2367 ArrayList<ItemInfo> currentScreenItems,
2368 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002369 // Purge any null ItemInfos
2370 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2371 while (iter.hasNext()) {
2372 ItemInfo i = iter.next();
2373 if (i == null) {
2374 iter.remove();
2375 }
2376 }
2377
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002378 // Order the set of items by their containers first, this allows use to walk through the
2379 // list sequentially, build up a list of containers that are in the specified screen,
2380 // as well as all items in those containers.
2381 Set<Long> itemsOnScreen = new HashSet<Long>();
2382 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2383 @Override
2384 public int compare(ItemInfo lhs, ItemInfo rhs) {
2385 return (int) (lhs.container - rhs.container);
2386 }
2387 });
2388 for (ItemInfo info : allWorkspaceItems) {
2389 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002390 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002391 currentScreenItems.add(info);
2392 itemsOnScreen.add(info.id);
2393 } else {
2394 otherScreenItems.add(info);
2395 }
2396 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2397 currentScreenItems.add(info);
2398 itemsOnScreen.add(info.id);
2399 } else {
2400 if (itemsOnScreen.contains(info.container)) {
2401 currentScreenItems.add(info);
2402 itemsOnScreen.add(info.id);
2403 } else {
2404 otherScreenItems.add(info);
2405 }
2406 }
2407 }
2408 }
2409
2410 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002411 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002412 ArrayList<LauncherAppWidgetInfo> appWidgets,
2413 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2414 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002415
2416 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002417 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002418 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002419 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002420 currentScreenWidgets.add(widget);
2421 } else {
2422 otherScreenWidgets.add(widget);
2423 }
2424 }
2425 }
2426
2427 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002428 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 HashMap<Long, ItemInfo> itemsIdMap,
2430 HashMap<Long, FolderInfo> folders,
2431 HashMap<Long, FolderInfo> currentScreenFolders,
2432 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002433
2434 for (long id : folders.keySet()) {
2435 ItemInfo info = itemsIdMap.get(id);
2436 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002437 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002438 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002439 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 currentScreenFolders.put(id, folder);
2441 } else {
2442 otherScreenFolders.put(id, folder);
2443 }
2444 }
2445 }
2446
2447 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2448 * right) */
2449 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002450 final LauncherAppState app = LauncherAppState.getInstance();
2451 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 // XXX: review this
2453 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002454 @Override
2455 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002456 int cellCountX = (int) grid.numColumns;
2457 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002458 int screenOffset = cellCountX * cellCountY;
2459 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002460 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002461 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002462 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002463 rhs.cellY * cellCountX + rhs.cellX);
2464 return (int) (lr - rr);
2465 }
2466 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002468
Adam Cohendcd297f2013-06-18 13:13:40 -07002469 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2470 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002471 final Runnable r = new Runnable() {
2472 @Override
2473 public void run() {
2474 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2475 if (callbacks != null) {
2476 callbacks.bindScreens(orderedScreens);
2477 }
2478 }
2479 };
2480 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2481 }
2482
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002483 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2484 final ArrayList<ItemInfo> workspaceItems,
2485 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2486 final HashMap<Long, FolderInfo> folders,
2487 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002488
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 final boolean postOnMainThread = (deferredBindRunnables != null);
2490
2491 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002492 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002493 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002494 final int start = i;
2495 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002496 final Runnable r = new Runnable() {
2497 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002498 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002499 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002500 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002501 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2502 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002503 }
2504 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002505 };
2506 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002507 synchronized (deferredBindRunnables) {
2508 deferredBindRunnables.add(r);
2509 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002510 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002511 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002512 }
Joe Onorato36115782010-06-17 13:28:48 -04002513 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002514
2515 // Bind the folders
2516 if (!folders.isEmpty()) {
2517 final Runnable r = new Runnable() {
2518 public void run() {
2519 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2520 if (callbacks != null) {
2521 callbacks.bindFolders(folders);
2522 }
2523 }
2524 };
2525 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002526 synchronized (deferredBindRunnables) {
2527 deferredBindRunnables.add(r);
2528 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002530 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002531 }
2532 }
2533
2534 // Bind the widgets, one at a time
2535 N = appWidgets.size();
2536 for (int i = 0; i < N; i++) {
2537 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2538 final Runnable r = new Runnable() {
2539 public void run() {
2540 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2541 if (callbacks != null) {
2542 callbacks.bindAppWidget(widget);
2543 }
2544 }
2545 };
2546 if (postOnMainThread) {
2547 deferredBindRunnables.add(r);
2548 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002549 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002550 }
2551 }
2552 }
2553
2554 /**
2555 * Binds all loaded data to actual views on the main thread.
2556 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002557 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 final long t = SystemClock.uptimeMillis();
2559 Runnable r;
2560
2561 // Don't use these two variables in any of the callback runnables.
2562 // Otherwise we hold a reference to them.
2563 final Callbacks oldCallbacks = mCallbacks.get();
2564 if (oldCallbacks == null) {
2565 // This launcher has exited and nobody bothered to tell us. Just bail.
2566 Log.w(TAG, "LoaderTask running with no launcher");
2567 return;
2568 }
2569
Winson Chung9b9fb962013-11-15 15:39:34 -08002570 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002571 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2572 ArrayList<LauncherAppWidgetInfo> appWidgets =
2573 new ArrayList<LauncherAppWidgetInfo>();
2574 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2575 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002576 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002577 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002578 workspaceItems.addAll(sBgWorkspaceItems);
2579 appWidgets.addAll(sBgAppWidgets);
2580 folders.putAll(sBgFolders);
2581 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002582 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583 }
2584
Derek Prothro7aff3992013-12-10 14:00:37 -05002585 final boolean isLoadingSynchronously =
2586 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002587 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002588 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002589 if (currScreen >= orderedScreenIds.size()) {
2590 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002591 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002592 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002593 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002594 final long currentScreenId = currentScreen < 0
2595 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002596
2597 // Load all the items that are on the current page first (and in the process, unbind
2598 // all the existing workspace items before we call startBinding() below.
2599 unbindWorkspaceItemsOnMainThread();
2600
2601 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002602 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2603 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2604 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2605 new ArrayList<LauncherAppWidgetInfo>();
2606 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2607 new ArrayList<LauncherAppWidgetInfo>();
2608 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2609 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2610
Winson Chung9b9fb962013-11-15 15:39:34 -08002611 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002612 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002613 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002614 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002615 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 otherFolders);
2617 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2618 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2619
2620 // Tell the workspace that we're about to start binding items
2621 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002622 public void run() {
2623 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2624 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002625 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002626 }
2627 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002628 };
Winson Chung81b52252012-08-27 15:34:29 -07002629 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002630
Adam Cohendcd297f2013-06-18 13:13:40 -07002631 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2632
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002633 // Load items on the current page
2634 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2635 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002636 if (isLoadingSynchronously) {
2637 r = new Runnable() {
2638 public void run() {
2639 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002640 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002641 callbacks.onPageBoundSynchronously(currentScreen);
2642 }
2643 }
2644 };
Winson Chung81b52252012-08-27 15:34:29 -07002645 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002646 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002647
Winson Chung4a2afa32012-07-19 14:53:05 -07002648 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2649 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002650 synchronized (mDeferredBindRunnables) {
2651 mDeferredBindRunnables.clear();
2652 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002654 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655
2656 // Tell the workspace that we're done binding items
2657 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002658 public void run() {
2659 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2660 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002661 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002662 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663
Winson Chung98e030b2012-05-07 16:01:11 -07002664 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002665 if (DEBUG_LOADERS) {
2666 Log.d(TAG, "bound workspace in "
2667 + (SystemClock.uptimeMillis()-t) + "ms");
2668 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002669
2670 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002671 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002673 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002674 synchronized (mDeferredBindRunnables) {
2675 mDeferredBindRunnables.add(r);
2676 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002677 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002678 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002679 }
Joe Onorato36115782010-06-17 13:28:48 -04002680 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002681
Joe Onorato36115782010-06-17 13:28:48 -04002682 private void loadAndBindAllApps() {
2683 if (DEBUG_LOADERS) {
2684 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2685 }
2686 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002687 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002688 synchronized (LoaderTask.this) {
2689 if (mStopped) {
2690 return;
2691 }
2692 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002693 }
Joe Onorato36115782010-06-17 13:28:48 -04002694 } else {
2695 onlyBindAllApps();
2696 }
2697 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002698
Joe Onorato36115782010-06-17 13:28:48 -04002699 private void onlyBindAllApps() {
2700 final Callbacks oldCallbacks = mCallbacks.get();
2701 if (oldCallbacks == null) {
2702 // This launcher has exited and nobody bothered to tell us. Just bail.
2703 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2704 return;
2705 }
2706
2707 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002708 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002709 final ArrayList<AppInfo> list
2710 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002711 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002712 public void run() {
2713 final long t = SystemClock.uptimeMillis();
2714 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2715 if (callbacks != null) {
2716 callbacks.bindAllApplications(list);
2717 }
2718 if (DEBUG_LOADERS) {
2719 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2720 + (SystemClock.uptimeMillis()-t) + "ms");
2721 }
2722 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002723 };
2724 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002725 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002726 r.run();
2727 } else {
2728 mHandler.post(r);
2729 }
Joe Onorato36115782010-06-17 13:28:48 -04002730 }
2731
Winson Chung64359a52013-07-08 17:17:08 -07002732 private void loadAllApps() {
2733 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002734
Joe Onorato36115782010-06-17 13:28:48 -04002735 final Callbacks oldCallbacks = mCallbacks.get();
2736 if (oldCallbacks == null) {
2737 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002738 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002739 return;
2740 }
2741
2742 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2743 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2744
Kenny Guyed131872014-04-30 03:02:21 +01002745 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2746
Winson Chung64359a52013-07-08 17:17:08 -07002747 // Clear the list of apps
2748 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002749 for (UserHandleCompat user : profiles) {
2750 // Query for the set of apps
2751 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2752 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2753 if (DEBUG_LOADERS) {
2754 Log.d(TAG, "getActivityList took "
2755 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2756 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2757 }
2758 // Fail if we don't have any apps
2759 if (apps == null || apps.isEmpty()) {
2760 return;
2761 }
2762 // Sort the applications by name
2763 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2764 Collections.sort(apps,
2765 new LauncherModel.ShortcutNameComparator(mLabelCache));
2766 if (DEBUG_LOADERS) {
2767 Log.d(TAG, "sort took "
2768 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2769 }
Joe Onorato36115782010-06-17 13:28:48 -04002770
Kenny Guyed131872014-04-30 03:02:21 +01002771 // Create the ApplicationInfos
2772 for (int i = 0; i < apps.size(); i++) {
2773 LauncherActivityInfoCompat app = apps.get(i);
2774 // This builds the icon bitmaps.
2775 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2776 }
Winson Chung64359a52013-07-08 17:17:08 -07002777 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002778 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002779 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2780 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002781
2782 // Post callback on main thread
2783 mHandler.post(new Runnable() {
2784 public void run() {
2785 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002786 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002787 if (callbacks != null) {
2788 callbacks.bindAllApplications(added);
2789 if (DEBUG_LOADERS) {
2790 Log.d(TAG, "bound " + added.size() + " apps in "
2791 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2792 }
2793 } else {
2794 Log.i(TAG, "not binding apps: no Launcher activity");
2795 }
2796 }
2797 });
2798
Joe Onorato36115782010-06-17 13:28:48 -04002799 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002800 Log.d(TAG, "Icons processed in "
2801 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002802 }
2803 }
2804
2805 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002806 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002807 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2808 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2809 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2810 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2811 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2812 }
Joe Onorato36115782010-06-17 13:28:48 -04002813 }
2814 }
2815
2816 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002817 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002818 }
2819
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002820 private class AppsAvailabilityCheck extends BroadcastReceiver {
2821
2822 @Override
2823 public void onReceive(Context context, Intent intent) {
2824 synchronized (sBgLock) {
2825 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2826 .getInstance(mApp.getContext());
2827 ArrayList<String> packagesRemoved;
2828 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2829 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002830 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002831 for (String pkg : entry.getValue()) {
2832 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2833 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2834 packagesRemoved.add(pkg);
2835 }
2836 }
2837 if (!packagesRemoved.isEmpty()) {
2838 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2839 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2840 }
2841 }
2842 sPendingPackages.clear();
2843 }
2844 }
2845 }
2846
Joe Onorato36115782010-06-17 13:28:48 -04002847 private class PackageUpdatedTask implements Runnable {
2848 int mOp;
2849 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002850 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002851
2852 public static final int OP_NONE = 0;
2853 public static final int OP_ADD = 1;
2854 public static final int OP_UPDATE = 2;
2855 public static final int OP_REMOVE = 3; // uninstlled
2856 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2857
2858
Kenny Guyed131872014-04-30 03:02:21 +01002859 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002860 mOp = op;
2861 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002862 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002863 }
2864
2865 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002866 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002867
2868 final String[] packages = mPackages;
2869 final int N = packages.length;
2870 switch (mOp) {
2871 case OP_ADD:
2872 for (int i=0; i<N; i++) {
2873 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002874 mIconCache.remove(packages[i], mUser);
2875 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002876 }
2877 break;
2878 case OP_UPDATE:
2879 for (int i=0; i<N; i++) {
2880 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002881 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002882 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002883 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002884 }
2885 break;
2886 case OP_REMOVE:
2887 case OP_UNAVAILABLE:
2888 for (int i=0; i<N; i++) {
2889 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002890 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002891 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002892 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002893 }
2894 break;
2895 }
2896
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002897 ArrayList<AppInfo> added = null;
2898 ArrayList<AppInfo> modified = null;
2899 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002900
Adam Cohen487f7dd2012-06-28 18:12:10 -07002901 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002902 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002903 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002904 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002905 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002906 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002907 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002908 }
Winson Chung5d55f332012-07-16 20:45:03 -07002909 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002910 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002911 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002912 }
2913
Joe Onorato36115782010-06-17 13:28:48 -04002914 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2915 if (callbacks == null) {
2916 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2917 return;
2918 }
2919
2920 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002921 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002922 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002923 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002924 addAndBindAddedWorkspaceApps(context, addedInfos);
2925 } else {
2926 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002927 }
Joe Onorato36115782010-06-17 13:28:48 -04002928 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002929
Joe Onorato36115782010-06-17 13:28:48 -04002930 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002931 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002932
2933 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002934 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002935 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002936 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002937 for (ItemInfo i : infos) {
2938 if (isShortcutInfoUpdateable(i)) {
2939 ShortcutInfo info = (ShortcutInfo) i;
2940 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002941 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002942 updateItemInDatabase(context, info);
2943 }
2944 }
2945 }
2946
Joe Onorato36115782010-06-17 13:28:48 -04002947 mHandler.post(new Runnable() {
2948 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002949 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2950 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002951 callbacks.bindAppsUpdated(modifiedFinal);
2952 }
2953 }
2954 });
2955 }
Winson Chung83892cc2013-05-01 16:53:33 -07002956
Winson Chungdf95eb12013-10-16 14:57:07 -07002957 final ArrayList<String> removedPackageNames =
2958 new ArrayList<String>();
2959 if (mOp == OP_REMOVE) {
2960 // Mark all packages in the broadcast to be removed
2961 removedPackageNames.addAll(Arrays.asList(packages));
2962 } else if (mOp == OP_UPDATE) {
2963 // Mark disabled packages in the broadcast to be removed
2964 final PackageManager pm = context.getPackageManager();
2965 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002966 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002967 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002968 }
2969 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002970 }
2971 // Remove all the components associated with this package
2972 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002973 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002974 for (ItemInfo i : infos) {
2975 deleteItemFromDatabase(context, i);
2976 }
2977 }
2978 // Remove all the specific components
2979 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002980 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002981 for (ItemInfo i : infos) {
2982 deleteItemFromDatabase(context, i);
2983 }
2984 }
2985 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2986 // Remove any queued items from the install queue
2987 String spKey = LauncherAppState.getSharedPreferencesKey();
2988 SharedPreferences sp =
2989 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2990 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2991 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002992 mHandler.post(new Runnable() {
2993 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002994 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2995 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01002996 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002997 }
2998 }
2999 });
Joe Onoratobe386092009-11-17 17:32:16 -08003000 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003001
Michael Jurkac402cd92013-05-20 15:49:32 +02003002 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003003 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003004 mHandler.post(new Runnable() {
3005 @Override
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) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003009 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003010 }
3011 }
3012 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003013
3014 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003015 mHandler.post(new Runnable() {
3016 public void run() {
3017 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3018 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003019 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003020 }
3021 }
3022 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003023 }
3024 }
3025
Michael Jurkac402cd92013-05-20 15:49:32 +02003026 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3027 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3028 PackageManager packageManager = context.getPackageManager();
3029 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
3030 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
3031 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3032 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
3033 Collections.sort(widgetsAndShortcuts,
3034 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
3035 return widgetsAndShortcuts;
3036 }
3037
Kenny Guyed131872014-04-30 03:02:21 +01003038 private static boolean isPackageDisabled(Context context, String packageName,
3039 UserHandleCompat user) {
3040 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3041 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003042 }
Adam Cohen556f6132014-01-15 15:18:08 -08003043
Kenny Guyed131872014-04-30 03:02:21 +01003044 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3045 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003046 if (cn == null) {
3047 return false;
3048 }
Kenny Guyed131872014-04-30 03:02:21 +01003049 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3050 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003051 return false;
3052 }
Kenny Guyed131872014-04-30 03:02:21 +01003053 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003054 }
3055
Adam Cohena28b78e2014-05-20 17:03:04 -07003056 public static boolean isValidPackage(Context context, String packageName,
3057 UserHandleCompat user) {
3058 if (packageName == null) {
3059 return false;
3060 }
3061 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3062 return launcherApps.isPackageEnabledForProfile(packageName, user);
3063 }
3064
Joe Onorato9c1289c2009-08-17 11:03:03 -04003065 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003066 * Make an ShortcutInfo object for a restored application or shortcut item that points
3067 * to a package that is not yet installed on the system.
3068 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003069 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003070 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003071 if (cursor != null) {
3072 info.title = cursor.getString(titleIndex);
3073 } else {
3074 info.title = "";
3075 }
Kenny Guyed131872014-04-30 03:02:21 +01003076 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003077 info.contentDescription = mUserManager.getBadgedLabelForUser(
3078 info.title.toString(), info.user);
Kenny Guyed131872014-04-30 03:02:21 +01003079 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user));
Chris Wrenf4d08112014-01-16 18:13:56 -05003080 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003081 info.restoredIntent = intent;
Sunny Goyal34846382014-07-09 00:09:28 -07003082 info.wasPromise = true;
Chris Wren40c5ed32014-06-24 18:24:23 -04003083 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003084 return info;
3085 }
3086
3087 /**
3088 * Make an Intent object for a restored application or shortcut item that points
3089 * to the market page for the item.
3090 */
3091 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003092 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05003093 ComponentName componentName = intent.getComponent();
3094 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
3095 Uri marketUri = new Uri.Builder()
3096 .scheme("market")
3097 .authority("details")
3098 .appendQueryParameter("id", componentName.getPackageName())
3099 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05003100 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05003101 marketIntent.setData(marketUri);
3102 return marketIntent;
3103 }
3104
3105 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003106 * This is called from the code that adds shortcuts from the intent receiver. This
3107 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003108 */
Kenny Guyed131872014-04-30 03:02:21 +01003109 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3110 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003111 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003112 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003113
Joe Onorato56d82912010-03-07 14:32:10 -05003114 /**
3115 * Make an ShortcutInfo object for a shortcut that is an application.
3116 *
3117 * If c is not null, then it will be used to fill in missing data like the title and icon.
3118 */
Kenny Guyed131872014-04-30 03:02:21 +01003119 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3120 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003121 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003122 if (user == null) {
3123 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003124 return null;
3125 }
3126
Kenny Guyed131872014-04-30 03:02:21 +01003127 ComponentName componentName = intent.getComponent();
3128 if (componentName == null) {
3129 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3130 return null;
3131 }
3132
3133 Intent newIntent = new Intent(intent.getAction(), null);
3134 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3135 newIntent.setComponent(componentName);
3136 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003137 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003138 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3139 return null;
3140 }
3141
3142 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003143
Joe Onorato56d82912010-03-07 14:32:10 -05003144 // the resource -- This may implicitly give us back the fallback icon,
3145 // but don't worry about that. All we're doing with usingFallbackIcon is
3146 // to avoid saving lots of copies of that in the database, and most apps
3147 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003148 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003149
Joe Onorato56d82912010-03-07 14:32:10 -05003150 // the db
3151 if (icon == null) {
3152 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003153 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003154 }
3155 }
3156 // the fallback icon
3157 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003158 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003159 info.usingFallbackIcon = true;
3160 }
3161 info.setIcon(icon);
3162
Kenny Guyed131872014-04-30 03:02:21 +01003163 // From the cache.
3164 if (labelCache != null) {
3165 info.title = labelCache.get(componentName);
3166 }
3167
Joe Onorato56d82912010-03-07 14:32:10 -05003168 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003169 if (info.title == null && lai != null) {
3170 info.title = lai.getLabel();
3171 if (labelCache != null) {
3172 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003173 }
Joe Onorato56d82912010-03-07 14:32:10 -05003174 }
3175 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003176 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003177 if (c != null) {
3178 info.title = c.getString(titleIndex);
3179 }
3180 }
3181 // fall back to the class name of the activity
3182 if (info.title == null) {
3183 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003184 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003185 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003186 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003187 info.contentDescription = mUserManager.getBadgedLabelForUser(
3188 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003189 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003190 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003191
Winson Chung64359a52013-07-08 17:17:08 -07003192 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3193 ItemInfoFilter f) {
3194 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3195 for (ItemInfo i : infos) {
3196 if (i instanceof ShortcutInfo) {
3197 ShortcutInfo info = (ShortcutInfo) i;
3198 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003199 if (info.restoredIntent != null) {
3200 cn = info.restoredIntent.getComponent();
3201 }
Winson Chung64359a52013-07-08 17:17:08 -07003202 if (cn != null && f.filterItem(null, info, cn)) {
3203 filtered.add(info);
3204 }
3205 } else if (i instanceof FolderInfo) {
3206 FolderInfo info = (FolderInfo) i;
3207 for (ShortcutInfo s : info.contents) {
3208 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003209 if (s.restoredIntent != null) {
3210 cn = s.restoredIntent.getComponent();
3211 }
Winson Chung64359a52013-07-08 17:17:08 -07003212 if (cn != null && f.filterItem(info, s, cn)) {
3213 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003214 }
3215 }
Winson Chung64359a52013-07-08 17:17:08 -07003216 } else if (i instanceof LauncherAppWidgetInfo) {
3217 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3218 ComponentName cn = info.providerName;
3219 if (cn != null && f.filterItem(null, info, cn)) {
3220 filtered.add(info);
3221 }
Winson Chung8a435102012-08-30 17:16:53 -07003222 }
3223 }
Winson Chung64359a52013-07-08 17:17:08 -07003224 return new ArrayList<ItemInfo>(filtered);
3225 }
3226
Kenny Guyed131872014-04-30 03:02:21 +01003227 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3228 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003229 ItemInfoFilter filter = new ItemInfoFilter() {
3230 @Override
3231 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003232 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003233 }
3234 };
3235 return filterItemInfos(sBgItemsIdMap.values(), filter);
3236 }
3237
Kenny Guyed131872014-04-30 03:02:21 +01003238 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3239 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003240 ItemInfoFilter filter = new ItemInfoFilter() {
3241 @Override
3242 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003243 if (info.user == null) {
3244 return cn.equals(cname);
3245 } else {
3246 return cn.equals(cname) && info.user.equals(user);
3247 }
Winson Chung64359a52013-07-08 17:17:08 -07003248 }
3249 };
3250 return filterItemInfos(sBgItemsIdMap.values(), filter);
3251 }
3252
3253 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3254 if (i instanceof ShortcutInfo) {
3255 ShortcutInfo info = (ShortcutInfo) i;
3256 // We need to check for ACTION_MAIN otherwise getComponent() might
3257 // return null for some shortcuts (for instance, for shortcuts to
3258 // web pages.)
3259 Intent intent = info.intent;
3260 ComponentName name = intent.getComponent();
3261 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3262 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3263 return true;
3264 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003265 // placeholder shortcuts get special treatment, let them through too.
3266 if (info.getRestoredIntent() != null) {
3267 return true;
3268 }
Winson Chung64359a52013-07-08 17:17:08 -07003269 }
3270 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003271 }
3272
3273 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003274 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003275 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003276 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003277 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3278 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003279
Joe Onorato56d82912010-03-07 14:32:10 -05003280 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003281 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003282 // Non-app shortcuts are only supported for current user.
3283 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003284 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003285
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003286 // TODO: If there's an explicit component and we can't install that, delete it.
3287
Joe Onorato56d82912010-03-07 14:32:10 -05003288 info.title = c.getString(titleIndex);
3289
Joe Onorato9c1289c2009-08-17 11:03:03 -04003290 int iconType = c.getInt(iconTypeIndex);
3291 switch (iconType) {
3292 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3293 String packageName = c.getString(iconPackageIndex);
3294 String resourceName = c.getString(iconResourceIndex);
3295 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003296 info.customIcon = false;
3297 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003298 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003299 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003300 if (resources != null) {
3301 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003302 icon = Utilities.createIconBitmap(
3303 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003304 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003305 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003306 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003307 }
Joe Onorato56d82912010-03-07 14:32:10 -05003308 // the db
3309 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003310 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003311 }
3312 // the fallback icon
3313 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003314 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003315 info.usingFallbackIcon = true;
3316 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003317 break;
3318 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003319 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003320 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003321 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003322 info.customIcon = false;
3323 info.usingFallbackIcon = true;
3324 } else {
3325 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003326 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003327 break;
3328 default:
Kenny Guyed131872014-04-30 03:02:21 +01003329 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003330 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003331 info.customIcon = false;
3332 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003333 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003334 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003335 return info;
3336 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003337
Michael Jurka931dc972011-08-05 15:08:15 -07003338 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003339 @SuppressWarnings("all") // suppress dead code warning
3340 final boolean debug = false;
3341 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003342 Log.d(TAG, "getIconFromCursor app="
3343 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3344 }
3345 byte[] data = c.getBlob(iconIndex);
3346 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003347 return Utilities.createIconBitmap(
3348 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003349 } catch (Exception e) {
3350 return null;
3351 }
3352 }
3353
Winson Chung3d503fb2011-07-13 17:25:49 -07003354 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3355 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003356 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003357 if (info == null) {
3358 return null;
3359 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003360 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003361
3362 return info;
3363 }
3364
Winson Chunga9abd0e2010-10-27 17:18:37 -07003365 /**
Winson Chung55cef262010-10-28 14:14:18 -07003366 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3367 */
3368 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3369 ComponentName component) {
3370 List<AppWidgetProviderInfo> widgets =
3371 AppWidgetManager.getInstance(context).getInstalledProviders();
3372 for (AppWidgetProviderInfo info : widgets) {
3373 if (info.provider.equals(component)) {
3374 return info;
3375 }
3376 }
3377 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003378 }
3379
Winson Chung68846fd2010-10-29 11:00:27 -07003380 /**
3381 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3382 */
3383 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3384 final PackageManager packageManager = context.getPackageManager();
3385 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3386 new ArrayList<WidgetMimeTypeHandlerData>();
3387
3388 final Intent supportsIntent =
3389 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3390 supportsIntent.setType(mimeType);
3391
3392 // Create a set of widget configuration components that we can test against
3393 final List<AppWidgetProviderInfo> widgets =
3394 AppWidgetManager.getInstance(context).getInstalledProviders();
3395 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3396 new HashMap<ComponentName, AppWidgetProviderInfo>();
3397 for (AppWidgetProviderInfo info : widgets) {
3398 configurationComponentToWidget.put(info.configure, info);
3399 }
3400
3401 // Run through each of the intents that can handle this type of clip data, and cross
3402 // reference them with the components that are actual configuration components
3403 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3404 PackageManager.MATCH_DEFAULT_ONLY);
3405 for (ResolveInfo info : activities) {
3406 final ActivityInfo activityInfo = info.activityInfo;
3407 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3408 activityInfo.name);
3409 if (configurationComponentToWidget.containsKey(infoComponent)) {
3410 supportedConfigurationActivities.add(
3411 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3412 configurationComponentToWidget.get(infoComponent)));
3413 }
3414 }
3415 return supportedConfigurationActivities;
3416 }
3417
Winson Chunga9abd0e2010-10-27 17:18:37 -07003418 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003419 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3420 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3421 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3422
Adam Cohend9198822011-11-22 16:42:47 -08003423 if (intent == null) {
3424 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3425 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3426 return null;
3427 }
3428
Joe Onorato0589f0f2010-02-08 13:44:00 -08003429 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003430 boolean customIcon = false;
3431 ShortcutIconResource iconResource = null;
3432
3433 if (bitmap != null && bitmap instanceof Bitmap) {
3434 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003435 customIcon = true;
3436 } else {
3437 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3438 if (extra != null && extra instanceof ShortcutIconResource) {
3439 try {
3440 iconResource = (ShortcutIconResource) extra;
3441 final PackageManager packageManager = context.getPackageManager();
3442 Resources resources = packageManager.getResourcesForApplication(
3443 iconResource.packageName);
3444 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003445 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003446 mIconCache.getFullResIcon(resources, id),
3447 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003448 } catch (Exception e) {
3449 Log.w(TAG, "Could not load shortcut icon: " + extra);
3450 }
3451 }
3452 }
3453
Michael Jurkac9d95c52011-08-29 14:03:34 -07003454 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003455
Kenny Guyed131872014-04-30 03:02:21 +01003456 // Only support intents for current user for now. Intents sent from other
3457 // users wouldn't get here without intent forwarding anyway.
3458 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003459 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003460 if (fallbackIcon != null) {
3461 icon = fallbackIcon;
3462 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003463 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003464 info.usingFallbackIcon = true;
3465 }
Joe Onorato56d82912010-03-07 14:32:10 -05003466 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003467 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003468
Joe Onorato0589f0f2010-02-08 13:44:00 -08003469 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003470 info.contentDescription = mUserManager.getBadgedLabelForUser(
3471 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003472 info.intent = intent;
3473 info.customIcon = customIcon;
3474 info.iconResource = iconResource;
3475
3476 return info;
3477 }
3478
Winson Chungaac01e12011-08-17 10:37:13 -07003479 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3480 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003481 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003482 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003483 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003484 }
Joe Onorato56d82912010-03-07 14:32:10 -05003485 // If this icon doesn't have a custom icon, check to see
3486 // what's stored in the DB, and if it doesn't match what
3487 // we're going to show, store what we are going to show back
3488 // into the DB. We do this so when we're loading, if the
3489 // package manager can't find an icon (for example because
3490 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003491 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003492 cache.put(info, c.getBlob(iconIndex));
3493 return true;
3494 }
3495 return false;
3496 }
3497 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3498 boolean needSave = false;
3499 try {
3500 if (data != null) {
3501 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3502 Bitmap loaded = info.getIcon(mIconCache);
3503 needSave = !saved.sameAs(loaded);
3504 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003505 needSave = true;
3506 }
Winson Chungaac01e12011-08-17 10:37:13 -07003507 } catch (Exception e) {
3508 needSave = true;
3509 }
3510 if (needSave) {
3511 Log.d(TAG, "going to save icon bitmap for info=" + info);
3512 // This is slower than is ideal, but this only happens once
3513 // or when the app is updated with a new icon.
3514 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003515 }
3516 }
3517
Joe Onorato9c1289c2009-08-17 11:03:03 -04003518 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003519 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003520 * or make a new one.
3521 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003522 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003523 // See if a placeholder was created for us already
3524 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003525 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003526 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003527 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003528 folders.put(id, folderInfo);
3529 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003530 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003531 }
3532
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003533 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003534 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003535 return new Comparator<AppInfo>() {
3536 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003537 if (a.user.equals(b.user)) {
3538 int result = collator.compare(a.title.toString().trim(),
3539 b.title.toString().trim());
3540 if (result == 0) {
3541 result = a.componentName.compareTo(b.componentName);
3542 }
3543 return result;
3544 } else {
3545 // TODO Need to figure out rules for sorting
3546 // profiles, this puts work second.
3547 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003548 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003549 }
Winson Chung11904872012-09-17 16:58:46 -07003550 };
3551 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003552 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3553 = new Comparator<AppInfo>() {
3554 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003555 if (a.firstInstallTime < b.firstInstallTime) return 1;
3556 if (a.firstInstallTime > b.firstInstallTime) return -1;
3557 return 0;
3558 }
3559 };
Winson Chung11904872012-09-17 16:58:46 -07003560 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3561 final Collator collator = Collator.getInstance();
3562 return new Comparator<AppWidgetProviderInfo>() {
3563 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003564 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003565 }
3566 };
3567 }
Winson Chung5308f242011-08-18 12:12:41 -07003568 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3569 if (info.activityInfo != null) {
3570 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3571 } else {
3572 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3573 }
3574 }
Kenny Guyed131872014-04-30 03:02:21 +01003575 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003576 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003577 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003578 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003579 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003580 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003581 }
Kenny Guyed131872014-04-30 03:02:21 +01003582 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003583 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003584 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003585 }
Kenny Guyed131872014-04-30 03:02:21 +01003586 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003587 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003588 ComponentName keyA = a.getComponentName();
3589 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003590 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003591 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003592 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003593 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003594
Winson Chung5308f242011-08-18 12:12:41 -07003595 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003596 }
Winson Chung5308f242011-08-18 12:12:41 -07003597 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003598 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003599 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003600 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003601
Winson Chung5308f242011-08-18 12:12:41 -07003602 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003603 }
Winson Chung11904872012-09-17 16:58:46 -07003604 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003605 }
3606 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003607 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003608 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003609 private PackageManager mPackageManager;
3610 private HashMap<Object, String> mLabelCache;
3611 WidgetAndShortcutNameComparator(PackageManager pm) {
3612 mPackageManager = pm;
3613 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003614 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003615 }
3616 public final int compare(Object a, Object b) {
3617 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003618 if (mLabelCache.containsKey(a)) {
3619 labelA = mLabelCache.get(a);
3620 } else {
3621 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003622 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003623 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003624 mLabelCache.put(a, labelA);
3625 }
3626 if (mLabelCache.containsKey(b)) {
3627 labelB = mLabelCache.get(b);
3628 } else {
3629 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003630 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003631 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003632 mLabelCache.put(b, labelB);
3633 }
Winson Chung11904872012-09-17 16:58:46 -07003634 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003635 }
3636 };
Joe Onoratobe386092009-11-17 17:32:16 -08003637
Sunny Goyal651077b2014-06-30 14:15:31 -07003638 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3639 return (provider != null) && (provider.provider != null)
3640 && (provider.provider.getPackageName() != null);
3641 }
3642
Joe Onoratobe386092009-11-17 17:32:16 -08003643 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003644 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003645 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3646 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3647 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3648 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003649 if (mLoaderTask != null) {
3650 mLoaderTask.dumpState();
3651 } else {
3652 Log.d(TAG, "mLoaderTask=null");
3653 }
Joe Onoratobe386092009-11-17 17:32:16 -08003654 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003655}