blob: 673fef981d983eef6a8b9c2e0f41288a7a049751 [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
169 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages = new HashMap<>();
170
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700171 // </ only access in worker thread >
172
173 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174
Reena Lee99a73f32011-10-24 17:27:37 -0700175 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700176
Kenny Guyed131872014-04-30 03:02:21 +0100177 private final LauncherAppsCompat mLauncherApps;
178 private final UserManagerCompat mUserManager;
179
Joe Onorato9c1289c2009-08-17 11:03:03 -0400180 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700181 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400182 public int getCurrentWorkspaceScreen();
183 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700184 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
185 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700186 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700187 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500188 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700189 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400190 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200191 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700192 public void bindAppsAdded(ArrayList<Long> newScreens,
193 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700194 ArrayList<ItemInfo> addAnimated,
195 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200196 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500197 public void updatePackageState(String pkgName, int state);
Winson Chung83892cc2013-05-01 16:53:33 -0700198 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100199 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200200 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100201 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700202 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700203 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700204 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206
Winson Chung64359a52013-07-08 17:17:08 -0700207 public interface ItemInfoFilter {
208 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
209 }
210
Bjorn Bringert1307f632013-10-03 22:31:03 +0100211 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800212 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400213
Winson Chungee055712013-07-30 14:46:24 -0700214 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700215 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400216 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
217 // resource string.
218 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
219 ProviderInfo providerInfo =
220 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
221 ProviderInfo redirectProvider =
222 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700223
224 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400225 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700226
227 if (mOldContentProviderExists) {
228 Log.d(TAG, "Old launcher provider exists.");
229 } else {
230 Log.d(TAG, "Old launcher provider does not exist.");
231 }
232
Daniel Sandlere4f98912013-06-25 15:13:26 -0400233 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100234 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800235 mIconCache = iconCache;
236
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400237 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700238 Configuration config = res.getConfiguration();
239 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100240 mLauncherApps = LauncherAppsCompat.getInstance(context);
241 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800242 }
243
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700244 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
245 * posted on the main thread handler. */
246 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700247 runOnMainThread(r, 0);
248 }
249 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700250 if (sWorkerThread.getThreadId() == Process.myTid()) {
251 // If we are on the worker thread, post onto the main handler
252 mHandler.post(r);
253 } else {
254 r.run();
255 }
256 }
257
258 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
259 * posted on the worker thread handler. */
260 private static void runOnWorkerThread(Runnable r) {
261 if (sWorkerThread.getThreadId() == Process.myTid()) {
262 r.run();
263 } else {
264 // If we are not on the worker thread, then post to the worker handler
265 sWorker.post(r);
266 }
267 }
268
Winson Chunge43a1e72014-01-15 10:33:02 -0800269 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
270 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800271 }
272
Winson Chungc9168342013-06-26 14:54:55 -0700273 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
274 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700275 LauncherAppState app = LauncherAppState.getInstance();
276 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
277 final int xCount = (int) grid.numColumns;
278 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700279 boolean[][] occupied = new boolean[xCount][yCount];
280
281 int cellX, cellY, spanX, spanY;
282 for (int i = 0; i < items.size(); ++i) {
283 final ItemInfo item = items.get(i);
284 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
285 if (item.screenId == screen) {
286 cellX = item.cellX;
287 cellY = item.cellY;
288 spanX = item.spanX;
289 spanY = item.spanY;
290 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
291 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
292 occupied[x][y] = true;
293 }
294 }
295 }
296 }
297 }
298
299 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
300 }
301 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700302 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700303 int firstScreenIndex,
304 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700305 // Lock on the app so that we don't try and get the items while apps are being added
306 LauncherAppState app = LauncherAppState.getInstance();
307 LauncherModel model = app.getModel();
308 boolean found = false;
309 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700310 if (sWorkerThread.getThreadId() != Process.myTid()) {
311 // Flush the LauncherModel worker thread, so that if we just did another
312 // processInstallShortcut, we give it time for its shortcut to get added to the
313 // database (getItemsInLocalCoordinates reads the database)
314 model.flushWorkerThread();
315 }
Winson Chungc9168342013-06-26 14:54:55 -0700316 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700317
318 // Try adding to the workspace screens incrementally, starting at the default or center
319 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700320 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
321 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700322 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700323 int[] tmpCoordinates = new int[2];
324 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700325 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700326 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700327 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700328 }
329 }
330 }
Winson Chungc9168342013-06-26 14:54:55 -0700331 return null;
332 }
333
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500334 public void setPackageState(final String pkgName, final int state) {
335 // Process the updated package state
336 Runnable r = new Runnable() {
337 public void run() {
338 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
339 if (callbacks != null) {
340 callbacks.updatePackageState(pkgName, state);
341 }
342 }
343 };
344 mHandler.post(r);
345 }
346
Adam Cohen76a47a12014-02-05 11:47:43 -0800347 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
348 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
349
350 if (allAppsApps == null) {
351 throw new RuntimeException("allAppsApps must not be null");
352 }
353 if (allAppsApps.isEmpty()) {
354 return;
355 }
356
Chris Wrenb6d4c282014-01-27 14:17:08 -0500357 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
358 Iterator<AppInfo> iter = allAppsApps.iterator();
359 while (iter.hasNext()) {
360 ItemInfo a = iter.next();
Kenny Guyed131872014-04-30 03:02:21 +0100361 if (LauncherModel.appWasRestored(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500362 restoredAppsFinal.add((AppInfo) a);
363 }
364 }
365
Adam Cohen76a47a12014-02-05 11:47:43 -0800366 // Process the newly added applications and add them to the database first
367 Runnable r = new Runnable() {
368 public void run() {
369 runOnMainThread(new Runnable() {
370 public void run() {
371 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
372 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500373 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500374 for (AppInfo info : restoredAppsFinal) {
375 final Intent intent = info.getIntent();
376 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100377 mIconCache.deletePreloadedIcon(intent.getComponent(),
378 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500379 }
380 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500381 callbacks.bindAppsUpdated(restoredAppsFinal);
382 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500383 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800384 }
385 }
386 });
387 }
388 };
389 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700390 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800391
392 public void addAndBindAddedWorkspaceApps(final Context context,
393 final ArrayList<ItemInfo> workspaceApps) {
394 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
395
396 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800397 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
398 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800399 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700400 return;
Winson Chung997a9232013-07-24 15:33:46 -0700401 }
Winson Chung64359a52013-07-08 17:17:08 -0700402 // Process the newly added applications and add them to the database first
403 Runnable r = new Runnable() {
404 public void run() {
405 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
406 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500407 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700408
Winson Chung76828c82013-08-19 15:43:29 -0700409 // Get the list of workspace screens. We need to append to this list and
410 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
411 // called.
412 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
413 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
414 for (Integer i : orderedScreens.keySet()) {
415 long screenId = orderedScreens.get(i);
416 workspaceScreens.add(screenId);
417 }
418
Winson Chung64359a52013-07-08 17:17:08 -0700419 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700420 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700421 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700422 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700423 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700424 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700425
426 // Short-circuit this logic if the icon exists somewhere on the workspace
427 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500428 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
429 if (a instanceof AppInfo &&
Kenny Guyed131872014-04-30 03:02:21 +0100430 LauncherModel.appWasRestored(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500431 restoredAppsFinal.add((AppInfo) a);
432 }
Winson Chung64359a52013-07-08 17:17:08 -0700433 continue;
434 }
435
Winson Chung87412982013-10-03 18:34:14 -0700436 // Add this icon to the db, creating a new page if necessary. If there
437 // is only the empty page then we just add items to the first page.
438 // Otherwise, we add them to the next pages.
439 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700440 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700441 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700442 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200443 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700444
445 // If we can't find a valid position, then just add a new screen.
446 // This takes time so we need to re-queue the add until the new
447 // page is added. Create as many screens as necessary to satisfy
448 // the startSearchPageIndex.
449 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700450 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700451 while (numPagesToAdd > 0) {
452 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700453 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700454 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700455 addedWorkspaceScreensFinal.add(screenId);
456 numPagesToAdd--;
457 }
Winson Chung76828c82013-08-19 15:43:29 -0700458
Winson Chung64359a52013-07-08 17:17:08 -0700459 // Find the coordinate again
460 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700461 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700462 }
463 if (coords == null) {
464 throw new RuntimeException("Coordinates should not be null");
465 }
466
Winson Chung997a9232013-07-24 15:33:46 -0700467 ShortcutInfo shortcutInfo;
468 if (a instanceof ShortcutInfo) {
469 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200470 } else if (a instanceof AppInfo) {
471 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700472 } else {
473 throw new RuntimeException("Unexpected info type");
474 }
Winson Chung94d67682013-09-25 16:29:40 -0700475
Winson Chung64359a52013-07-08 17:17:08 -0700476 // Add the shortcut to the db
477 addItemToDatabase(context, shortcutInfo,
478 LauncherSettings.Favorites.CONTAINER_DESKTOP,
479 coords.first, coords.second[0], coords.second[1], false);
480 // Save the ShortcutInfo for binding in the workspace
481 addedShortcutsFinal.add(shortcutInfo);
482 }
483 }
484
Winson Chung76828c82013-08-19 15:43:29 -0700485 // Update the workspace screens
486 updateWorkspaceScreenOrder(context, workspaceScreens);
487
Adam Cohen76a47a12014-02-05 11:47:43 -0800488 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700489 runOnMainThread(new Runnable() {
490 public void run() {
491 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
492 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700493 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
494 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700495 if (!addedShortcutsFinal.isEmpty()) {
496 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
497 long lastScreenId = info.screenId;
498 for (ItemInfo i : addedShortcutsFinal) {
499 if (i.screenId == lastScreenId) {
500 addAnimated.add(i);
501 } else {
502 addNotAnimated.add(i);
503 }
Winson Chung997a9232013-07-24 15:33:46 -0700504 }
505 }
Winson Chungd64d1762013-08-20 14:37:16 -0700506 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800507 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500508 if (!restoredAppsFinal.isEmpty()) {
509 callbacks.bindAppsUpdated(restoredAppsFinal);
510 }
Winson Chung997a9232013-07-24 15:33:46 -0700511 }
Winson Chung64359a52013-07-08 17:17:08 -0700512 }
Winson Chung997a9232013-07-24 15:33:46 -0700513 });
514 }
Winson Chung64359a52013-07-08 17:17:08 -0700515 }
516 };
517 runOnWorkerThread(r);
518 }
519
Winson Chung81b52252012-08-27 15:34:29 -0700520 public void unbindItemInfosAndClearQueuedBindRunnables() {
521 if (sWorkerThread.getThreadId() == Process.myTid()) {
522 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
523 "main thread");
524 }
525
526 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400527 synchronized (mDeferredBindRunnables) {
528 mDeferredBindRunnables.clear();
529 }
Winson Chung81b52252012-08-27 15:34:29 -0700530 // Remove any queued bind runnables
531 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
532 // Unbind all the workspace items
533 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700534 }
535
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700536 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700537 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700538 // Ensure that we don't use the same workspace items data structure on the main thread
539 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700540 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
541 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700542 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700543 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
544 tmpAppWidgets.addAll(sBgAppWidgets);
545 }
546 Runnable r = new Runnable() {
547 @Override
548 public void run() {
549 for (ItemInfo item : tmpWorkspaceItems) {
550 item.unbind();
551 }
552 for (ItemInfo item : tmpAppWidgets) {
553 item.unbind();
554 }
555 }
556 };
557 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700558 }
559
Joe Onorato9c1289c2009-08-17 11:03:03 -0400560 /**
561 * Adds an item to the DB if it was not created previously, or move it to a new
562 * <container, screen, cellX, cellY>
563 */
564 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700565 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400566 if (item.container == ItemInfo.NO_ID) {
567 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700568 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400569 } else {
570 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800572 }
573 }
574
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700575 static void checkItemInfoLocked(
576 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
577 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
578 if (modelItem != null && item != modelItem) {
579 // check all the data is consistent
580 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
581 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
582 ShortcutInfo shortcut = (ShortcutInfo) item;
583 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
584 modelShortcut.intent.filterEquals(shortcut.intent) &&
585 modelShortcut.id == shortcut.id &&
586 modelShortcut.itemType == shortcut.itemType &&
587 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700588 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700589 modelShortcut.cellX == shortcut.cellX &&
590 modelShortcut.cellY == shortcut.cellY &&
591 modelShortcut.spanX == shortcut.spanX &&
592 modelShortcut.spanY == shortcut.spanY &&
593 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
594 (modelShortcut.dropPos != null &&
595 shortcut.dropPos != null &&
596 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
597 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
598 // For all intents and purposes, this is the same object
599 return;
600 }
601 }
602
603 // the modelItem needs to match up perfectly with item if our model is
604 // to be consistent with the database-- for now, just require
605 // modelItem == item or the equality check above
606 String msg = "item: " + ((item != null) ? item.toString() : "null") +
607 "modelItem: " +
608 ((modelItem != null) ? modelItem.toString() : "null") +
609 "Error: ItemInfo passed to checkItemInfo doesn't match original";
610 RuntimeException e = new RuntimeException(msg);
611 if (stackTrace != null) {
612 e.setStackTrace(stackTrace);
613 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800614 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700615 }
616 }
617
Michael Jurka816474f2012-06-25 14:49:02 -0700618 static void checkItemInfo(final ItemInfo item) {
619 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
620 final long itemId = item.id;
621 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700622 public void run() {
623 synchronized (sBgLock) {
624 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700625 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700626 }
627 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700628 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700629 }
630
Michael Jurkac9d95c52011-08-29 14:03:34 -0700631 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
632 final ItemInfo item, final String callingFunction) {
633 final long itemId = item.id;
634 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
635 final ContentResolver cr = context.getContentResolver();
636
Adam Cohen487f7dd2012-06-28 18:12:10 -0700637 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700638 Runnable r = new Runnable() {
639 public void run() {
640 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700641 updateItemArrays(item, itemId, stackTrace);
642 }
643 };
644 runOnWorkerThread(r);
645 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700646
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700647 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
648 final ArrayList<ItemInfo> items, final String callingFunction) {
649 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700650
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700651 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
652 Runnable r = new Runnable() {
653 public void run() {
654 ArrayList<ContentProviderOperation> ops =
655 new ArrayList<ContentProviderOperation>();
656 int count = items.size();
657 for (int i = 0; i < count; i++) {
658 ItemInfo item = items.get(i);
659 final long itemId = item.id;
660 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
661 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700662
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700663 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
664 updateItemArrays(item, itemId, stackTrace);
665
666 }
667 try {
668 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
669 } catch (Exception e) {
670 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700671 }
672 }
673 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700674 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700675 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700676
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700677 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
678 // Lock on mBgLock *after* the db operation
679 synchronized (sBgLock) {
680 checkItemInfoLocked(itemId, item, stackTrace);
681
682 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
683 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
684 // Item is in a folder, make sure this folder exists
685 if (!sBgFolders.containsKey(item.container)) {
686 // An items container is being set to a that of an item which is not in
687 // the list of Folders.
688 String msg = "item: " + item + " container being set to: " +
689 item.container + ", not in the list of folders";
690 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700691 }
692 }
693
694 // Items are added/removed from the corresponding FolderInfo elsewhere, such
695 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
696 // that are on the desktop, as appropriate
697 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800698 if (modelItem != null &&
699 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
700 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700701 switch (modelItem.itemType) {
702 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
703 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
704 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
705 if (!sBgWorkspaceItems.contains(modelItem)) {
706 sBgWorkspaceItems.add(modelItem);
707 }
708 break;
709 default:
710 break;
711 }
712 } else {
713 sBgWorkspaceItems.remove(modelItem);
714 }
715 }
716 }
717
Michael Jurkac7700af2013-05-14 20:17:58 +0200718 public void flushWorkerThread() {
719 mFlushingWorkerThread = true;
720 Runnable waiter = new Runnable() {
721 public void run() {
722 synchronized (this) {
723 notifyAll();
724 mFlushingWorkerThread = false;
725 }
726 }
727 };
728
729 synchronized(waiter) {
730 runOnWorkerThread(waiter);
731 if (mLoaderTask != null) {
732 synchronized(mLoaderTask) {
733 mLoaderTask.notify();
734 }
735 }
736 boolean success = false;
737 while (!success) {
738 try {
739 waiter.wait();
740 success = true;
741 } catch (InterruptedException e) {
742 }
743 }
744 }
745 }
746
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800747 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400748 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700749 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700750 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400752 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400753 item.cellX = cellX;
754 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700755
Winson Chung3d503fb2011-07-13 17:25:49 -0700756 // We store hotseat items in canonical form which is this orientation invariant position
757 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700759 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700763 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400764
765 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700767 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
768 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700769 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400770
Michael Jurkac9d95c52011-08-29 14:03:34 -0700771 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700772 }
773
774 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700775 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
776 * cellX, cellY have already been updated on the ItemInfos.
777 */
778 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
779 final long container, final int screen) {
780
781 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
782 int count = items.size();
783
784 for (int i = 0; i < count; i++) {
785 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700786 item.container = container;
787
788 // We store hotseat items in canonical form which is this orientation invariant position
789 // in the hotseat
790 if (context instanceof Launcher && screen < 0 &&
791 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700792 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700793 item.cellY);
794 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700796 }
797
798 final ContentValues values = new ContentValues();
799 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
800 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
801 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700802 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700803
804 contentValues.add(values);
805 }
806 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
807 }
808
809 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700810 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800811 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700812 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700814 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800815 item.cellX = cellX;
816 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700817 item.spanX = spanX;
818 item.spanY = spanY;
819
820 // We store hotseat items in canonical form which is this orientation invariant position
821 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700822 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700823 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700825 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 }
Adam Cohend4844c32011-02-18 19:25:06 -0800828
Adam Cohend4844c32011-02-18 19:25:06 -0800829 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800830 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700831 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
832 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
833 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
834 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700835 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800836
Michael Jurka816474f2012-06-25 14:49:02 -0700837 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700838 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700839
840 /**
841 * Update an item to the database in a specified container.
842 */
843 static void updateItemInDatabase(Context context, final ItemInfo item) {
844 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100845 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700846 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
847 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800848 }
849
850 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400851 * Returns true if the shortcuts already exists in the database.
852 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800853 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 static boolean shortcutExists(Context context, String title, Intent intent) {
855 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700856 final Intent intentWithPkg, intentWithoutPkg;
857
858 if (intent.getComponent() != null) {
859 // If component is not null, an intent with null package will produce
860 // the same result and should also be a match.
861 if (intent.getPackage() != null) {
862 intentWithPkg = intent;
863 intentWithoutPkg = new Intent(intent).setPackage(null);
864 } else {
865 intentWithPkg = new Intent(intent).setPackage(
866 intent.getComponent().getPackageName());
867 intentWithoutPkg = intent;
868 }
869 } else {
870 intentWithPkg = intent;
871 intentWithoutPkg = intent;
872 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400873 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700874 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
875 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400876 boolean result = false;
877 try {
878 result = c.moveToFirst();
879 } finally {
880 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800881 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400882 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700883 }
884
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 /**
Chris Wrenb6d4c282014-01-27 14:17:08 -0500886 * Returns true if the shortcuts already exists in the database.
Kenny Guyed131872014-04-30 03:02:21 +0100887 * we identify a shortcut by the component name of the intent
888 * and the user.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500889 */
Kenny Guyed131872014-04-30 03:02:21 +0100890 static boolean appWasRestored(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500891 final ContentResolver cr = context.getContentResolver();
892 final ComponentName component = intent.getComponent();
893 if (component == null) {
894 return false;
895 }
896 String componentName = component.flattenToString();
Chris Wren0e584b52014-05-12 16:07:25 -0400897 String shortName = component.flattenToShortString();
Kenny Guyed131872014-04-30 03:02:21 +0100898 long serialNumber = UserManagerCompat.getInstance(context)
899 .getSerialNumberForUser(user);
Chris Wren0e584b52014-05-12 16:07:25 -0400900 final String where = "(intent glob \"*component=" + componentName + "*\" or " +
901 "intent glob \"*component=" + shortName + "*\")" +
902 "and restored = 1 and profileId = " + serialNumber;
Chris Wrenb6d4c282014-01-27 14:17:08 -0500903 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Kenny Guyed131872014-04-30 03:02:21 +0100904 new String[]{"intent", "restored", "profileId"}, where, null, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500905 boolean result = false;
906 try {
907 result = c.moveToFirst();
908 } finally {
909 c.close();
910 }
911 Log.d(TAG, "shortcutWasRestored is " + result + " for " + componentName);
912 return result;
913 }
914
915 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 * Returns an ItemInfo array containing all the items in the LauncherModel.
917 * The ItemInfo.id is not set through this function.
918 */
919 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
920 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
921 final ContentResolver cr = context.getContentResolver();
922 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
923 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100924 LauncherSettings.Favorites.SCREEN,
925 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
926 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
927 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700928
929 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
930 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
931 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
932 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
933 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
934 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
935 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100936 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
937 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700938 try {
939 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700940 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700941 item.cellX = c.getInt(cellXIndex);
942 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700943 item.spanX = Math.max(1, c.getInt(spanXIndex));
944 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700945 item.container = c.getInt(containerIndex);
946 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100948 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100949 item.user = userManager.getUserForSerialNumber(serialNumber);
950 // Skip if user has been deleted.
951 if (item.user != null) {
952 items.add(item);
953 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700954 }
955 } catch (Exception e) {
956 items.clear();
957 } finally {
958 c.close();
959 }
960
961 return items;
962 }
963
964 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
966 */
967 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
968 final ContentResolver cr = context.getContentResolver();
969 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
970 "_id=? and (itemType=? or itemType=?)",
971 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700972 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700973
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 try {
975 if (c.moveToFirst()) {
976 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
977 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
978 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
979 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
980 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
981 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800982
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 FolderInfo folderInfo = null;
984 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700985 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
986 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400987 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700988 }
989
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 folderInfo.title = c.getString(titleIndex);
991 folderInfo.id = id;
992 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700994 folderInfo.cellX = c.getInt(cellXIndex);
995 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996
997 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700998 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999 } finally {
1000 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001001 }
1002
1003 return null;
1004 }
1005
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006 /**
1007 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1008 * cellY fields of the item. Also assigns an ID to the item.
1009 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001010 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013 item.cellX = cellX;
1014 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001015 // We store hotseat items in canonical form which is this orientation invariant position
1016 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001017 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001018 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001020 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001022 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001023
1024 final ContentValues values = new ContentValues();
1025 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001026 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001027
Michael Jurka414300a2013-08-27 15:42:35 +02001028 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001029 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001030 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001031
Jason Monk8e19cf22014-03-20 15:06:57 -04001032 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001033 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001034 public void run() {
1035 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1036 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001037
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001039 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001040 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 sBgItemsIdMap.put(item.id, item);
1042 switch (item.itemType) {
1043 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1044 sBgFolders.put(item.id, (FolderInfo) item);
1045 // Fall through
1046 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1047 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1048 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1049 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1050 sBgWorkspaceItems.add(item);
1051 } else {
1052 if (!sBgFolders.containsKey(item.container)) {
1053 // Adding an item to a folder that doesn't exist.
1054 String msg = "adding item: " + item + " to a folder that " +
1055 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001056 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001058 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001059 break;
1060 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1061 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1062 break;
1063 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001064 }
1065 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001066 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001067 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001068 }
1069
Joe Onorato9c1289c2009-08-17 11:03:03 -04001070 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001071 * Creates a new unique child id, for a given cell span across all layouts.
1072 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001073 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001075 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001077 }
1078
Winson Chungaafa03c2010-06-11 17:34:16 -07001079 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001080 * Removes the specified item from the database
1081 * @param context
1082 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001083 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001084 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001085 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001086 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -07001087
Michael Jurka83df1882011-08-31 20:59:26 -07001088 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001089 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -07001090 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001091
1092 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001093 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001094 switch (item.itemType) {
1095 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1096 sBgFolders.remove(item.id);
1097 for (ItemInfo info: sBgItemsIdMap.values()) {
1098 if (info.container == item.id) {
1099 // We are deleting a folder which still contains items that
1100 // think they are contained by that folder.
1101 String msg = "deleting a folder (" + item + ") which still " +
1102 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -07001103 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001104 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001105 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106 sBgWorkspaceItems.remove(item);
1107 break;
1108 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1109 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1110 sBgWorkspaceItems.remove(item);
1111 break;
1112 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1113 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1114 break;
1115 }
1116 sBgItemsIdMap.remove(item.id);
1117 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001118 }
1119 }
Michael Jurka83df1882011-08-31 20:59:26 -07001120 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001122 }
1123
1124 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001125 * Update the order of the workspace screens in the database. The array list contains
1126 * a list of screen ids in the order that they should appear.
1127 */
Winson Chungc9168342013-06-26 14:54:55 -07001128 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001129 // Log to disk
1130 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1131 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1132
Winson Chung64359a52013-07-08 17:17:08 -07001133 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001134 final ContentResolver cr = context.getContentResolver();
1135 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1136
1137 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001138 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001139 while (iter.hasNext()) {
1140 long id = iter.next();
1141 if (id < 0) {
1142 iter.remove();
1143 }
1144 }
1145
1146 Runnable r = new Runnable() {
1147 @Override
1148 public void run() {
Yura085c8532014-02-11 15:15:29 +00001149 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001151 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001152 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001153 for (int i = 0; i < count; i++) {
1154 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001155 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001156 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1157 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001158 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001159 }
Yura085c8532014-02-11 15:15:29 +00001160
1161 try {
1162 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1163 } catch (Exception ex) {
1164 throw new RuntimeException(ex);
1165 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001166
Winson Chungba9c37f2013-08-30 14:11:37 -07001167 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001168 sBgWorkspaceScreens.clear();
1169 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001170 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 }
1172 };
1173 runOnWorkerThread(r);
1174 }
1175
1176 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001177 * Remove the contents of the specified folder from the database
1178 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001179 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001180 final ContentResolver cr = context.getContentResolver();
1181
Michael Jurkac9d95c52011-08-29 14:03:34 -07001182 Runnable r = new Runnable() {
1183 public void run() {
1184 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001185 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001186 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001187 sBgItemsIdMap.remove(info.id);
1188 sBgFolders.remove(info.id);
1189 sBgDbIconCache.remove(info);
1190 sBgWorkspaceItems.remove(info);
1191 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001192
Michael Jurkac9d95c52011-08-29 14:03:34 -07001193 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1194 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001195 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001196 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 for (ItemInfo childInfo : info.contents) {
1198 sBgItemsIdMap.remove(childInfo.id);
1199 sBgDbIconCache.remove(childInfo);
1200 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001201 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001202 }
1203 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001205 }
1206
1207 /**
1208 * Set this as the current Launcher activity object for the loader.
1209 */
1210 public void initialize(Callbacks callbacks) {
1211 synchronized (mLock) {
1212 mCallbacks = new WeakReference<Callbacks>(callbacks);
1213 }
1214 }
1215
Kenny Guyed131872014-04-30 03:02:21 +01001216 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001217 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001218 int op = PackageUpdatedTask.OP_UPDATE;
1219 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1220 user));
1221 }
1222
1223 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001224 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001225 int op = PackageUpdatedTask.OP_REMOVE;
1226 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1227 user));
1228 }
1229
1230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_ADD;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001239 boolean replacing) {
1240 if (!replacing) {
1241 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1242 user));
1243 if (mAppsCanBeOnRemoveableStorage) {
1244 // Only rebind if we support removable storage. It catches the
1245 // case where
1246 // apps on the external sd card need to be reloaded
1247 startLoaderFromBackground();
1248 }
1249 } else {
1250 // If we are replacing then just update the packages in the list
1251 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1252 packageNames, user));
1253 }
1254 }
1255
1256 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001257 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001258 boolean replacing) {
1259 if (!replacing) {
1260 enqueuePackageUpdated(new PackageUpdatedTask(
1261 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1262 user));
1263 }
1264
1265 }
1266
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001267 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001268 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1269 * ACTION_PACKAGE_CHANGED.
1270 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001271 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001272 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001273 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001274
Joe Onorato36115782010-06-17 13:28:48 -04001275 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001276 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001277 // If we have changed locale we need to clear out the labels in all apps/workspace.
1278 forceReload();
1279 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1280 // Check if configuration change was an mcc/mnc change which would affect app resources
1281 // and we would need to clear out the labels in all apps/workspace. Same handling as
1282 // above for ACTION_LOCALE_CHANGED
1283 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001284 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001285 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001286 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001287 forceReload();
1288 }
1289 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001290 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001291 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1292 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001293 if (mCallbacks != null) {
1294 Callbacks callbacks = mCallbacks.get();
1295 if (callbacks != null) {
1296 callbacks.bindSearchablesChanged();
1297 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001298 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001299 }
1300 }
1301
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001302 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001303 resetLoadedState(true, true);
1304
Reena Lee93f824a2011-09-23 17:20:28 -07001305 // Do this here because if the launcher activity is running it will be restarted.
1306 // If it's not running startLoaderFromBackground will merely tell it that it needs
1307 // to reload.
1308 startLoaderFromBackground();
1309 }
1310
Winson Chungf0c6ae02012-03-21 16:10:31 -07001311 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1312 synchronized (mLock) {
1313 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1314 // mWorkspaceLoaded to true later
1315 stopLoaderLocked();
1316 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1317 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1318 }
1319 }
1320
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001321 /**
1322 * When the launcher is in the background, it's possible for it to miss paired
1323 * configuration changes. So whenever we trigger the loader from the background
1324 * tell the launcher that it needs to re-run the loader when it comes back instead
1325 * of doing it now.
1326 */
1327 public void startLoaderFromBackground() {
1328 boolean runLoader = false;
1329 if (mCallbacks != null) {
1330 Callbacks callbacks = mCallbacks.get();
1331 if (callbacks != null) {
1332 // Only actually run the loader if they're not paused.
1333 if (!callbacks.setLoadOnResume()) {
1334 runLoader = true;
1335 }
1336 }
1337 }
1338 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001339 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001340 }
Joe Onorato36115782010-06-17 13:28:48 -04001341 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001342
Reena Lee93f824a2011-09-23 17:20:28 -07001343 // If there is already a loader task running, tell it to stop.
1344 // returns true if isLaunching() was true on the old task
1345 private boolean stopLoaderLocked() {
1346 boolean isLaunching = false;
1347 LoaderTask oldTask = mLoaderTask;
1348 if (oldTask != null) {
1349 if (oldTask.isLaunching()) {
1350 isLaunching = true;
1351 }
1352 oldTask.stopLocked();
1353 }
1354 return isLaunching;
1355 }
1356
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001357 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001358 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1359 }
1360
1361 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001362 synchronized (mLock) {
1363 if (DEBUG_LOADERS) {
1364 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1365 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001366
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001367 // Clear any deferred bind-runnables from the synchronized load process
1368 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001369 synchronized (mDeferredBindRunnables) {
1370 mDeferredBindRunnables.clear();
1371 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001372
Joe Onorato36115782010-06-17 13:28:48 -04001373 // Don't bother to start the thread if we know it's not going to do anything
1374 if (mCallbacks != null && mCallbacks.get() != null) {
1375 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001376 // also, don't downgrade isLaunching if we're already running
1377 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001378 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001379 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1380 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1382 } else {
1383 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1384 sWorker.post(mLoaderTask);
1385 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001386 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001387 }
1388 }
1389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 void bindRemainingSynchronousPages() {
1391 // Post the remaining side pages to be loaded
1392 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001393 Runnable[] deferredBindRunnables = null;
1394 synchronized (mDeferredBindRunnables) {
1395 deferredBindRunnables = mDeferredBindRunnables.toArray(
1396 new Runnable[mDeferredBindRunnables.size()]);
1397 mDeferredBindRunnables.clear();
1398 }
1399 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001400 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 }
1403 }
1404
Joe Onorato36115782010-06-17 13:28:48 -04001405 public void stopLoader() {
1406 synchronized (mLock) {
1407 if (mLoaderTask != null) {
1408 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001409 }
1410 }
Joe Onorato36115782010-06-17 13:28:48 -04001411 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001412
Winson Chung76828c82013-08-19 15:43:29 -07001413 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1414 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1415 final ContentResolver contentResolver = context.getContentResolver();
1416 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1417 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1418 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1419
1420 try {
1421 final int idIndex = sc.getColumnIndexOrThrow(
1422 LauncherSettings.WorkspaceScreens._ID);
1423 final int rankIndex = sc.getColumnIndexOrThrow(
1424 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1425 while (sc.moveToNext()) {
1426 try {
1427 long screenId = sc.getLong(idIndex);
1428 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001429 orderedScreens.put(rank, screenId);
1430 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001431 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001432 }
1433 }
1434 } finally {
1435 sc.close();
1436 }
Winson Chunga90303b2013-11-15 13:05:06 -08001437
1438 // Log to disk
1439 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1440 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1441 for (Integer i : orderedScreens.keySet()) {
1442 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1443 }
1444 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1445 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001446 return orderedScreens;
1447 }
1448
Michael Jurkac57b7a82011-08-09 22:02:20 -07001449 public boolean isAllAppsLoaded() {
1450 return mAllAppsLoaded;
1451 }
1452
Winson Chung36a62fe2012-05-06 18:04:42 -07001453 boolean isLoadingWorkspace() {
1454 synchronized (mLock) {
1455 if (mLoaderTask != null) {
1456 return mLoaderTask.isLoadingWorkspace();
1457 }
1458 }
1459 return false;
1460 }
1461
Joe Onorato36115782010-06-17 13:28:48 -04001462 /**
1463 * Runnable for the thread that loads the contents of the launcher:
1464 * - workspace icons
1465 * - widgets
1466 * - all apps icons
1467 */
1468 private class LoaderTask implements Runnable {
1469 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001470 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001471 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001472 private boolean mStopped;
1473 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001474 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001475
Winson Chungc3eecff2011-07-11 17:44:15 -07001476 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001477
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001479 mContext = context;
1480 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001481 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001482 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 boolean isLaunching() {
1486 return mIsLaunching;
1487 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 boolean isLoadingWorkspace() {
1490 return mIsLoadingAndBindingWorkspace;
1491 }
1492
Winson Chungc763c4e2013-07-19 13:49:06 -07001493 /** Returns whether this is an upgrade path */
1494 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001495 mIsLoadingAndBindingWorkspace = true;
1496
Joe Onorato36115782010-06-17 13:28:48 -04001497 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001498 if (DEBUG_LOADERS) {
1499 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001500 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001501
Winson Chungc763c4e2013-07-19 13:49:06 -07001502 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001503 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001504 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001505 synchronized (LoaderTask.this) {
1506 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001507 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001508 }
1509 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001510 }
1511 }
1512
Joe Onorato36115782010-06-17 13:28:48 -04001513 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001514 bindWorkspace(-1, isUpgradePath);
1515 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001516 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001517
Joe Onorato36115782010-06-17 13:28:48 -04001518 private void waitForIdle() {
1519 // Wait until the either we're stopped or the other threads are done.
1520 // This way we don't start loading all apps until the workspace has settled
1521 // down.
1522 synchronized (LoaderTask.this) {
1523 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001524
Joe Onorato36115782010-06-17 13:28:48 -04001525 mHandler.postIdle(new Runnable() {
1526 public void run() {
1527 synchronized (LoaderTask.this) {
1528 mLoadAndBindStepFinished = true;
1529 if (DEBUG_LOADERS) {
1530 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Joe Onorato36115782010-06-17 13:28:48 -04001532 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001533 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001534 }
Joe Onorato36115782010-06-17 13:28:48 -04001535 });
1536
Michael Jurkac7700af2013-05-14 20:17:58 +02001537 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001538 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001539 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1540 // wait no longer than 1sec at a time
1541 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001542 } catch (InterruptedException ex) {
1543 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001544 }
1545 }
Joe Onorato36115782010-06-17 13:28:48 -04001546 if (DEBUG_LOADERS) {
1547 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001548 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001549 + "ms for previous step to finish binding");
1550 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001551 }
Joe Onorato36115782010-06-17 13:28:48 -04001552 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001553
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001555 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001556 // Ensure that we have a valid page index to load synchronously
1557 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1558 "valid page index");
1559 }
1560 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1561 // Ensure that we don't try and bind a specified page when the pages have not been
1562 // loaded already (we should load everything asynchronously in that case)
1563 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1564 }
1565 synchronized (mLock) {
1566 if (mIsLoaderTaskRunning) {
1567 // Ensure that we are never running the background loading at this point since
1568 // we also touch the background collections
1569 throw new RuntimeException("Error! Background loading is already running");
1570 }
1571 }
1572
1573 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1574 // data structures, we can't allow any other thread to touch that data, but because
1575 // this call is synchronous, we can get away with not locking).
1576
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001577 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001578 // operations from the previous activity. We need to ensure that all queued operations
1579 // are executed before any synchronous binding work is done.
1580 mHandler.flush();
1581
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 // Divide the set of loaded items into those that we are binding synchronously, and
1583 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001584 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1586 // arise from that.
1587 onlyBindAllApps();
1588 }
1589
Joe Onorato36115782010-06-17 13:28:48 -04001590 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001591 boolean isUpgrade = false;
1592
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001593 synchronized (mLock) {
1594 mIsLoaderTaskRunning = true;
1595 }
Joe Onorato36115782010-06-17 13:28:48 -04001596 // Optimize for end-user experience: if the Launcher is up and // running with the
1597 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1598 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001599 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001600 // Elevate priority when Home launches for the first time to avoid
1601 // starving at boot time. Staring at a blank home is not cool.
1602 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001603 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1604 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001605 android.os.Process.setThreadPriority(mIsLaunching
1606 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1607 }
Winson Chung64359a52013-07-08 17:17:08 -07001608 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001609 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001610
Joe Onorato36115782010-06-17 13:28:48 -04001611 if (mStopped) {
1612 break keep_running;
1613 }
1614
1615 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1616 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001617 synchronized (mLock) {
1618 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001619 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001620 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1621 }
1622 }
Joe Onorato36115782010-06-17 13:28:48 -04001623 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001624
1625 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001626 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1627 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001628
1629 // Restore the default thread priority after we are done loading items
1630 synchronized (mLock) {
1631 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632 }
Joe Onorato36115782010-06-17 13:28:48 -04001633 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001634
Winson Chungaac01e12011-08-17 10:37:13 -07001635 // Update the saved icons if necessary
1636 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001637 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001638 for (Object key : sBgDbIconCache.keySet()) {
1639 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1640 }
1641 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001642 }
Winson Chungaac01e12011-08-17 10:37:13 -07001643
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001644 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001645 // Ensure that all the applications that are in the system are
1646 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001647 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001648 verifyApplications();
1649 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001650 }
1651
Joe Onorato36115782010-06-17 13:28:48 -04001652 // Clear out this reference, otherwise we end up holding it until all of the
1653 // callback runnables are done.
1654 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001655
Joe Onorato36115782010-06-17 13:28:48 -04001656 synchronized (mLock) {
1657 // If we are still the last one to be scheduled, remove ourselves.
1658 if (mLoaderTask == this) {
1659 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001660 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001661 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663 }
1664
1665 public void stopLocked() {
1666 synchronized (LoaderTask.this) {
1667 mStopped = true;
1668 this.notify();
1669 }
1670 }
1671
1672 /**
1673 * Gets the callbacks object. If we've been stopped, or if the launcher object
1674 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1675 * object that was around when the deferred message was scheduled, and if there's
1676 * a new Callbacks object around then also return null. This will save us from
1677 * calling onto it with data that will be ignored.
1678 */
1679 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1680 synchronized (mLock) {
1681 if (mStopped) {
1682 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001683 }
Joe Onorato36115782010-06-17 13:28:48 -04001684
1685 if (mCallbacks == null) {
1686 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001687 }
Joe Onorato36115782010-06-17 13:28:48 -04001688
1689 final Callbacks callbacks = mCallbacks.get();
1690 if (callbacks != oldCallbacks) {
1691 return null;
1692 }
1693 if (callbacks == null) {
1694 Log.w(TAG, "no mCallbacks");
1695 return null;
1696 }
1697
1698 return callbacks;
1699 }
1700 }
1701
Winson Chungc763c4e2013-07-19 13:49:06 -07001702 private void verifyApplications() {
1703 final Context context = mApp.getContext();
1704
1705 // Cross reference all the applications in our apps list with items in the workspace
1706 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001707 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001708 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001709 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001710 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001711 if (tmpInfos.isEmpty()) {
1712 // We are missing an application icon, so add this to the workspace
1713 added.add(app);
1714 // This is a rare event, so lets log it
1715 Log.e(TAG, "Missing Application on load: " + app);
1716 }
1717 }
1718 }
1719 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001720 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001721 }
1722 }
1723
Joe Onorato36115782010-06-17 13:28:48 -04001724 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001725 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001726 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001727 LauncherAppState app = LauncherAppState.getInstance();
1728 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001729 final int countX = (int) grid.numColumns;
1730 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001731
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001733 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001734 // Return early if we detect that an item is under the hotseat button
1735 if (mCallbacks == null ||
1736 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001737 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001738 Log.e(TAG, "Error loading shortcut into hotseat " + item
1739 + " into position (" + item.screenId + ":" + item.cellX + ","
1740 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001741 return false;
1742 }
1743
Dan Sandler295ae182013-12-10 16:05:47 -05001744 final ItemInfo[][] hotseatItems =
1745 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1746
Adam Cohenae4409d2013-11-26 10:34:59 -08001747 if (item.screenId >= grid.numHotseatIcons) {
1748 Log.e(TAG, "Error loading shortcut " + item
1749 + " into hotseat position " + item.screenId
1750 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1751 + ")");
1752 return false;
1753 }
1754
Dan Sandler295ae182013-12-10 16:05:47 -05001755 if (hotseatItems != null) {
1756 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001757 Log.e(TAG, "Error loading shortcut into hotseat " + item
1758 + " into position (" + item.screenId + ":" + item.cellX + ","
1759 + item.cellY + ") occupied by "
1760 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1761 [(int) item.screenId][0]);
1762 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001763 } else {
1764 hotseatItems[(int) item.screenId][0] = item;
1765 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001767 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001768 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001769 items[(int) item.screenId][0] = item;
1770 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001771 return true;
1772 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001773 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1774 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001775 return true;
1776 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001777
Adam Cohendcd297f2013-06-18 13:13:40 -07001778 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001779 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001780 occupied.put(item.screenId, items);
1781 }
1782
Dan Sandler295ae182013-12-10 16:05:47 -05001783 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001784 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1785 item.cellX < 0 || item.cellY < 0 ||
1786 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1787 Log.e(TAG, "Error loading shortcut " + item
1788 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1789 + item.cellX + "," + item.cellY
1790 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1791 return false;
1792 }
1793
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001794 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001795 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1796 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001797 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001798 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001800 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001801 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001802 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001803 return false;
1804 }
1805 }
1806 }
1807 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1808 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001810 }
1811 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001812
Joe Onorato36115782010-06-17 13:28:48 -04001813 return true;
1814 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001815
Winson Chungba9c37f2013-08-30 14:11:37 -07001816 /** Clears all the sBg data structures */
1817 private void clearSBgDataStructures() {
1818 synchronized (sBgLock) {
1819 sBgWorkspaceItems.clear();
1820 sBgAppWidgets.clear();
1821 sBgFolders.clear();
1822 sBgItemsIdMap.clear();
1823 sBgDbIconCache.clear();
1824 sBgWorkspaceScreens.clear();
1825 }
1826 }
1827
Dan Sandlerd5024042014-01-09 15:01:33 -05001828 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001829 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001830 // Log to disk
1831 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1832
Joe Onorato36115782010-06-17 13:28:48 -04001833 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001834
Joe Onorato36115782010-06-17 13:28:48 -04001835 final Context context = mContext;
1836 final ContentResolver contentResolver = context.getContentResolver();
1837 final PackageManager manager = context.getPackageManager();
1838 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1839 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001840 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1841 final boolean isSdCardReady = context.registerReceiver(null,
1842 new IntentFilter(StartupReceiver.SYESTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001843
Winson Chung892c74d2013-08-22 16:15:50 -07001844 LauncherAppState app = LauncherAppState.getInstance();
1845 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1846 int countX = (int) grid.numColumns;
1847 int countY = (int) grid.numRows;
1848
Dan Sandlerd5024042014-01-09 15:01:33 -05001849 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1850 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1851 LauncherAppState.getLauncherProvider().deleteDatabase();
1852 }
1853
1854 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1855 // append the user's Launcher2 shortcuts
1856 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1857 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1858 } else {
1859 // Make sure the default workspace is loaded
1860 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1861 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1862 }
Adam Cohene25af792013-06-06 23:08:25 -07001863
Adam Cohen71483f42014-05-15 14:04:01 -07001864 // This code path is for our old migration code and should no longer be exercised
1865 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001866
Winson Chung9f9f00b2013-11-15 13:27:00 -08001867 // Log to disk
1868 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001869
Winson Chung2abf94d2012-07-18 18:16:38 -07001870 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001871 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001872
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001873 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001874 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001875 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001876 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001877 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001878
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001879 // +1 for the hotseat (it can be larger than the workspace)
1880 // Load workspace in reverse order to ensure that latest items are loaded first (and
1881 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001882 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 try {
1885 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1886 final int intentIndex = c.getColumnIndexOrThrow
1887 (LauncherSettings.Favorites.INTENT);
1888 final int titleIndex = c.getColumnIndexOrThrow
1889 (LauncherSettings.Favorites.TITLE);
1890 final int iconTypeIndex = c.getColumnIndexOrThrow(
1891 LauncherSettings.Favorites.ICON_TYPE);
1892 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1893 final int iconPackageIndex = c.getColumnIndexOrThrow(
1894 LauncherSettings.Favorites.ICON_PACKAGE);
1895 final int iconResourceIndex = c.getColumnIndexOrThrow(
1896 LauncherSettings.Favorites.ICON_RESOURCE);
1897 final int containerIndex = c.getColumnIndexOrThrow(
1898 LauncherSettings.Favorites.CONTAINER);
1899 final int itemTypeIndex = c.getColumnIndexOrThrow(
1900 LauncherSettings.Favorites.ITEM_TYPE);
1901 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1902 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001903 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 final int screenIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.SCREEN);
1907 final int cellXIndex = c.getColumnIndexOrThrow
1908 (LauncherSettings.Favorites.CELLX);
1909 final int cellYIndex = c.getColumnIndexOrThrow
1910 (LauncherSettings.Favorites.CELLY);
1911 final int spanXIndex = c.getColumnIndexOrThrow
1912 (LauncherSettings.Favorites.SPANX);
1913 final int spanYIndex = c.getColumnIndexOrThrow(
1914 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001915 final int restoredIndex = c.getColumnIndexOrThrow(
1916 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001917 final int profileIdIndex = c.getColumnIndexOrThrow(
1918 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001919 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1920 //final int displayModeIndex = c.getColumnIndexOrThrow(
1921 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001922
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001923 ShortcutInfo info;
1924 String intentDescription;
1925 LauncherAppWidgetInfo appWidgetInfo;
1926 int container;
1927 long id;
1928 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001929 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001930
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001931 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001932 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001933 try {
1934 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001935 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001936 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001937
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001938 switch (itemType) {
1939 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1940 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001941 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001942 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001943 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001944 user = mUserManager.getUserForSerialNumber(serialNumber);
1945 if (user == null) {
1946 // User has been deleted remove the item.
1947 itemsToRemove.add(id);
1948 continue;
1949 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 try {
1951 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001952 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001953 if (cn != null && cn.getPackageName() != null) {
1954 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1955 cn.getPackageName(), user);
1956 boolean validComponent = validPkg &&
1957 launcherApps.isActivityEnabledForProfile(cn, user);
1958
1959 if (validComponent) {
1960 if (restored) {
1961 // no special handling necessary for this item
1962 restoredRows.add(id);
1963 restored = false;
1964 }
1965 } else if (validPkg) {
1966 // The app is installed but the component is no
1967 // longer available.
1968 Launcher.addDumpLog(TAG,
1969 "Invalid component removed: " + cn, true);
1970 itemsToRemove.add(id);
1971 continue;
1972 } else if (restored) {
1973 // Package is not yet available but might be
1974 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001975 Launcher.addDumpLog(TAG,
1976 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001977 } else if (isSdCardReady) {
1978 // Do not wait for external media load anymore.
1979 // Log the invalid package, and remove it
1980 Launcher.addDumpLog(TAG,
1981 "Invalid package removed: " + cn, true);
1982 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05001983 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001984 } else {
1985 // SdCard is not ready yet. Package might get available,
1986 // once it is ready.
1987 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1988 + " (check again later)", true);
1989 HashSet<String> pkgs = sPendingPackages.get(user);
1990 if (pkgs == null) {
1991 pkgs = new HashSet<>();
1992 sPendingPackages.put(user, pkgs);
1993 }
1994 pkgs.add(cn.getPackageName());
1995 allowMissingTarget = true;
1996 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07001997 }
Winson Chungee055712013-07-30 14:46:24 -07001998 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001999 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002000 Launcher.addDumpLog(TAG,
2001 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002002 continue;
2003 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002004
Chris Wrenf4d08112014-01-16 18:13:56 -05002005 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002006 if (user.equals(UserHandleCompat.myUserHandle())) {
2007 Launcher.addDumpLog(TAG,
2008 "constructing info for partially restored package",
2009 true);
2010 info = getRestoredItemInfo(c, titleIndex, intent);
2011 intent = getRestoredItemIntent(c, context, intent);
2012 } else {
2013 // Don't restore items for other profiles.
2014 itemsToRemove.add(id);
2015 continue;
2016 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002017 } else if (itemType ==
2018 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002019 info = getShortcutInfo(manager, intent, user, context, c,
2020 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002021 } else {
2022 info = getShortcutInfo(c, context, iconTypeIndex,
2023 iconPackageIndex, iconResourceIndex, iconIndex,
2024 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002025
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002026 // App shortcuts that used to be automatically added to Launcher
2027 // didn't always have the correct intent flags set, so do that
2028 // here
2029 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002030 intent.getCategories() != null &&
2031 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002032 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002033 intent.addFlags(
2034 Intent.FLAG_ACTIVITY_NEW_TASK |
2035 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2036 }
Michael Jurka96879562012-03-22 05:54:33 -07002037 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002038
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002039 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002040 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002041 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002042 container = c.getInt(containerIndex);
2043 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002045 info.cellX = c.getInt(cellXIndex);
2046 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002047 info.spanX = 1;
2048 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002049 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002050 info.isDisabled = isSafeMode
2051 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002052
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002053 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002054 deleteOnInvalidPlacement.set(false);
2055 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2056 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002057 itemsToRemove.add(id);
2058 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002059 break;
2060 }
2061
2062 switch (container) {
2063 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2064 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2065 sBgWorkspaceItems.add(info);
2066 break;
2067 default:
2068 // Item is in a user folder
2069 FolderInfo folderInfo =
2070 findOrMakeFolder(sBgFolders, container);
2071 folderInfo.add(info);
2072 break;
2073 }
2074 sBgItemsIdMap.put(info.id, info);
2075
2076 // now that we've loaded everthing re-save it with the
2077 // icon in case it disappears somehow.
2078 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002079 } else {
2080 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002081 }
2082 break;
2083
2084 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2085 id = c.getLong(idIndex);
2086 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2087
2088 folderInfo.title = c.getString(titleIndex);
2089 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002090 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002092 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093 folderInfo.cellX = c.getInt(cellXIndex);
2094 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002095 folderInfo.spanX = 1;
2096 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002097
Daniel Sandler8802e962010-05-26 16:28:16 -04002098 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002099 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002100 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002101 deleteOnInvalidPlacement)) {
2102 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002103 itemsToRemove.add(id);
2104 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002105 break;
2106 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002107
Joe Onorato9c1289c2009-08-17 11:03:03 -04002108 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2110 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2111 sBgWorkspaceItems.add(folderInfo);
2112 break;
Joe Onorato36115782010-06-17 13:28:48 -04002113 }
Joe Onorato17a89222011-02-08 17:26:11 -08002114
Chris Wrenf4d08112014-01-16 18:13:56 -05002115 if (restored) {
2116 // no special handling required for restored folders
2117 restoredRows.add(id);
2118 }
2119
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2121 sBgFolders.put(folderInfo.id, folderInfo);
2122 break;
2123
2124 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2125 // Read all Launcher-specific widget details
2126 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002127 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002128 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002129
Sunny Goyal651077b2014-06-30 14:15:31 -07002130 final int restoreStatus = c.getInt(restoredIndex);
2131 final boolean restorePending = Utilities.isLmp()
2132 && (restoreStatus ==
2133 LauncherAppWidgetInfo.RESTORE_REMAP_PENDING);
2134 final boolean providerPending = Utilities.isLmp()
2135 && (restoreStatus ==
2136 LauncherAppWidgetInfo.RESTORE_PROVIDER_PENDING);
Joe Onorato36115782010-06-17 13:28:48 -04002137
Sunny Goyal651077b2014-06-30 14:15:31 -07002138 // Do not try to get the provider if restore is pending, as the
2139 // widget id is invalid, and it might point to some other provider.
2140 final AppWidgetProviderInfo provider = restorePending ? null
2141 : widgets.getAppWidgetInfo(appWidgetId);
2142 boolean providerValid = isValidProvider(provider);
2143
2144 // Skip provider check,
2145 // 1. when the widget id re-map is pending
2146 // 2. provider is pending install for a restored widget
2147 if (!isSafeMode && !providerPending && !restorePending
2148 && !providerValid) {
2149 String log = "Deleting widget that isn't installed anymore: "
2150 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002152 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002153 itemsToRemove.add(id);
2154 } else {
Sunny Goyal651077b2014-06-30 14:15:31 -07002155 if (providerValid) {
2156 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2157 provider.provider);
2158 int[] minSpan =
2159 Launcher.getMinSpanForWidget(context, provider);
2160 appWidgetInfo.minSpanX = minSpan[0];
2161 appWidgetInfo.minSpanY = minSpan[1];
2162 } else {
2163 Log.v(TAG, "Widget restore pending id=" + id
2164 + " appWidgetId=" + appWidgetId
2165 + " status =" + restoreStatus);
2166 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2167 ComponentName.unflattenFromString(savedProvider));
2168 appWidgetInfo.restoreStatus = restoreStatus;
2169 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002171 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002172 appWidgetInfo.cellX = c.getInt(cellXIndex);
2173 appWidgetInfo.cellY = c.getInt(cellYIndex);
2174 appWidgetInfo.spanX = c.getInt(spanXIndex);
2175 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002176
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002177 container = c.getInt(containerIndex);
2178 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2179 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2180 Log.e(TAG, "Widget found where container != " +
2181 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2182 continue;
2183 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184
Adam Cohene25af792013-06-06 23:08:25 -07002185 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002186 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002187 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002188 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002189 deleteOnInvalidPlacement)) {
2190 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002191 itemsToRemove.add(id);
2192 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002193 break;
2194 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002195
2196 if (providerValid) {
2197 String providerName = provider.provider.flattenToString();
2198
2199 if (!providerName.equals(savedProvider) || providerPending) {
2200 ContentValues values = new ContentValues();
2201 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2202 providerName);
2203 values.put(LauncherSettings.Favorites.RESTORED,
2204 LauncherAppWidgetInfo.RESTORE_COMPLETED);
2205 String where = BaseColumns._ID + "= ?";
2206 String[] args = {Long.toString(id)};
2207 contentResolver.update(contentUri, values, where, args);
2208 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002209 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002210 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2211 sBgAppWidgets.add(appWidgetInfo);
2212 }
Joe Onorato36115782010-06-17 13:28:48 -04002213 break;
2214 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002215 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002216 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002217 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218 }
2219 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002220 if (c != null) {
2221 c.close();
2222 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223 }
2224
Winson Chungba9c37f2013-08-30 14:11:37 -07002225 // Break early if we've stopped loading
2226 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002227 clearSBgDataStructures();
2228 return false;
2229 }
2230
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002231 if (itemsToRemove.size() > 0) {
2232 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002233 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002234 // Remove dead items
2235 for (long id : itemsToRemove) {
2236 if (DEBUG_LOADERS) {
2237 Log.d(TAG, "Removed id = " + id);
2238 }
2239 // Don't notify content observers
2240 try {
2241 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2242 null, null);
2243 } catch (RemoteException e) {
2244 Log.w(TAG, "Could not remove id = " + id);
2245 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002246 }
2247 }
2248
Chris Wrenf4d08112014-01-16 18:13:56 -05002249 if (restoredRows.size() > 0) {
2250 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2251 LauncherSettings.Favorites.CONTENT_URI);
2252 // Update restored items that no longer require special handling
2253 try {
2254 StringBuilder selectionBuilder = new StringBuilder();
2255 selectionBuilder.append(LauncherSettings.Favorites._ID);
2256 selectionBuilder.append(" IN (");
2257 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2258 selectionBuilder.append(")");
2259 ContentValues values = new ContentValues();
2260 values.put(LauncherSettings.Favorites.RESTORED, 0);
2261 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2262 values, selectionBuilder.toString(), null);
2263 } catch (RemoteException e) {
2264 Log.w(TAG, "Could not update restored rows");
2265 }
2266 }
2267
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002268 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2269 context.registerReceiver(new AppsAvailabilityCheck(),
2270 new IntentFilter(StartupReceiver.SYESTEM_READY),
2271 null, sWorker);
2272 }
2273
Winson Chungc763c4e2013-07-19 13:49:06 -07002274 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002275 long maxScreenId = 0;
2276 // If we're importing we use the old screen order.
2277 for (ItemInfo item: sBgItemsIdMap.values()) {
2278 long screenId = item.screenId;
2279 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2280 !sBgWorkspaceScreens.contains(screenId)) {
2281 sBgWorkspaceScreens.add(screenId);
2282 if (screenId > maxScreenId) {
2283 maxScreenId = screenId;
2284 }
2285 }
2286 }
2287 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002288 // Log to disk
2289 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2290 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2291 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002292
Michael Jurka414300a2013-08-27 15:42:35 +02002293 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002294 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002295
2296 // Update the max item id after we load an old db
2297 long maxItemId = 0;
2298 // If we're importing we use the old screen order.
2299 for (ItemInfo item: sBgItemsIdMap.values()) {
2300 maxItemId = Math.max(maxItemId, item.id);
2301 }
Michael Jurka414300a2013-08-27 15:42:35 +02002302 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002303 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002304 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2305 for (Integer i : orderedScreens.keySet()) {
2306 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002307 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002308 // Log to disk
2309 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2310 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002311
2312 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002313 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002314 for (ItemInfo item: sBgItemsIdMap.values()) {
2315 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002316 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2317 unusedScreens.contains(screenId)) {
2318 unusedScreens.remove(screenId);
2319 }
2320 }
2321
2322 // If there are any empty screens remove them, and update.
2323 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002324 // Log to disk
2325 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2326 TextUtils.join(", ", unusedScreens), true);
2327
Winson Chung933bae62013-08-29 11:42:30 -07002328 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002329 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2330 }
2331 }
2332
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002333 if (DEBUG_LOADERS) {
2334 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2335 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002336 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002337 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002338 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002339
Daniel Sandler566da102013-06-25 23:43:45 -04002340 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002341 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002342 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002343 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002344 line += " | ";
2345 }
Winson Chung892c74d2013-08-22 16:15:50 -07002346 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002347 ItemInfo[][] screen = occupied.get(screenId);
2348 if (x < screen.length && y < screen[x].length) {
2349 line += (screen[x][y] != null) ? "#" : ".";
2350 } else {
2351 line += "!";
2352 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002353 }
Joe Onorato36115782010-06-17 13:28:48 -04002354 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002355 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002356 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002357 }
Joe Onorato36115782010-06-17 13:28:48 -04002358 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002359 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002360 }
2361
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 /** Filters the set of items who are directly or indirectly (via another container) on the
2363 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002364 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002365 ArrayList<ItemInfo> allWorkspaceItems,
2366 ArrayList<ItemInfo> currentScreenItems,
2367 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002368 // Purge any null ItemInfos
2369 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2370 while (iter.hasNext()) {
2371 ItemInfo i = iter.next();
2372 if (i == null) {
2373 iter.remove();
2374 }
2375 }
2376
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002377 // Order the set of items by their containers first, this allows use to walk through the
2378 // list sequentially, build up a list of containers that are in the specified screen,
2379 // as well as all items in those containers.
2380 Set<Long> itemsOnScreen = new HashSet<Long>();
2381 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2382 @Override
2383 public int compare(ItemInfo lhs, ItemInfo rhs) {
2384 return (int) (lhs.container - rhs.container);
2385 }
2386 });
2387 for (ItemInfo info : allWorkspaceItems) {
2388 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002389 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002390 currentScreenItems.add(info);
2391 itemsOnScreen.add(info.id);
2392 } else {
2393 otherScreenItems.add(info);
2394 }
2395 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2396 currentScreenItems.add(info);
2397 itemsOnScreen.add(info.id);
2398 } else {
2399 if (itemsOnScreen.contains(info.container)) {
2400 currentScreenItems.add(info);
2401 itemsOnScreen.add(info.id);
2402 } else {
2403 otherScreenItems.add(info);
2404 }
2405 }
2406 }
2407 }
2408
2409 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002410 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002411 ArrayList<LauncherAppWidgetInfo> appWidgets,
2412 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2413 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002414
2415 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002416 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002417 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002418 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002419 currentScreenWidgets.add(widget);
2420 } else {
2421 otherScreenWidgets.add(widget);
2422 }
2423 }
2424 }
2425
2426 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002427 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002428 HashMap<Long, ItemInfo> itemsIdMap,
2429 HashMap<Long, FolderInfo> folders,
2430 HashMap<Long, FolderInfo> currentScreenFolders,
2431 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432
2433 for (long id : folders.keySet()) {
2434 ItemInfo info = itemsIdMap.get(id);
2435 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002436 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002437 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002438 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002439 currentScreenFolders.put(id, folder);
2440 } else {
2441 otherScreenFolders.put(id, folder);
2442 }
2443 }
2444 }
2445
2446 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2447 * right) */
2448 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002449 final LauncherAppState app = LauncherAppState.getInstance();
2450 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 // XXX: review this
2452 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002453 @Override
2454 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002455 int cellCountX = (int) grid.numColumns;
2456 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002457 int screenOffset = cellCountX * cellCountY;
2458 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002459 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002460 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002461 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002462 rhs.cellY * cellCountX + rhs.cellX);
2463 return (int) (lr - rr);
2464 }
2465 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002467
Adam Cohendcd297f2013-06-18 13:13:40 -07002468 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2469 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002470 final Runnable r = new Runnable() {
2471 @Override
2472 public void run() {
2473 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2474 if (callbacks != null) {
2475 callbacks.bindScreens(orderedScreens);
2476 }
2477 }
2478 };
2479 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2480 }
2481
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002482 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2483 final ArrayList<ItemInfo> workspaceItems,
2484 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2485 final HashMap<Long, FolderInfo> folders,
2486 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002487
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002488 final boolean postOnMainThread = (deferredBindRunnables != null);
2489
2490 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002491 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002493 final int start = i;
2494 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002495 final Runnable r = new Runnable() {
2496 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002497 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002498 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002499 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002500 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2501 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002502 }
2503 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002504 };
2505 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002506 synchronized (deferredBindRunnables) {
2507 deferredBindRunnables.add(r);
2508 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002509 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002510 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511 }
Joe Onorato36115782010-06-17 13:28:48 -04002512 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002513
2514 // Bind the folders
2515 if (!folders.isEmpty()) {
2516 final Runnable r = new Runnable() {
2517 public void run() {
2518 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2519 if (callbacks != null) {
2520 callbacks.bindFolders(folders);
2521 }
2522 }
2523 };
2524 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002525 synchronized (deferredBindRunnables) {
2526 deferredBindRunnables.add(r);
2527 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002528 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002529 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 }
2531 }
2532
2533 // Bind the widgets, one at a time
2534 N = appWidgets.size();
2535 for (int i = 0; i < N; i++) {
2536 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2537 final Runnable r = new Runnable() {
2538 public void run() {
2539 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2540 if (callbacks != null) {
2541 callbacks.bindAppWidget(widget);
2542 }
2543 }
2544 };
2545 if (postOnMainThread) {
2546 deferredBindRunnables.add(r);
2547 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002548 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 }
2550 }
2551 }
2552
2553 /**
2554 * Binds all loaded data to actual views on the main thread.
2555 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002556 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002557 final long t = SystemClock.uptimeMillis();
2558 Runnable r;
2559
2560 // Don't use these two variables in any of the callback runnables.
2561 // Otherwise we hold a reference to them.
2562 final Callbacks oldCallbacks = mCallbacks.get();
2563 if (oldCallbacks == null) {
2564 // This launcher has exited and nobody bothered to tell us. Just bail.
2565 Log.w(TAG, "LoaderTask running with no launcher");
2566 return;
2567 }
2568
Winson Chung9b9fb962013-11-15 15:39:34 -08002569 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2571 ArrayList<LauncherAppWidgetInfo> appWidgets =
2572 new ArrayList<LauncherAppWidgetInfo>();
2573 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2574 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002575 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002576 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002577 workspaceItems.addAll(sBgWorkspaceItems);
2578 appWidgets.addAll(sBgAppWidgets);
2579 folders.putAll(sBgFolders);
2580 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002581 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002582 }
2583
Derek Prothro7aff3992013-12-10 14:00:37 -05002584 final boolean isLoadingSynchronously =
2585 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002586 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002587 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002588 if (currScreen >= orderedScreenIds.size()) {
2589 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002590 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002591 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002592 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002593 final long currentScreenId = currentScreen < 0
2594 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002595
2596 // Load all the items that are on the current page first (and in the process, unbind
2597 // all the existing workspace items before we call startBinding() below.
2598 unbindWorkspaceItemsOnMainThread();
2599
2600 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2602 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2603 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2604 new ArrayList<LauncherAppWidgetInfo>();
2605 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2606 new ArrayList<LauncherAppWidgetInfo>();
2607 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2608 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2609
Winson Chung9b9fb962013-11-15 15:39:34 -08002610 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002612 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002613 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002614 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615 otherFolders);
2616 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2617 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2618
2619 // Tell the workspace that we're about to start binding items
2620 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002621 public void run() {
2622 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2623 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002624 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002625 }
2626 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 };
Winson Chung81b52252012-08-27 15:34:29 -07002628 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002629
Adam Cohendcd297f2013-06-18 13:13:40 -07002630 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2631
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002632 // Load items on the current page
2633 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2634 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002635 if (isLoadingSynchronously) {
2636 r = new Runnable() {
2637 public void run() {
2638 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002639 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002640 callbacks.onPageBoundSynchronously(currentScreen);
2641 }
2642 }
2643 };
Winson Chung81b52252012-08-27 15:34:29 -07002644 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002645 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002646
Winson Chung4a2afa32012-07-19 14:53:05 -07002647 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2648 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002649 synchronized (mDeferredBindRunnables) {
2650 mDeferredBindRunnables.clear();
2651 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002653 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002654
2655 // Tell the workspace that we're done binding items
2656 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002657 public void run() {
2658 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2659 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002660 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002661 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002662
Winson Chung98e030b2012-05-07 16:01:11 -07002663 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002664 if (DEBUG_LOADERS) {
2665 Log.d(TAG, "bound workspace in "
2666 + (SystemClock.uptimeMillis()-t) + "ms");
2667 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002668
2669 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002670 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002672 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002673 synchronized (mDeferredBindRunnables) {
2674 mDeferredBindRunnables.add(r);
2675 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002676 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002677 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002678 }
Joe Onorato36115782010-06-17 13:28:48 -04002679 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002680
Joe Onorato36115782010-06-17 13:28:48 -04002681 private void loadAndBindAllApps() {
2682 if (DEBUG_LOADERS) {
2683 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2684 }
2685 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002686 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002687 synchronized (LoaderTask.this) {
2688 if (mStopped) {
2689 return;
2690 }
2691 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002692 }
Joe Onorato36115782010-06-17 13:28:48 -04002693 } else {
2694 onlyBindAllApps();
2695 }
2696 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002697
Joe Onorato36115782010-06-17 13:28:48 -04002698 private void onlyBindAllApps() {
2699 final Callbacks oldCallbacks = mCallbacks.get();
2700 if (oldCallbacks == null) {
2701 // This launcher has exited and nobody bothered to tell us. Just bail.
2702 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2703 return;
2704 }
2705
2706 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002707 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002708 final ArrayList<AppInfo> list
2709 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002710 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002711 public void run() {
2712 final long t = SystemClock.uptimeMillis();
2713 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2714 if (callbacks != null) {
2715 callbacks.bindAllApplications(list);
2716 }
2717 if (DEBUG_LOADERS) {
2718 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2719 + (SystemClock.uptimeMillis()-t) + "ms");
2720 }
2721 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002722 };
2723 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002724 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002725 r.run();
2726 } else {
2727 mHandler.post(r);
2728 }
Joe Onorato36115782010-06-17 13:28:48 -04002729 }
2730
Winson Chung64359a52013-07-08 17:17:08 -07002731 private void loadAllApps() {
2732 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002733
Joe Onorato36115782010-06-17 13:28:48 -04002734 final Callbacks oldCallbacks = mCallbacks.get();
2735 if (oldCallbacks == null) {
2736 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002737 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002738 return;
2739 }
2740
2741 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2742 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2743
Kenny Guyed131872014-04-30 03:02:21 +01002744 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2745
Winson Chung64359a52013-07-08 17:17:08 -07002746 // Clear the list of apps
2747 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002748 for (UserHandleCompat user : profiles) {
2749 // Query for the set of apps
2750 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2751 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2752 if (DEBUG_LOADERS) {
2753 Log.d(TAG, "getActivityList took "
2754 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2755 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2756 }
2757 // Fail if we don't have any apps
2758 if (apps == null || apps.isEmpty()) {
2759 return;
2760 }
2761 // Sort the applications by name
2762 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2763 Collections.sort(apps,
2764 new LauncherModel.ShortcutNameComparator(mLabelCache));
2765 if (DEBUG_LOADERS) {
2766 Log.d(TAG, "sort took "
2767 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2768 }
Joe Onorato36115782010-06-17 13:28:48 -04002769
Kenny Guyed131872014-04-30 03:02:21 +01002770 // Create the ApplicationInfos
2771 for (int i = 0; i < apps.size(); i++) {
2772 LauncherActivityInfoCompat app = apps.get(i);
2773 // This builds the icon bitmaps.
2774 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2775 }
Winson Chung64359a52013-07-08 17:17:08 -07002776 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002777 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002778 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2779 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002780
2781 // Post callback on main thread
2782 mHandler.post(new Runnable() {
2783 public void run() {
2784 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002785 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002786 if (callbacks != null) {
2787 callbacks.bindAllApplications(added);
2788 if (DEBUG_LOADERS) {
2789 Log.d(TAG, "bound " + added.size() + " apps in "
2790 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2791 }
2792 } else {
2793 Log.i(TAG, "not binding apps: no Launcher activity");
2794 }
2795 }
2796 });
2797
Joe Onorato36115782010-06-17 13:28:48 -04002798 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002799 Log.d(TAG, "Icons processed in "
2800 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002801 }
2802 }
2803
2804 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002805 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002806 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2807 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2808 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2809 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2810 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2811 }
Joe Onorato36115782010-06-17 13:28:48 -04002812 }
2813 }
2814
2815 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002816 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002817 }
2818
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002819 private class AppsAvailabilityCheck extends BroadcastReceiver {
2820
2821 @Override
2822 public void onReceive(Context context, Intent intent) {
2823 synchronized (sBgLock) {
2824 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2825 .getInstance(mApp.getContext());
2826 ArrayList<String> packagesRemoved;
2827 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2828 UserHandleCompat user = entry.getKey();
2829 packagesRemoved = new ArrayList<>();
2830 for (String pkg : entry.getValue()) {
2831 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2832 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2833 packagesRemoved.add(pkg);
2834 }
2835 }
2836 if (!packagesRemoved.isEmpty()) {
2837 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2838 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2839 }
2840 }
2841 sPendingPackages.clear();
2842 }
2843 }
2844 }
2845
Joe Onorato36115782010-06-17 13:28:48 -04002846 private class PackageUpdatedTask implements Runnable {
2847 int mOp;
2848 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002849 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002850
2851 public static final int OP_NONE = 0;
2852 public static final int OP_ADD = 1;
2853 public static final int OP_UPDATE = 2;
2854 public static final int OP_REMOVE = 3; // uninstlled
2855 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2856
2857
Kenny Guyed131872014-04-30 03:02:21 +01002858 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002859 mOp = op;
2860 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002861 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002862 }
2863
2864 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002865 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002866
2867 final String[] packages = mPackages;
2868 final int N = packages.length;
2869 switch (mOp) {
2870 case OP_ADD:
2871 for (int i=0; i<N; i++) {
2872 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002873 mIconCache.remove(packages[i], mUser);
2874 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002875 }
2876 break;
2877 case OP_UPDATE:
2878 for (int i=0; i<N; i++) {
2879 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002880 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002881 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002882 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002883 }
2884 break;
2885 case OP_REMOVE:
2886 case OP_UNAVAILABLE:
2887 for (int i=0; i<N; i++) {
2888 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002889 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002890 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002891 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002892 }
2893 break;
2894 }
2895
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002896 ArrayList<AppInfo> added = null;
2897 ArrayList<AppInfo> modified = null;
2898 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002899
Adam Cohen487f7dd2012-06-28 18:12:10 -07002900 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002901 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002902 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002903 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002904 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002905 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002906 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002907 }
Winson Chung5d55f332012-07-16 20:45:03 -07002908 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002909 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002910 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002911 }
2912
Joe Onorato36115782010-06-17 13:28:48 -04002913 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2914 if (callbacks == null) {
2915 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2916 return;
2917 }
2918
2919 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002920 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002921 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002922 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002923 addAndBindAddedWorkspaceApps(context, addedInfos);
2924 } else {
2925 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002926 }
Joe Onorato36115782010-06-17 13:28:48 -04002927 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002928
Joe Onorato36115782010-06-17 13:28:48 -04002929 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002930 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002931
2932 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002933 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002934 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01002935 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07002936 for (ItemInfo i : infos) {
2937 if (isShortcutInfoUpdateable(i)) {
2938 ShortcutInfo info = (ShortcutInfo) i;
2939 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01002940 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07002941 updateItemInDatabase(context, info);
2942 }
2943 }
2944 }
2945
Joe Onorato36115782010-06-17 13:28:48 -04002946 mHandler.post(new Runnable() {
2947 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002948 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2949 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002950 callbacks.bindAppsUpdated(modifiedFinal);
2951 }
2952 }
2953 });
2954 }
Winson Chung83892cc2013-05-01 16:53:33 -07002955
Winson Chungdf95eb12013-10-16 14:57:07 -07002956 final ArrayList<String> removedPackageNames =
2957 new ArrayList<String>();
2958 if (mOp == OP_REMOVE) {
2959 // Mark all packages in the broadcast to be removed
2960 removedPackageNames.addAll(Arrays.asList(packages));
2961 } else if (mOp == OP_UPDATE) {
2962 // Mark disabled packages in the broadcast to be removed
2963 final PackageManager pm = context.getPackageManager();
2964 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01002965 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002966 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002967 }
2968 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002969 }
2970 // Remove all the components associated with this package
2971 for (String pn : removedPackageNames) {
Kenny Guyed131872014-04-30 03:02:21 +01002972 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002973 for (ItemInfo i : infos) {
2974 deleteItemFromDatabase(context, i);
2975 }
2976 }
2977 // Remove all the specific components
2978 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01002979 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07002980 for (ItemInfo i : infos) {
2981 deleteItemFromDatabase(context, i);
2982 }
2983 }
2984 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2985 // Remove any queued items from the install queue
2986 String spKey = LauncherAppState.getSharedPreferencesKey();
2987 SharedPreferences sp =
2988 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2989 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2990 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002991 mHandler.post(new Runnable() {
2992 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002993 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2994 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01002995 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002996 }
2997 }
2998 });
Joe Onoratobe386092009-11-17 17:32:16 -08002999 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003000
Michael Jurkac402cd92013-05-20 15:49:32 +02003001 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003002 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003003 mHandler.post(new Runnable() {
3004 @Override
3005 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003006 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3007 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003008 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003009 }
3010 }
3011 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003012
3013 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003014 mHandler.post(new Runnable() {
3015 public void run() {
3016 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3017 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003018 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003019 }
3020 }
3021 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003022 }
3023 }
3024
Michael Jurkac402cd92013-05-20 15:49:32 +02003025 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3026 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3027 PackageManager packageManager = context.getPackageManager();
3028 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
3029 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
3030 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3031 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
3032 Collections.sort(widgetsAndShortcuts,
3033 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
3034 return widgetsAndShortcuts;
3035 }
3036
Kenny Guyed131872014-04-30 03:02:21 +01003037 private static boolean isPackageDisabled(Context context, String packageName,
3038 UserHandleCompat user) {
3039 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3040 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003041 }
Adam Cohen556f6132014-01-15 15:18:08 -08003042
Kenny Guyed131872014-04-30 03:02:21 +01003043 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3044 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003045 if (cn == null) {
3046 return false;
3047 }
Kenny Guyed131872014-04-30 03:02:21 +01003048 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3049 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003050 return false;
3051 }
Kenny Guyed131872014-04-30 03:02:21 +01003052 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003053 }
3054
Adam Cohena28b78e2014-05-20 17:03:04 -07003055 public static boolean isValidPackage(Context context, String packageName,
3056 UserHandleCompat user) {
3057 if (packageName == null) {
3058 return false;
3059 }
3060 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3061 return launcherApps.isPackageEnabledForProfile(packageName, user);
3062 }
3063
Joe Onorato9c1289c2009-08-17 11:03:03 -04003064 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003065 * Make an ShortcutInfo object for a restored application or shortcut item that points
3066 * to a package that is not yet installed on the system.
3067 */
Chris Wrenb6d4c282014-01-27 14:17:08 -05003068 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003069 final ShortcutInfo info = new ShortcutInfo();
Chris Wrenf4d08112014-01-16 18:13:56 -05003070 if (cursor != null) {
3071 info.title = cursor.getString(titleIndex);
3072 } else {
3073 info.title = "";
3074 }
Kenny Guyed131872014-04-30 03:02:21 +01003075 info.user = UserHandleCompat.myUserHandle();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003076 info.contentDescription = mUserManager.getBadgedLabelForUser(
3077 info.title.toString(), info.user);
Kenny Guyed131872014-04-30 03:02:21 +01003078 info.setIcon(mIconCache.getIcon(intent, info.title.toString(), info.user));
Chris Wrenf4d08112014-01-16 18:13:56 -05003079 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Chris Wrenb6d4c282014-01-27 14:17:08 -05003080 info.restoredIntent = intent;
Sunny Goyal34846382014-07-09 00:09:28 -07003081 info.wasPromise = true;
Chris Wren40c5ed32014-06-24 18:24:23 -04003082 info.setState(ShortcutInfo.PACKAGE_STATE_UNKNOWN);
Chris Wrenf4d08112014-01-16 18:13:56 -05003083 return info;
3084 }
3085
3086 /**
3087 * Make an Intent object for a restored application or shortcut item that points
3088 * to the market page for the item.
3089 */
3090 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003091 final boolean debug = false;
Chris Wrenf4d08112014-01-16 18:13:56 -05003092 ComponentName componentName = intent.getComponent();
3093 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
3094 Uri marketUri = new Uri.Builder()
3095 .scheme("market")
3096 .authority("details")
3097 .appendQueryParameter("id", componentName.getPackageName())
3098 .build();
Chris Wrenb6d4c282014-01-27 14:17:08 -05003099 if (debug) Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
Chris Wrenf4d08112014-01-16 18:13:56 -05003100 marketIntent.setData(marketUri);
3101 return marketIntent;
3102 }
3103
3104 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003105 * This is called from the code that adds shortcuts from the intent receiver. This
3106 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003107 */
Kenny Guyed131872014-04-30 03:02:21 +01003108 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3109 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003110 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003111 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003112
Joe Onorato56d82912010-03-07 14:32:10 -05003113 /**
3114 * Make an ShortcutInfo object for a shortcut that is an application.
3115 *
3116 * If c is not null, then it will be used to fill in missing data like the title and icon.
3117 */
Kenny Guyed131872014-04-30 03:02:21 +01003118 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3119 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003120 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003121 if (user == null) {
3122 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003123 return null;
3124 }
3125
Kenny Guyed131872014-04-30 03:02:21 +01003126 ComponentName componentName = intent.getComponent();
3127 if (componentName == null) {
3128 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3129 return null;
3130 }
3131
3132 Intent newIntent = new Intent(intent.getAction(), null);
3133 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3134 newIntent.setComponent(componentName);
3135 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003136 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003137 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3138 return null;
3139 }
3140
3141 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003142
Joe Onorato56d82912010-03-07 14:32:10 -05003143 // the resource -- This may implicitly give us back the fallback icon,
3144 // but don't worry about that. All we're doing with usingFallbackIcon is
3145 // to avoid saving lots of copies of that in the database, and most apps
3146 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003147 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003148
Joe Onorato56d82912010-03-07 14:32:10 -05003149 // the db
3150 if (icon == null) {
3151 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003152 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003153 }
3154 }
3155 // the fallback icon
3156 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003157 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003158 info.usingFallbackIcon = true;
3159 }
3160 info.setIcon(icon);
3161
Kenny Guyed131872014-04-30 03:02:21 +01003162 // From the cache.
3163 if (labelCache != null) {
3164 info.title = labelCache.get(componentName);
3165 }
3166
Joe Onorato56d82912010-03-07 14:32:10 -05003167 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003168 if (info.title == null && lai != null) {
3169 info.title = lai.getLabel();
3170 if (labelCache != null) {
3171 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003172 }
Joe Onorato56d82912010-03-07 14:32:10 -05003173 }
3174 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003175 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003176 if (c != null) {
3177 info.title = c.getString(titleIndex);
3178 }
3179 }
3180 // fall back to the class name of the activity
3181 if (info.title == null) {
3182 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003183 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003184 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003185 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003186 info.contentDescription = mUserManager.getBadgedLabelForUser(
3187 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003188 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003189 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003190
Winson Chung64359a52013-07-08 17:17:08 -07003191 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3192 ItemInfoFilter f) {
3193 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3194 for (ItemInfo i : infos) {
3195 if (i instanceof ShortcutInfo) {
3196 ShortcutInfo info = (ShortcutInfo) i;
3197 ComponentName cn = info.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003198 if (info.restoredIntent != null) {
3199 cn = info.restoredIntent.getComponent();
3200 }
Winson Chung64359a52013-07-08 17:17:08 -07003201 if (cn != null && f.filterItem(null, info, cn)) {
3202 filtered.add(info);
3203 }
3204 } else if (i instanceof FolderInfo) {
3205 FolderInfo info = (FolderInfo) i;
3206 for (ShortcutInfo s : info.contents) {
3207 ComponentName cn = s.intent.getComponent();
Chris Wren40c5ed32014-06-24 18:24:23 -04003208 if (s.restoredIntent != null) {
3209 cn = s.restoredIntent.getComponent();
3210 }
Winson Chung64359a52013-07-08 17:17:08 -07003211 if (cn != null && f.filterItem(info, s, cn)) {
3212 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003213 }
3214 }
Winson Chung64359a52013-07-08 17:17:08 -07003215 } else if (i instanceof LauncherAppWidgetInfo) {
3216 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3217 ComponentName cn = info.providerName;
3218 if (cn != null && f.filterItem(null, info, cn)) {
3219 filtered.add(info);
3220 }
Winson Chung8a435102012-08-30 17:16:53 -07003221 }
3222 }
Winson Chung64359a52013-07-08 17:17:08 -07003223 return new ArrayList<ItemInfo>(filtered);
3224 }
3225
Kenny Guyed131872014-04-30 03:02:21 +01003226 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn,
3227 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003228 ItemInfoFilter filter = new ItemInfoFilter() {
3229 @Override
3230 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003231 return cn.getPackageName().equals(pn) && info.user.equals(user);
Winson Chung64359a52013-07-08 17:17:08 -07003232 }
3233 };
3234 return filterItemInfos(sBgItemsIdMap.values(), filter);
3235 }
3236
Kenny Guyed131872014-04-30 03:02:21 +01003237 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3238 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003239 ItemInfoFilter filter = new ItemInfoFilter() {
3240 @Override
3241 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003242 if (info.user == null) {
3243 return cn.equals(cname);
3244 } else {
3245 return cn.equals(cname) && info.user.equals(user);
3246 }
Winson Chung64359a52013-07-08 17:17:08 -07003247 }
3248 };
3249 return filterItemInfos(sBgItemsIdMap.values(), filter);
3250 }
3251
3252 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3253 if (i instanceof ShortcutInfo) {
3254 ShortcutInfo info = (ShortcutInfo) i;
3255 // We need to check for ACTION_MAIN otherwise getComponent() might
3256 // return null for some shortcuts (for instance, for shortcuts to
3257 // web pages.)
3258 Intent intent = info.intent;
3259 ComponentName name = intent.getComponent();
3260 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3261 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3262 return true;
3263 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003264 // placeholder shortcuts get special treatment, let them through too.
3265 if (info.getRestoredIntent() != null) {
3266 return true;
3267 }
Winson Chung64359a52013-07-08 17:17:08 -07003268 }
3269 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003270 }
3271
3272 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003273 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003274 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003275 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003276 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3277 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003278
Joe Onorato56d82912010-03-07 14:32:10 -05003279 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003280 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003281 // Non-app shortcuts are only supported for current user.
3282 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003283 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003284
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003285 // TODO: If there's an explicit component and we can't install that, delete it.
3286
Joe Onorato56d82912010-03-07 14:32:10 -05003287 info.title = c.getString(titleIndex);
3288
Joe Onorato9c1289c2009-08-17 11:03:03 -04003289 int iconType = c.getInt(iconTypeIndex);
3290 switch (iconType) {
3291 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3292 String packageName = c.getString(iconPackageIndex);
3293 String resourceName = c.getString(iconResourceIndex);
3294 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003295 info.customIcon = false;
3296 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003297 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003298 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003299 if (resources != null) {
3300 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003301 icon = Utilities.createIconBitmap(
3302 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003303 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003304 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003305 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003306 }
Joe Onorato56d82912010-03-07 14:32:10 -05003307 // the db
3308 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003309 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003310 }
3311 // the fallback icon
3312 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003313 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003314 info.usingFallbackIcon = true;
3315 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003316 break;
3317 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003318 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003319 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003320 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003321 info.customIcon = false;
3322 info.usingFallbackIcon = true;
3323 } else {
3324 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003325 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003326 break;
3327 default:
Kenny Guyed131872014-04-30 03:02:21 +01003328 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003329 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003330 info.customIcon = false;
3331 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003332 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003333 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003334 return info;
3335 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003336
Michael Jurka931dc972011-08-05 15:08:15 -07003337 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003338 @SuppressWarnings("all") // suppress dead code warning
3339 final boolean debug = false;
3340 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003341 Log.d(TAG, "getIconFromCursor app="
3342 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3343 }
3344 byte[] data = c.getBlob(iconIndex);
3345 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003346 return Utilities.createIconBitmap(
3347 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003348 } catch (Exception e) {
3349 return null;
3350 }
3351 }
3352
Winson Chung3d503fb2011-07-13 17:25:49 -07003353 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3354 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003355 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003356 if (info == null) {
3357 return null;
3358 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003359 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003360
3361 return info;
3362 }
3363
Winson Chunga9abd0e2010-10-27 17:18:37 -07003364 /**
Winson Chung55cef262010-10-28 14:14:18 -07003365 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3366 */
3367 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3368 ComponentName component) {
3369 List<AppWidgetProviderInfo> widgets =
3370 AppWidgetManager.getInstance(context).getInstalledProviders();
3371 for (AppWidgetProviderInfo info : widgets) {
3372 if (info.provider.equals(component)) {
3373 return info;
3374 }
3375 }
3376 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003377 }
3378
Winson Chung68846fd2010-10-29 11:00:27 -07003379 /**
3380 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3381 */
3382 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3383 final PackageManager packageManager = context.getPackageManager();
3384 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3385 new ArrayList<WidgetMimeTypeHandlerData>();
3386
3387 final Intent supportsIntent =
3388 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3389 supportsIntent.setType(mimeType);
3390
3391 // Create a set of widget configuration components that we can test against
3392 final List<AppWidgetProviderInfo> widgets =
3393 AppWidgetManager.getInstance(context).getInstalledProviders();
3394 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3395 new HashMap<ComponentName, AppWidgetProviderInfo>();
3396 for (AppWidgetProviderInfo info : widgets) {
3397 configurationComponentToWidget.put(info.configure, info);
3398 }
3399
3400 // Run through each of the intents that can handle this type of clip data, and cross
3401 // reference them with the components that are actual configuration components
3402 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3403 PackageManager.MATCH_DEFAULT_ONLY);
3404 for (ResolveInfo info : activities) {
3405 final ActivityInfo activityInfo = info.activityInfo;
3406 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3407 activityInfo.name);
3408 if (configurationComponentToWidget.containsKey(infoComponent)) {
3409 supportedConfigurationActivities.add(
3410 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3411 configurationComponentToWidget.get(infoComponent)));
3412 }
3413 }
3414 return supportedConfigurationActivities;
3415 }
3416
Winson Chunga9abd0e2010-10-27 17:18:37 -07003417 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003418 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3419 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3420 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3421
Adam Cohend9198822011-11-22 16:42:47 -08003422 if (intent == null) {
3423 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3424 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3425 return null;
3426 }
3427
Joe Onorato0589f0f2010-02-08 13:44:00 -08003428 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003429 boolean customIcon = false;
3430 ShortcutIconResource iconResource = null;
3431
3432 if (bitmap != null && bitmap instanceof Bitmap) {
3433 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003434 customIcon = true;
3435 } else {
3436 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3437 if (extra != null && extra instanceof ShortcutIconResource) {
3438 try {
3439 iconResource = (ShortcutIconResource) extra;
3440 final PackageManager packageManager = context.getPackageManager();
3441 Resources resources = packageManager.getResourcesForApplication(
3442 iconResource.packageName);
3443 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003444 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003445 mIconCache.getFullResIcon(resources, id),
3446 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003447 } catch (Exception e) {
3448 Log.w(TAG, "Could not load shortcut icon: " + extra);
3449 }
3450 }
3451 }
3452
Michael Jurkac9d95c52011-08-29 14:03:34 -07003453 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003454
Kenny Guyed131872014-04-30 03:02:21 +01003455 // Only support intents for current user for now. Intents sent from other
3456 // users wouldn't get here without intent forwarding anyway.
3457 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003458 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003459 if (fallbackIcon != null) {
3460 icon = fallbackIcon;
3461 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003462 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003463 info.usingFallbackIcon = true;
3464 }
Joe Onorato56d82912010-03-07 14:32:10 -05003465 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003466 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003467
Joe Onorato0589f0f2010-02-08 13:44:00 -08003468 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003469 info.contentDescription = mUserManager.getBadgedLabelForUser(
3470 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003471 info.intent = intent;
3472 info.customIcon = customIcon;
3473 info.iconResource = iconResource;
3474
3475 return info;
3476 }
3477
Winson Chungaac01e12011-08-17 10:37:13 -07003478 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3479 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003480 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003481 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003482 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003483 }
Joe Onorato56d82912010-03-07 14:32:10 -05003484 // If this icon doesn't have a custom icon, check to see
3485 // what's stored in the DB, and if it doesn't match what
3486 // we're going to show, store what we are going to show back
3487 // into the DB. We do this so when we're loading, if the
3488 // package manager can't find an icon (for example because
3489 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003490 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003491 cache.put(info, c.getBlob(iconIndex));
3492 return true;
3493 }
3494 return false;
3495 }
3496 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3497 boolean needSave = false;
3498 try {
3499 if (data != null) {
3500 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3501 Bitmap loaded = info.getIcon(mIconCache);
3502 needSave = !saved.sameAs(loaded);
3503 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003504 needSave = true;
3505 }
Winson Chungaac01e12011-08-17 10:37:13 -07003506 } catch (Exception e) {
3507 needSave = true;
3508 }
3509 if (needSave) {
3510 Log.d(TAG, "going to save icon bitmap for info=" + info);
3511 // This is slower than is ideal, but this only happens once
3512 // or when the app is updated with a new icon.
3513 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003514 }
3515 }
3516
Joe Onorato9c1289c2009-08-17 11:03:03 -04003517 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003518 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003519 * or make a new one.
3520 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003521 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003522 // See if a placeholder was created for us already
3523 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003524 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003525 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003526 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003527 folders.put(id, folderInfo);
3528 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003529 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003530 }
3531
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003532 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003533 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003534 return new Comparator<AppInfo>() {
3535 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003536 if (a.user.equals(b.user)) {
3537 int result = collator.compare(a.title.toString().trim(),
3538 b.title.toString().trim());
3539 if (result == 0) {
3540 result = a.componentName.compareTo(b.componentName);
3541 }
3542 return result;
3543 } else {
3544 // TODO Need to figure out rules for sorting
3545 // profiles, this puts work second.
3546 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003547 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003548 }
Winson Chung11904872012-09-17 16:58:46 -07003549 };
3550 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003551 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3552 = new Comparator<AppInfo>() {
3553 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003554 if (a.firstInstallTime < b.firstInstallTime) return 1;
3555 if (a.firstInstallTime > b.firstInstallTime) return -1;
3556 return 0;
3557 }
3558 };
Winson Chung11904872012-09-17 16:58:46 -07003559 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3560 final Collator collator = Collator.getInstance();
3561 return new Comparator<AppWidgetProviderInfo>() {
3562 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003563 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003564 }
3565 };
3566 }
Winson Chung5308f242011-08-18 12:12:41 -07003567 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3568 if (info.activityInfo != null) {
3569 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3570 } else {
3571 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3572 }
3573 }
Kenny Guyed131872014-04-30 03:02:21 +01003574 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003575 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003576 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003577 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003578 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003579 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003580 }
Kenny Guyed131872014-04-30 03:02:21 +01003581 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003582 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003583 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003584 }
Kenny Guyed131872014-04-30 03:02:21 +01003585 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003586 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003587 ComponentName keyA = a.getComponentName();
3588 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003589 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003590 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003591 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003592 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003593
Winson Chung5308f242011-08-18 12:12:41 -07003594 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003595 }
Winson Chung5308f242011-08-18 12:12:41 -07003596 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003597 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003598 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003599 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003600
Winson Chung5308f242011-08-18 12:12:41 -07003601 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003602 }
Winson Chung11904872012-09-17 16:58:46 -07003603 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003604 }
3605 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003606 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003607 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003608 private PackageManager mPackageManager;
3609 private HashMap<Object, String> mLabelCache;
3610 WidgetAndShortcutNameComparator(PackageManager pm) {
3611 mPackageManager = pm;
3612 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003613 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003614 }
3615 public final int compare(Object a, Object b) {
3616 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003617 if (mLabelCache.containsKey(a)) {
3618 labelA = mLabelCache.get(a);
3619 } else {
3620 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003621 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003622 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003623 mLabelCache.put(a, labelA);
3624 }
3625 if (mLabelCache.containsKey(b)) {
3626 labelB = mLabelCache.get(b);
3627 } else {
3628 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003629 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003630 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003631 mLabelCache.put(b, labelB);
3632 }
Winson Chung11904872012-09-17 16:58:46 -07003633 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003634 }
3635 };
Joe Onoratobe386092009-11-17 17:32:16 -08003636
Sunny Goyal651077b2014-06-30 14:15:31 -07003637 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3638 return (provider != null) && (provider.provider != null)
3639 && (provider.provider.getPackageName() != null);
3640 }
3641
Joe Onoratobe386092009-11-17 17:32:16 -08003642 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003643 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003644 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3645 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3646 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3647 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003648 if (mLoaderTask != null) {
3649 mLoaderTask.dumpState();
3650 } else {
3651 Log.d(TAG, "mLoaderTask=null");
3652 }
Joe Onoratobe386092009-11-17 17:32:16 -08003653 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003654}