blob: c372b47d12ea68583cff1789705150aa8e09d960 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070022import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.ContentProviderClient;
25import android.content.ContentProviderOperation;
26import android.content.ContentResolver;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080030import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070031import android.content.IntentFilter;
32import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040034import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070036import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.content.res.Resources;
38import android.database.Cursor;
39import android.graphics.Bitmap;
40import android.graphics.BitmapFactory;
41import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040049import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080050import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070051import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070077import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070078import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080/**
81 * Maintains in-memory state of the Launcher. It is expected that there should be only one
82 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070083 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 */
Kenny Guyed131872014-04-30 03:02:21 +010085public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010086 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040088 private static final boolean DEBUG_RECEIVER = false;
Chris Wrenb358f812014-04-16 13:37:00 -040089
Joe Onorato9c1289c2009-08-17 11:03:03 -040090 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070091
Daniel Sandler8707e0f2013-08-15 15:54:18 -070092 // true = use a "More Apps" folder for non-workspace apps on upgrade
93 // false = strew non-workspace apps across the workspace on upgrade
94 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050095 public static final int LOADER_FLAG_NONE = 0;
96 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
97 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
98
Joe Onorato36115782010-06-17 13:28:48 -040099 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500100 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800101
Winson Chungee055712013-07-30 14:46:24 -0700102 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800103 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400104
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400105 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400106 private final Object mLock = new Object();
107 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400108 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200110 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
Winson Chung81b52252012-08-27 15:34:29 -0700112 // Specific runnable types that are run on the main thread deferred handler, this allows us to
113 // clear all queued binding runnables when the Launcher activity is destroyed.
114 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
115 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
116
Jason Monkbbe1e242014-05-16 17:37:34 -0400117 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700118
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700119 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
120 static {
121 sWorkerThread.start();
122 }
123 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
124
Joe Onoratocc67f472010-06-08 10:54:30 -0700125 // We start off with everything not loaded. After that, we assume that
126 // our monitoring of the package manager provides all updates and we never
127 // need to do a requery. These are only ever touched from the loader thread.
128 private boolean mWorkspaceLoaded;
129 private boolean mAllAppsLoaded;
130
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700131 // When we are loading pages synchronously, we can't just post the binding of items on the side
132 // pages as this delays the rotation process. Instead, we wait for a callback from the first
133 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
134 // a normal load, we also clear this set of Runnables.
135 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
136
Joe Onorato9c1289c2009-08-17 11:03:03 -0400137 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800138
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700139 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700140 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800141
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700142 // The lock that must be acquired before referencing any static bg data structures. Unlike
143 // other locks, this one can generally be held long-term because we never expect any of these
144 // static data structures to be referenced outside of the worker thread except on the first
145 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700146 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700147
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151
Adam Cohen487f7dd2012-06-28 18:12:10 -0700152 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
153 // created by LauncherModel that are directly on the home screen (however, no widgets or
154 // shortcuts within folders).
155 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156
Adam Cohen487f7dd2012-06-28 18:12:10 -0700157 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
158 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159 new ArrayList<LauncherAppWidgetInfo>();
160
Adam Cohen487f7dd2012-06-28 18:12:10 -0700161 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
162 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700163
Adam Cohen487f7dd2012-06-28 18:12:10 -0700164 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
165 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700166
167 // sBgWorkspaceScreens is the ordered set of workspace screens.
168 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
169
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700170 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700171 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
172 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700173
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 // </ only access in worker thread >
175
176 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177
Reena Lee99a73f32011-10-24 17:27:37 -0700178 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700179
Kenny Guyed131872014-04-30 03:02:21 +0100180 private final LauncherAppsCompat mLauncherApps;
181 private final UserManagerCompat mUserManager;
182
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700184 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400185 public int getCurrentWorkspaceScreen();
186 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700187 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
188 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700189 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700190 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500191 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700192 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400193 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200194 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700195 public void bindAppsAdded(ArrayList<Long> newScreens,
196 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700197 ArrayList<ItemInfo> addAnimated,
198 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200199 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyale755d462014-07-22 13:48:29 -0700200 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700201 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700202 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100203 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200204 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100205 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700206 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700207 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700208 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400209 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
Winson Chung64359a52013-07-08 17:17:08 -0700211 public interface ItemInfoFilter {
212 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
213 }
214
Bjorn Bringert1307f632013-10-03 22:31:03 +0100215 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800216 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400217
Winson Chungee055712013-07-30 14:46:24 -0700218 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700219 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400220 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
221 // resource string.
222 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
223 ProviderInfo providerInfo =
224 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
225 ProviderInfo redirectProvider =
226 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700227
228 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400229 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700230
231 if (mOldContentProviderExists) {
232 Log.d(TAG, "Old launcher provider exists.");
233 } else {
234 Log.d(TAG, "Old launcher provider does not exist.");
235 }
236
Daniel Sandlere4f98912013-06-25 15:13:26 -0400237 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100238 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800239 mIconCache = iconCache;
240
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400241 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700242 Configuration config = res.getConfiguration();
243 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100244 mLauncherApps = LauncherAppsCompat.getInstance(context);
245 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800246 }
247
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700248 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
249 * posted on the main thread handler. */
250 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700251 runOnMainThread(r, 0);
252 }
253 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700254 if (sWorkerThread.getThreadId() == Process.myTid()) {
255 // If we are on the worker thread, post onto the main handler
256 mHandler.post(r);
257 } else {
258 r.run();
259 }
260 }
261
262 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
263 * posted on the worker thread handler. */
264 private static void runOnWorkerThread(Runnable r) {
265 if (sWorkerThread.getThreadId() == Process.myTid()) {
266 r.run();
267 } else {
268 // If we are not on the worker thread, then post to the worker handler
269 sWorker.post(r);
270 }
271 }
272
Winson Chunge43a1e72014-01-15 10:33:02 -0800273 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
274 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800275 }
276
Winson Chungc9168342013-06-26 14:54:55 -0700277 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
278 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700279 LauncherAppState app = LauncherAppState.getInstance();
280 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
281 final int xCount = (int) grid.numColumns;
282 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700283 boolean[][] occupied = new boolean[xCount][yCount];
284
285 int cellX, cellY, spanX, spanY;
286 for (int i = 0; i < items.size(); ++i) {
287 final ItemInfo item = items.get(i);
288 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
289 if (item.screenId == screen) {
290 cellX = item.cellX;
291 cellY = item.cellY;
292 spanX = item.spanX;
293 spanY = item.spanY;
294 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
295 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
296 occupied[x][y] = true;
297 }
298 }
299 }
300 }
301 }
302
303 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
304 }
305 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700306 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700307 int firstScreenIndex,
308 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700309 // Lock on the app so that we don't try and get the items while apps are being added
310 LauncherAppState app = LauncherAppState.getInstance();
311 LauncherModel model = app.getModel();
312 boolean found = false;
313 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700314 if (sWorkerThread.getThreadId() != Process.myTid()) {
315 // Flush the LauncherModel worker thread, so that if we just did another
316 // processInstallShortcut, we give it time for its shortcut to get added to the
317 // database (getItemsInLocalCoordinates reads the database)
318 model.flushWorkerThread();
319 }
Winson Chungc9168342013-06-26 14:54:55 -0700320 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700321
322 // Try adding to the workspace screens incrementally, starting at the default or center
323 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700324 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
325 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700326 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700327 int[] tmpCoordinates = new int[2];
328 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700329 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700330 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700331 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700332 }
333 }
334 }
Winson Chungc9168342013-06-26 14:54:55 -0700335 return null;
336 }
337
Sunny Goyale755d462014-07-22 13:48:29 -0700338 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500339 // Process the updated package state
340 Runnable r = new Runnable() {
341 public void run() {
342 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
343 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700344 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500345 }
346 }
347 };
348 mHandler.post(r);
349 }
350
Sunny Goyala22666f2014-09-18 13:25:15 -0700351 public void updatePackageBadge(final String packageName) {
352 // Process the updated package badge
353 Runnable r = new Runnable() {
354 public void run() {
355 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
356 if (callbacks != null) {
357 callbacks.updatePackageBadge(packageName);
358 }
359 }
360 };
361 mHandler.post(r);
362 }
363
Adam Cohen76a47a12014-02-05 11:47:43 -0800364 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
365 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
366
367 if (allAppsApps == null) {
368 throw new RuntimeException("allAppsApps must not be null");
369 }
370 if (allAppsApps.isEmpty()) {
371 return;
372 }
373
Chris Wrenb6d4c282014-01-27 14:17:08 -0500374 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
375 Iterator<AppInfo> iter = allAppsApps.iterator();
376 while (iter.hasNext()) {
377 ItemInfo a = iter.next();
Sunny Goyal34942622014-08-29 17:20:55 -0700378 if (LauncherModel.appWasPromise(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500379 restoredAppsFinal.add((AppInfo) a);
380 }
381 }
382
Adam Cohen76a47a12014-02-05 11:47:43 -0800383 // Process the newly added applications and add them to the database first
384 Runnable r = new Runnable() {
385 public void run() {
386 runOnMainThread(new Runnable() {
387 public void run() {
388 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
389 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500390 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500391 for (AppInfo info : restoredAppsFinal) {
392 final Intent intent = info.getIntent();
393 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100394 mIconCache.deletePreloadedIcon(intent.getComponent(),
395 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500396 }
397 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500398 callbacks.bindAppsUpdated(restoredAppsFinal);
399 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500400 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800401 }
402 }
403 });
404 }
405 };
406 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700407 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800408
409 public void addAndBindAddedWorkspaceApps(final Context context,
410 final ArrayList<ItemInfo> workspaceApps) {
411 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
412
413 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800414 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
415 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800416 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700417 return;
Winson Chung997a9232013-07-24 15:33:46 -0700418 }
Winson Chung64359a52013-07-08 17:17:08 -0700419 // Process the newly added applications and add them to the database first
420 Runnable r = new Runnable() {
421 public void run() {
422 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
423 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500424 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700425
Winson Chung76828c82013-08-19 15:43:29 -0700426 // Get the list of workspace screens. We need to append to this list and
427 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
428 // called.
429 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
430 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
431 for (Integer i : orderedScreens.keySet()) {
432 long screenId = orderedScreens.get(i);
433 workspaceScreens.add(screenId);
434 }
435
Winson Chung64359a52013-07-08 17:17:08 -0700436 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700437 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700438 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700439 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700440 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700441 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700442
443 // Short-circuit this logic if the icon exists somewhere on the workspace
444 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500445 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
446 if (a instanceof AppInfo &&
Sunny Goyal34942622014-08-29 17:20:55 -0700447 LauncherModel.appWasPromise(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500448 restoredAppsFinal.add((AppInfo) a);
449 }
Winson Chung64359a52013-07-08 17:17:08 -0700450 continue;
451 }
452
Winson Chung87412982013-10-03 18:34:14 -0700453 // Add this icon to the db, creating a new page if necessary. If there
454 // is only the empty page then we just add items to the first page.
455 // Otherwise, we add them to the next pages.
456 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700457 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700458 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700459 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200460 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700461
462 // If we can't find a valid position, then just add a new screen.
463 // This takes time so we need to re-queue the add until the new
464 // page is added. Create as many screens as necessary to satisfy
465 // the startSearchPageIndex.
466 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700467 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700468 while (numPagesToAdd > 0) {
469 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700470 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700471 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 addedWorkspaceScreensFinal.add(screenId);
473 numPagesToAdd--;
474 }
Winson Chung76828c82013-08-19 15:43:29 -0700475
Winson Chung64359a52013-07-08 17:17:08 -0700476 // Find the coordinate again
477 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700478 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700479 }
480 if (coords == null) {
481 throw new RuntimeException("Coordinates should not be null");
482 }
483
Winson Chung997a9232013-07-24 15:33:46 -0700484 ShortcutInfo shortcutInfo;
485 if (a instanceof ShortcutInfo) {
486 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200487 } else if (a instanceof AppInfo) {
488 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700489 } else {
490 throw new RuntimeException("Unexpected info type");
491 }
Winson Chung94d67682013-09-25 16:29:40 -0700492
Winson Chung64359a52013-07-08 17:17:08 -0700493 // Add the shortcut to the db
494 addItemToDatabase(context, shortcutInfo,
495 LauncherSettings.Favorites.CONTAINER_DESKTOP,
496 coords.first, coords.second[0], coords.second[1], false);
497 // Save the ShortcutInfo for binding in the workspace
498 addedShortcutsFinal.add(shortcutInfo);
499 }
500 }
501
Winson Chung76828c82013-08-19 15:43:29 -0700502 // Update the workspace screens
503 updateWorkspaceScreenOrder(context, workspaceScreens);
504
Adam Cohen76a47a12014-02-05 11:47:43 -0800505 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700506 runOnMainThread(new Runnable() {
507 public void run() {
508 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
509 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700510 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
511 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700512 if (!addedShortcutsFinal.isEmpty()) {
513 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
514 long lastScreenId = info.screenId;
515 for (ItemInfo i : addedShortcutsFinal) {
516 if (i.screenId == lastScreenId) {
517 addAnimated.add(i);
518 } else {
519 addNotAnimated.add(i);
520 }
Winson Chung997a9232013-07-24 15:33:46 -0700521 }
522 }
Winson Chungd64d1762013-08-20 14:37:16 -0700523 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800524 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500525 if (!restoredAppsFinal.isEmpty()) {
526 callbacks.bindAppsUpdated(restoredAppsFinal);
527 }
Winson Chung997a9232013-07-24 15:33:46 -0700528 }
Winson Chung64359a52013-07-08 17:17:08 -0700529 }
Winson Chung997a9232013-07-24 15:33:46 -0700530 });
531 }
Winson Chung64359a52013-07-08 17:17:08 -0700532 }
533 };
534 runOnWorkerThread(r);
535 }
536
Winson Chung81b52252012-08-27 15:34:29 -0700537 public void unbindItemInfosAndClearQueuedBindRunnables() {
538 if (sWorkerThread.getThreadId() == Process.myTid()) {
539 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
540 "main thread");
541 }
542
543 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400544 synchronized (mDeferredBindRunnables) {
545 mDeferredBindRunnables.clear();
546 }
Winson Chung81b52252012-08-27 15:34:29 -0700547 // Remove any queued bind runnables
548 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
549 // Unbind all the workspace items
550 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700551 }
552
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700553 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700554 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700555 // Ensure that we don't use the same workspace items data structure on the main thread
556 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700557 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
558 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700559 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700560 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
561 tmpAppWidgets.addAll(sBgAppWidgets);
562 }
563 Runnable r = new Runnable() {
564 @Override
565 public void run() {
566 for (ItemInfo item : tmpWorkspaceItems) {
567 item.unbind();
568 }
569 for (ItemInfo item : tmpAppWidgets) {
570 item.unbind();
571 }
572 }
573 };
574 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700575 }
576
Joe Onorato9c1289c2009-08-17 11:03:03 -0400577 /**
578 * Adds an item to the DB if it was not created previously, or move it to a new
579 * <container, screen, cellX, cellY>
580 */
581 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700582 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400583 if (item.container == ItemInfo.NO_ID) {
584 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700585 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400586 } else {
587 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700588 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589 }
590 }
591
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700592 static void checkItemInfoLocked(
593 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
594 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
595 if (modelItem != null && item != modelItem) {
596 // check all the data is consistent
597 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
598 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
599 ShortcutInfo shortcut = (ShortcutInfo) item;
600 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
601 modelShortcut.intent.filterEquals(shortcut.intent) &&
602 modelShortcut.id == shortcut.id &&
603 modelShortcut.itemType == shortcut.itemType &&
604 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700605 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700606 modelShortcut.cellX == shortcut.cellX &&
607 modelShortcut.cellY == shortcut.cellY &&
608 modelShortcut.spanX == shortcut.spanX &&
609 modelShortcut.spanY == shortcut.spanY &&
610 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
611 (modelShortcut.dropPos != null &&
612 shortcut.dropPos != null &&
613 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
614 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
615 // For all intents and purposes, this is the same object
616 return;
617 }
618 }
619
620 // the modelItem needs to match up perfectly with item if our model is
621 // to be consistent with the database-- for now, just require
622 // modelItem == item or the equality check above
623 String msg = "item: " + ((item != null) ? item.toString() : "null") +
624 "modelItem: " +
625 ((modelItem != null) ? modelItem.toString() : "null") +
626 "Error: ItemInfo passed to checkItemInfo doesn't match original";
627 RuntimeException e = new RuntimeException(msg);
628 if (stackTrace != null) {
629 e.setStackTrace(stackTrace);
630 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800631 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700632 }
633 }
634
Michael Jurka816474f2012-06-25 14:49:02 -0700635 static void checkItemInfo(final ItemInfo item) {
636 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
637 final long itemId = item.id;
638 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700639 public void run() {
640 synchronized (sBgLock) {
641 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700642 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700643 }
644 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700645 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700646 }
647
Michael Jurkac9d95c52011-08-29 14:03:34 -0700648 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
649 final ItemInfo item, final String callingFunction) {
650 final long itemId = item.id;
651 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
652 final ContentResolver cr = context.getContentResolver();
653
Adam Cohen487f7dd2012-06-28 18:12:10 -0700654 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700655 Runnable r = new Runnable() {
656 public void run() {
657 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700658 updateItemArrays(item, itemId, stackTrace);
659 }
660 };
661 runOnWorkerThread(r);
662 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700663
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700664 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
665 final ArrayList<ItemInfo> items, final String callingFunction) {
666 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700667
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700668 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
669 Runnable r = new Runnable() {
670 public void run() {
671 ArrayList<ContentProviderOperation> ops =
672 new ArrayList<ContentProviderOperation>();
673 int count = items.size();
674 for (int i = 0; i < count; i++) {
675 ItemInfo item = items.get(i);
676 final long itemId = item.id;
677 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
678 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700679
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700680 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
681 updateItemArrays(item, itemId, stackTrace);
682
683 }
684 try {
685 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
686 } catch (Exception e) {
687 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700688 }
689 }
690 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700691 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700692 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700693
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700694 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
695 // Lock on mBgLock *after* the db operation
696 synchronized (sBgLock) {
697 checkItemInfoLocked(itemId, item, stackTrace);
698
699 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
700 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
701 // Item is in a folder, make sure this folder exists
702 if (!sBgFolders.containsKey(item.container)) {
703 // An items container is being set to a that of an item which is not in
704 // the list of Folders.
705 String msg = "item: " + item + " container being set to: " +
706 item.container + ", not in the list of folders";
707 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700708 }
709 }
710
711 // Items are added/removed from the corresponding FolderInfo elsewhere, such
712 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
713 // that are on the desktop, as appropriate
714 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800715 if (modelItem != null &&
716 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
717 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700718 switch (modelItem.itemType) {
719 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
720 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
721 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
722 if (!sBgWorkspaceItems.contains(modelItem)) {
723 sBgWorkspaceItems.add(modelItem);
724 }
725 break;
726 default:
727 break;
728 }
729 } else {
730 sBgWorkspaceItems.remove(modelItem);
731 }
732 }
733 }
734
Michael Jurkac7700af2013-05-14 20:17:58 +0200735 public void flushWorkerThread() {
736 mFlushingWorkerThread = true;
737 Runnable waiter = new Runnable() {
738 public void run() {
739 synchronized (this) {
740 notifyAll();
741 mFlushingWorkerThread = false;
742 }
743 }
744 };
745
746 synchronized(waiter) {
747 runOnWorkerThread(waiter);
748 if (mLoaderTask != null) {
749 synchronized(mLoaderTask) {
750 mLoaderTask.notify();
751 }
752 }
753 boolean success = false;
754 while (!success) {
755 try {
756 waiter.wait();
757 success = true;
758 } catch (InterruptedException e) {
759 }
760 }
761 }
762 }
763
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800764 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400765 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700766 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700767 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700768 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400769 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400770 item.cellX = cellX;
771 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700772
Winson Chung3d503fb2011-07-13 17:25:49 -0700773 // We store hotseat items in canonical form which is this orientation invariant position
774 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700775 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700776 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700777 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700778 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700779 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700780 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400781
782 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400783 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700784 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
785 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700786 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400787
Michael Jurkac9d95c52011-08-29 14:03:34 -0700788 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700789 }
790
791 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700792 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
793 * cellX, cellY have already been updated on the ItemInfos.
794 */
795 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
796 final long container, final int screen) {
797
798 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
799 int count = items.size();
800
801 for (int i = 0; i < count; i++) {
802 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700803 item.container = container;
804
805 // We store hotseat items in canonical form which is this orientation invariant position
806 // in the hotseat
807 if (context instanceof Launcher && screen < 0 &&
808 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700809 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700810 item.cellY);
811 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700812 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700813 }
814
815 final ContentValues values = new ContentValues();
816 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
817 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
818 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700819 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700820
821 contentValues.add(values);
822 }
823 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
824 }
825
826 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800828 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700830 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700831 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800832 item.cellX = cellX;
833 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700834 item.spanX = spanX;
835 item.spanY = spanY;
836
837 // We store hotseat items in canonical form which is this orientation invariant position
838 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700839 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700840 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700841 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700842 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700843 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700844 }
Adam Cohend4844c32011-02-18 19:25:06 -0800845
Adam Cohend4844c32011-02-18 19:25:06 -0800846 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800847 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700848 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
849 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
850 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
851 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700852 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800853
Michael Jurka816474f2012-06-25 14:49:02 -0700854 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700855 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700856
857 /**
858 * Update an item to the database in a specified container.
859 */
860 static void updateItemInDatabase(Context context, final ItemInfo item) {
861 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100862 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700863 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
864 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800865 }
866
867 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400868 * Returns true if the shortcuts already exists in the database.
869 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800870 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400871 static boolean shortcutExists(Context context, String title, Intent intent) {
872 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700873 final Intent intentWithPkg, intentWithoutPkg;
874
875 if (intent.getComponent() != null) {
876 // If component is not null, an intent with null package will produce
877 // the same result and should also be a match.
878 if (intent.getPackage() != null) {
879 intentWithPkg = intent;
880 intentWithoutPkg = new Intent(intent).setPackage(null);
881 } else {
882 intentWithPkg = new Intent(intent).setPackage(
883 intent.getComponent().getPackageName());
884 intentWithoutPkg = intent;
885 }
886 } else {
887 intentWithPkg = intent;
888 intentWithoutPkg = intent;
889 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400890 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700891 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
892 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400893 boolean result = false;
894 try {
895 result = c.moveToFirst();
896 } finally {
897 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800898 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400899 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700900 }
901
Joe Onorato9c1289c2009-08-17 11:03:03 -0400902 /**
Sunny Goyal34942622014-08-29 17:20:55 -0700903 * Returns true if the promise shortcuts with the same package name exists on the workspace.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500904 */
Sunny Goyal34942622014-08-29 17:20:55 -0700905 static boolean appWasPromise(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500906 final ComponentName component = intent.getComponent();
907 if (component == null) {
908 return false;
909 }
Sunny Goyal34942622014-08-29 17:20:55 -0700910 return !getItemsByPackageName(component.getPackageName(), user).isEmpty();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500911 }
912
913 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700914 * Returns an ItemInfo array containing all the items in the LauncherModel.
915 * The ItemInfo.id is not set through this function.
916 */
917 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
918 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
919 final ContentResolver cr = context.getContentResolver();
920 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
921 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100922 LauncherSettings.Favorites.SCREEN,
923 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
924 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
925 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700926
927 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
928 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
929 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
930 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
931 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
932 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
933 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100934 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
935 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700936 try {
937 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700938 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700939 item.cellX = c.getInt(cellXIndex);
940 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700941 item.spanX = Math.max(1, c.getInt(spanXIndex));
942 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700943 item.container = c.getInt(containerIndex);
944 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100946 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100947 item.user = userManager.getUserForSerialNumber(serialNumber);
948 // Skip if user has been deleted.
949 if (item.user != null) {
950 items.add(item);
951 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700952 }
953 } catch (Exception e) {
954 items.clear();
955 } finally {
956 c.close();
957 }
958
959 return items;
960 }
961
962 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400963 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
964 */
965 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
966 final ContentResolver cr = context.getContentResolver();
967 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
968 "_id=? and (itemType=? or itemType=?)",
969 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700970 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700971
Joe Onorato9c1289c2009-08-17 11:03:03 -0400972 try {
973 if (c.moveToFirst()) {
974 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
975 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
976 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
977 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
978 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
979 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800980
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981 FolderInfo folderInfo = null;
982 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700983 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
984 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700986 }
987
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 folderInfo.title = c.getString(titleIndex);
989 folderInfo.id = id;
990 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700991 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700992 folderInfo.cellX = c.getInt(cellXIndex);
993 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994
995 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700996 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997 } finally {
998 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700999 }
1000
1001 return null;
1002 }
1003
Joe Onorato9c1289c2009-08-17 11:03:03 -04001004 /**
1005 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1006 * cellY fields of the item. Also assigns an ID to the item.
1007 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001008 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001009 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001010 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001011 item.cellX = cellX;
1012 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001013 // We store hotseat items in canonical form which is this orientation invariant position
1014 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001015 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001016 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001017 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001018 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001020 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001021
1022 final ContentValues values = new ContentValues();
1023 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001024 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001025
Michael Jurka414300a2013-08-27 15:42:35 +02001026 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001027 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001028 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001029
Jason Monk8e19cf22014-03-20 15:06:57 -04001030 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001031 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001032 public void run() {
1033 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1034 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001035
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001036 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001037 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001038 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 sBgItemsIdMap.put(item.id, item);
1040 switch (item.itemType) {
1041 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1042 sBgFolders.put(item.id, (FolderInfo) item);
1043 // Fall through
1044 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1045 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1046 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1047 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1048 sBgWorkspaceItems.add(item);
1049 } else {
1050 if (!sBgFolders.containsKey(item.container)) {
1051 // Adding an item to a folder that doesn't exist.
1052 String msg = "adding item: " + item + " to a folder that " +
1053 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001054 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001055 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001056 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 break;
1058 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1059 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1060 break;
1061 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001062 }
1063 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001064 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001065 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001066 }
1067
Joe Onorato9c1289c2009-08-17 11:03:03 -04001068 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001069 * Creates a new unique child id, for a given cell span across all layouts.
1070 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001071 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001072 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001073 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001075 }
1076
Sunny Goyal34942622014-08-29 17:20:55 -07001077 private static ArrayList<ItemInfo> getItemsByPackageName(
1078 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001079 ItemInfoFilter filter = new ItemInfoFilter() {
1080 @Override
1081 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1082 return cn.getPackageName().equals(pn) && info.user.equals(user);
1083 }
1084 };
Sunny Goyal34942622014-08-29 17:20:55 -07001085 return filterItemInfos(sBgItemsIdMap.values(), filter);
1086 }
1087
1088 /**
1089 * Removes all the items from the database corresponding to the specified package.
1090 */
1091 static void deletePackageFromDatabase(Context context, final String pn,
1092 final UserHandleCompat user) {
1093 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001094 }
1095
1096 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001097 * Removes the specified item from the database
1098 * @param context
1099 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001100 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001101 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001102 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1103 items.add(item);
1104 deleteItemsFromDatabase(context, items);
1105 }
1106
1107 /**
1108 * Removes the specified items from the database
1109 * @param context
1110 * @param item
1111 */
1112 static void deleteItemsFromDatabase(Context context, final ArrayList<ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001113 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001114
Michael Jurka83df1882011-08-31 20:59:26 -07001115 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001116 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001117 for (ItemInfo item : items) {
1118 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1119 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001120
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001121 // Lock on mBgLock *after* the db operation
1122 synchronized (sBgLock) {
1123 switch (item.itemType) {
1124 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1125 sBgFolders.remove(item.id);
1126 for (ItemInfo info: sBgItemsIdMap.values()) {
1127 if (info.container == item.id) {
1128 // We are deleting a folder which still contains items that
1129 // think they are contained by that folder.
1130 String msg = "deleting a folder (" + item + ") which still " +
1131 "contains items (" + info + ")";
1132 Log.e(TAG, msg);
1133 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001134 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001135 sBgWorkspaceItems.remove(item);
1136 break;
1137 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1138 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1139 sBgWorkspaceItems.remove(item);
1140 break;
1141 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1142 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1143 break;
1144 }
1145 sBgItemsIdMap.remove(item.id);
1146 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001147 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001148 }
1149 }
Michael Jurka83df1882011-08-31 20:59:26 -07001150 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001151 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001152 }
1153
1154 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 * Update the order of the workspace screens in the database. The array list contains
1156 * a list of screen ids in the order that they should appear.
1157 */
Winson Chungc9168342013-06-26 14:54:55 -07001158 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001159 // Log to disk
1160 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1161 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1162
Winson Chung64359a52013-07-08 17:17:08 -07001163 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001164 final ContentResolver cr = context.getContentResolver();
1165 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1166
1167 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001168 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 while (iter.hasNext()) {
1170 long id = iter.next();
1171 if (id < 0) {
1172 iter.remove();
1173 }
1174 }
1175
1176 Runnable r = new Runnable() {
1177 @Override
1178 public void run() {
Yura085c8532014-02-11 15:15:29 +00001179 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001180 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001181 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001182 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001183 for (int i = 0; i < count; i++) {
1184 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001185 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001186 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1187 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001188 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001189 }
Yura085c8532014-02-11 15:15:29 +00001190
1191 try {
1192 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1193 } catch (Exception ex) {
1194 throw new RuntimeException(ex);
1195 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001196
Winson Chungba9c37f2013-08-30 14:11:37 -07001197 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001198 sBgWorkspaceScreens.clear();
1199 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001200 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001201 }
1202 };
1203 runOnWorkerThread(r);
1204 }
1205
1206 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001207 * Remove the contents of the specified folder from the database
1208 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001209 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001210 final ContentResolver cr = context.getContentResolver();
1211
Michael Jurkac9d95c52011-08-29 14:03:34 -07001212 Runnable r = new Runnable() {
1213 public void run() {
1214 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001215 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001216 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001217 sBgItemsIdMap.remove(info.id);
1218 sBgFolders.remove(info.id);
1219 sBgDbIconCache.remove(info);
1220 sBgWorkspaceItems.remove(info);
1221 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001222
Michael Jurkac9d95c52011-08-29 14:03:34 -07001223 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1224 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001225 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001226 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001227 for (ItemInfo childInfo : info.contents) {
1228 sBgItemsIdMap.remove(childInfo.id);
1229 sBgDbIconCache.remove(childInfo);
1230 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001231 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001232 }
1233 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001234 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001235 }
1236
1237 /**
1238 * Set this as the current Launcher activity object for the loader.
1239 */
1240 public void initialize(Callbacks callbacks) {
1241 synchronized (mLock) {
1242 mCallbacks = new WeakReference<Callbacks>(callbacks);
1243 }
1244 }
1245
Kenny Guyed131872014-04-30 03:02:21 +01001246 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001247 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001248 int op = PackageUpdatedTask.OP_UPDATE;
1249 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1250 user));
1251 }
1252
1253 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001254 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001255 int op = PackageUpdatedTask.OP_REMOVE;
1256 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1257 user));
1258 }
1259
1260 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001261 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001262 int op = PackageUpdatedTask.OP_ADD;
1263 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1264 user));
1265 }
1266
1267 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001268 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001269 boolean replacing) {
1270 if (!replacing) {
1271 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1272 user));
1273 if (mAppsCanBeOnRemoveableStorage) {
1274 // Only rebind if we support removable storage. It catches the
1275 // case where
1276 // apps on the external sd card need to be reloaded
1277 startLoaderFromBackground();
1278 }
1279 } else {
1280 // If we are replacing then just update the packages in the list
1281 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1282 packageNames, user));
1283 }
1284 }
1285
1286 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001287 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001288 boolean replacing) {
1289 if (!replacing) {
1290 enqueuePackageUpdated(new PackageUpdatedTask(
1291 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1292 user));
1293 }
1294
1295 }
1296
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001297 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001298 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1299 * ACTION_PACKAGE_CHANGED.
1300 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001301 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001302 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001303 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001304
Joe Onorato36115782010-06-17 13:28:48 -04001305 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001306 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001307 // If we have changed locale we need to clear out the labels in all apps/workspace.
1308 forceReload();
1309 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1310 // Check if configuration change was an mcc/mnc change which would affect app resources
1311 // and we would need to clear out the labels in all apps/workspace. Same handling as
1312 // above for ACTION_LOCALE_CHANGED
1313 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001314 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001315 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001316 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001317 forceReload();
1318 }
1319 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001320 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001321 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1322 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001323 if (mCallbacks != null) {
1324 Callbacks callbacks = mCallbacks.get();
1325 if (callbacks != null) {
1326 callbacks.bindSearchablesChanged();
1327 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001328 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001329 }
1330 }
1331
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001332 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001333 resetLoadedState(true, true);
1334
Reena Lee93f824a2011-09-23 17:20:28 -07001335 // Do this here because if the launcher activity is running it will be restarted.
1336 // If it's not running startLoaderFromBackground will merely tell it that it needs
1337 // to reload.
1338 startLoaderFromBackground();
1339 }
1340
Winson Chungf0c6ae02012-03-21 16:10:31 -07001341 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1342 synchronized (mLock) {
1343 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1344 // mWorkspaceLoaded to true later
1345 stopLoaderLocked();
1346 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1347 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1348 }
1349 }
1350
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001351 /**
1352 * When the launcher is in the background, it's possible for it to miss paired
1353 * configuration changes. So whenever we trigger the loader from the background
1354 * tell the launcher that it needs to re-run the loader when it comes back instead
1355 * of doing it now.
1356 */
1357 public void startLoaderFromBackground() {
1358 boolean runLoader = false;
1359 if (mCallbacks != null) {
1360 Callbacks callbacks = mCallbacks.get();
1361 if (callbacks != null) {
1362 // Only actually run the loader if they're not paused.
1363 if (!callbacks.setLoadOnResume()) {
1364 runLoader = true;
1365 }
1366 }
1367 }
1368 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001369 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001370 }
Joe Onorato36115782010-06-17 13:28:48 -04001371 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001372
Reena Lee93f824a2011-09-23 17:20:28 -07001373 // If there is already a loader task running, tell it to stop.
1374 // returns true if isLaunching() was true on the old task
1375 private boolean stopLoaderLocked() {
1376 boolean isLaunching = false;
1377 LoaderTask oldTask = mLoaderTask;
1378 if (oldTask != null) {
1379 if (oldTask.isLaunching()) {
1380 isLaunching = true;
1381 }
1382 oldTask.stopLocked();
1383 }
1384 return isLaunching;
1385 }
1386
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001388 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1389 }
1390
1391 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001392 synchronized (mLock) {
1393 if (DEBUG_LOADERS) {
1394 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1395 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001396
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001397 // Clear any deferred bind-runnables from the synchronized load process
1398 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001399 synchronized (mDeferredBindRunnables) {
1400 mDeferredBindRunnables.clear();
1401 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402
Joe Onorato36115782010-06-17 13:28:48 -04001403 // Don't bother to start the thread if we know it's not going to do anything
1404 if (mCallbacks != null && mCallbacks.get() != null) {
1405 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001406 // also, don't downgrade isLaunching if we're already running
1407 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001408 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001409 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1410 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1412 } else {
1413 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1414 sWorker.post(mLoaderTask);
1415 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001416 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001417 }
1418 }
1419
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001420 void bindRemainingSynchronousPages() {
1421 // Post the remaining side pages to be loaded
1422 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001423 Runnable[] deferredBindRunnables = null;
1424 synchronized (mDeferredBindRunnables) {
1425 deferredBindRunnables = mDeferredBindRunnables.toArray(
1426 new Runnable[mDeferredBindRunnables.size()]);
1427 mDeferredBindRunnables.clear();
1428 }
1429 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001430 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001431 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001432 }
1433 }
1434
Joe Onorato36115782010-06-17 13:28:48 -04001435 public void stopLoader() {
1436 synchronized (mLock) {
1437 if (mLoaderTask != null) {
1438 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001439 }
1440 }
Joe Onorato36115782010-06-17 13:28:48 -04001441 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001442
Winson Chung76828c82013-08-19 15:43:29 -07001443 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1444 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1445 final ContentResolver contentResolver = context.getContentResolver();
1446 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1447 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1448 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1449
1450 try {
1451 final int idIndex = sc.getColumnIndexOrThrow(
1452 LauncherSettings.WorkspaceScreens._ID);
1453 final int rankIndex = sc.getColumnIndexOrThrow(
1454 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1455 while (sc.moveToNext()) {
1456 try {
1457 long screenId = sc.getLong(idIndex);
1458 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001459 orderedScreens.put(rank, screenId);
1460 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001461 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001462 }
1463 }
1464 } finally {
1465 sc.close();
1466 }
Winson Chunga90303b2013-11-15 13:05:06 -08001467
1468 // Log to disk
1469 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1470 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1471 for (Integer i : orderedScreens.keySet()) {
1472 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1473 }
1474 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1475 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001476 return orderedScreens;
1477 }
1478
Michael Jurkac57b7a82011-08-09 22:02:20 -07001479 public boolean isAllAppsLoaded() {
1480 return mAllAppsLoaded;
1481 }
1482
Winson Chung36a62fe2012-05-06 18:04:42 -07001483 boolean isLoadingWorkspace() {
1484 synchronized (mLock) {
1485 if (mLoaderTask != null) {
1486 return mLoaderTask.isLoadingWorkspace();
1487 }
1488 }
1489 return false;
1490 }
1491
Joe Onorato36115782010-06-17 13:28:48 -04001492 /**
1493 * Runnable for the thread that loads the contents of the launcher:
1494 * - workspace icons
1495 * - widgets
1496 * - all apps icons
1497 */
1498 private class LoaderTask implements Runnable {
1499 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001500 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001501 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001502 private boolean mStopped;
1503 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001504 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001505
Winson Chungc3eecff2011-07-11 17:44:15 -07001506 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001507
Dan Sandlerd5024042014-01-09 15:01:33 -05001508 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001509 mContext = context;
1510 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001511 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001512 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001513 }
1514
Joe Onorato36115782010-06-17 13:28:48 -04001515 boolean isLaunching() {
1516 return mIsLaunching;
1517 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001518
Winson Chung36a62fe2012-05-06 18:04:42 -07001519 boolean isLoadingWorkspace() {
1520 return mIsLoadingAndBindingWorkspace;
1521 }
1522
Winson Chungc763c4e2013-07-19 13:49:06 -07001523 /** Returns whether this is an upgrade path */
1524 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001525 mIsLoadingAndBindingWorkspace = true;
1526
Joe Onorato36115782010-06-17 13:28:48 -04001527 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001528 if (DEBUG_LOADERS) {
1529 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001530 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001531
Winson Chungc763c4e2013-07-19 13:49:06 -07001532 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001533 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001534 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001535 synchronized (LoaderTask.this) {
1536 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001537 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001538 }
1539 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001540 }
1541 }
1542
Joe Onorato36115782010-06-17 13:28:48 -04001543 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001544 bindWorkspace(-1, isUpgradePath);
1545 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001546 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001547
Joe Onorato36115782010-06-17 13:28:48 -04001548 private void waitForIdle() {
1549 // Wait until the either we're stopped or the other threads are done.
1550 // This way we don't start loading all apps until the workspace has settled
1551 // down.
1552 synchronized (LoaderTask.this) {
1553 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001554
Joe Onorato36115782010-06-17 13:28:48 -04001555 mHandler.postIdle(new Runnable() {
1556 public void run() {
1557 synchronized (LoaderTask.this) {
1558 mLoadAndBindStepFinished = true;
1559 if (DEBUG_LOADERS) {
1560 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001561 }
Joe Onorato36115782010-06-17 13:28:48 -04001562 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001563 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001564 }
Joe Onorato36115782010-06-17 13:28:48 -04001565 });
1566
Michael Jurkac7700af2013-05-14 20:17:58 +02001567 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001568 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001569 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1570 // wait no longer than 1sec at a time
1571 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001572 } catch (InterruptedException ex) {
1573 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001574 }
1575 }
Joe Onorato36115782010-06-17 13:28:48 -04001576 if (DEBUG_LOADERS) {
1577 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001578 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001579 + "ms for previous step to finish binding");
1580 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001581 }
Joe Onorato36115782010-06-17 13:28:48 -04001582 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001583
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001584 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001585 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 // Ensure that we have a valid page index to load synchronously
1587 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1588 "valid page index");
1589 }
1590 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1591 // Ensure that we don't try and bind a specified page when the pages have not been
1592 // loaded already (we should load everything asynchronously in that case)
1593 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1594 }
1595 synchronized (mLock) {
1596 if (mIsLoaderTaskRunning) {
1597 // Ensure that we are never running the background loading at this point since
1598 // we also touch the background collections
1599 throw new RuntimeException("Error! Background loading is already running");
1600 }
1601 }
1602
1603 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1604 // data structures, we can't allow any other thread to touch that data, but because
1605 // this call is synchronous, we can get away with not locking).
1606
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001607 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001608 // operations from the previous activity. We need to ensure that all queued operations
1609 // are executed before any synchronous binding work is done.
1610 mHandler.flush();
1611
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001612 // Divide the set of loaded items into those that we are binding synchronously, and
1613 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001614 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001615 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1616 // arise from that.
1617 onlyBindAllApps();
1618 }
1619
Joe Onorato36115782010-06-17 13:28:48 -04001620 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001621 boolean isUpgrade = false;
1622
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001623 synchronized (mLock) {
1624 mIsLoaderTaskRunning = true;
1625 }
Joe Onorato36115782010-06-17 13:28:48 -04001626 // Optimize for end-user experience: if the Launcher is up and // running with the
1627 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1628 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001629 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001630 // Elevate priority when Home launches for the first time to avoid
1631 // starving at boot time. Staring at a blank home is not cool.
1632 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001633 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1634 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001635 android.os.Process.setThreadPriority(mIsLaunching
1636 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1637 }
Winson Chung64359a52013-07-08 17:17:08 -07001638 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001639 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001640
Joe Onorato36115782010-06-17 13:28:48 -04001641 if (mStopped) {
1642 break keep_running;
1643 }
1644
1645 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1646 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001647 synchronized (mLock) {
1648 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001649 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001650 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651 }
1652 }
Joe Onorato36115782010-06-17 13:28:48 -04001653 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001654
1655 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001656 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1657 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001658
1659 // Restore the default thread priority after we are done loading items
1660 synchronized (mLock) {
1661 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001664
Winson Chungaac01e12011-08-17 10:37:13 -07001665 // Update the saved icons if necessary
1666 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001667 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001668 for (Object key : sBgDbIconCache.keySet()) {
1669 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1670 }
1671 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001672 }
Winson Chungaac01e12011-08-17 10:37:13 -07001673
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001674 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001675 // Ensure that all the applications that are in the system are
1676 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001677 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001678 verifyApplications();
1679 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001680 }
1681
Joe Onorato36115782010-06-17 13:28:48 -04001682 // Clear out this reference, otherwise we end up holding it until all of the
1683 // callback runnables are done.
1684 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001685
Joe Onorato36115782010-06-17 13:28:48 -04001686 synchronized (mLock) {
1687 // If we are still the last one to be scheduled, remove ourselves.
1688 if (mLoaderTask == this) {
1689 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001690 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001691 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001692 }
Joe Onorato36115782010-06-17 13:28:48 -04001693 }
1694
1695 public void stopLocked() {
1696 synchronized (LoaderTask.this) {
1697 mStopped = true;
1698 this.notify();
1699 }
1700 }
1701
1702 /**
1703 * Gets the callbacks object. If we've been stopped, or if the launcher object
1704 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1705 * object that was around when the deferred message was scheduled, and if there's
1706 * a new Callbacks object around then also return null. This will save us from
1707 * calling onto it with data that will be ignored.
1708 */
1709 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1710 synchronized (mLock) {
1711 if (mStopped) {
1712 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001713 }
Joe Onorato36115782010-06-17 13:28:48 -04001714
1715 if (mCallbacks == null) {
1716 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001717 }
Joe Onorato36115782010-06-17 13:28:48 -04001718
1719 final Callbacks callbacks = mCallbacks.get();
1720 if (callbacks != oldCallbacks) {
1721 return null;
1722 }
1723 if (callbacks == null) {
1724 Log.w(TAG, "no mCallbacks");
1725 return null;
1726 }
1727
1728 return callbacks;
1729 }
1730 }
1731
Winson Chungc763c4e2013-07-19 13:49:06 -07001732 private void verifyApplications() {
1733 final Context context = mApp.getContext();
1734
1735 // Cross reference all the applications in our apps list with items in the workspace
1736 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001737 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001738 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001739 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001740 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001741 if (tmpInfos.isEmpty()) {
1742 // We are missing an application icon, so add this to the workspace
1743 added.add(app);
1744 // This is a rare event, so lets log it
1745 Log.e(TAG, "Missing Application on load: " + app);
1746 }
1747 }
1748 }
1749 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001750 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001751 }
1752 }
1753
Joe Onorato36115782010-06-17 13:28:48 -04001754 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001755 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001756 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001757 LauncherAppState app = LauncherAppState.getInstance();
1758 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001759 final int countX = (int) grid.numColumns;
1760 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001761
Adam Cohendcd297f2013-06-18 13:13:40 -07001762 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001763 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001764 // Return early if we detect that an item is under the hotseat button
1765 if (mCallbacks == null ||
1766 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001767 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001768 Log.e(TAG, "Error loading shortcut into hotseat " + item
1769 + " into position (" + item.screenId + ":" + item.cellX + ","
1770 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001771 return false;
1772 }
1773
Dan Sandler295ae182013-12-10 16:05:47 -05001774 final ItemInfo[][] hotseatItems =
1775 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1776
Adam Cohenae4409d2013-11-26 10:34:59 -08001777 if (item.screenId >= grid.numHotseatIcons) {
1778 Log.e(TAG, "Error loading shortcut " + item
1779 + " into hotseat position " + item.screenId
1780 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1781 + ")");
1782 return false;
1783 }
1784
Dan Sandler295ae182013-12-10 16:05:47 -05001785 if (hotseatItems != null) {
1786 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001787 Log.e(TAG, "Error loading shortcut into hotseat " + item
1788 + " into position (" + item.screenId + ":" + item.cellX + ","
1789 + item.cellY + ") occupied by "
1790 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1791 [(int) item.screenId][0]);
1792 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001793 } else {
1794 hotseatItems[(int) item.screenId][0] = item;
1795 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001796 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001797 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001798 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 items[(int) item.screenId][0] = item;
1800 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001801 return true;
1802 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001803 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1804 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001805 return true;
1806 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001807
Adam Cohendcd297f2013-06-18 13:13:40 -07001808 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001809 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 occupied.put(item.screenId, items);
1811 }
1812
Dan Sandler295ae182013-12-10 16:05:47 -05001813 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001814 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1815 item.cellX < 0 || item.cellY < 0 ||
1816 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1817 Log.e(TAG, "Error loading shortcut " + item
1818 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1819 + item.cellX + "," + item.cellY
1820 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1821 return false;
1822 }
1823
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001824 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001825 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1826 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001827 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001828 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001829 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001830 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001831 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001832 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001833 return false;
1834 }
1835 }
1836 }
1837 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1838 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001839 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001840 }
1841 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001842
Joe Onorato36115782010-06-17 13:28:48 -04001843 return true;
1844 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001845
Winson Chungba9c37f2013-08-30 14:11:37 -07001846 /** Clears all the sBg data structures */
1847 private void clearSBgDataStructures() {
1848 synchronized (sBgLock) {
1849 sBgWorkspaceItems.clear();
1850 sBgAppWidgets.clear();
1851 sBgFolders.clear();
1852 sBgItemsIdMap.clear();
1853 sBgDbIconCache.clear();
1854 sBgWorkspaceScreens.clear();
1855 }
1856 }
1857
Dan Sandlerd5024042014-01-09 15:01:33 -05001858 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001859 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001860 // Log to disk
1861 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1862
Joe Onorato36115782010-06-17 13:28:48 -04001863 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001864
Joe Onorato36115782010-06-17 13:28:48 -04001865 final Context context = mContext;
1866 final ContentResolver contentResolver = context.getContentResolver();
1867 final PackageManager manager = context.getPackageManager();
1868 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1869 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001870 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1871 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001872 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001873
Winson Chung892c74d2013-08-22 16:15:50 -07001874 LauncherAppState app = LauncherAppState.getInstance();
1875 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1876 int countX = (int) grid.numColumns;
1877 int countY = (int) grid.numRows;
1878
Dan Sandlerd5024042014-01-09 15:01:33 -05001879 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1880 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1881 LauncherAppState.getLauncherProvider().deleteDatabase();
1882 }
1883
1884 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1885 // append the user's Launcher2 shortcuts
1886 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1887 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1888 } else {
1889 // Make sure the default workspace is loaded
1890 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001891 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001892 }
Adam Cohene25af792013-06-06 23:08:25 -07001893
Adam Cohen71483f42014-05-15 14:04:01 -07001894 // This code path is for our old migration code and should no longer be exercised
1895 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001896
Winson Chung9f9f00b2013-11-15 13:27:00 -08001897 // Log to disk
1898 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001899
Winson Chung2abf94d2012-07-18 18:16:38 -07001900 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001901 clearSBgDataStructures();
Sunny Goyal34942622014-08-29 17:20:55 -07001902 PackageInstallerCompat.getInstance(mContext).updateActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001903
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001904 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001905 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001906 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001907 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001908 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001909
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001910 // +1 for the hotseat (it can be larger than the workspace)
1911 // Load workspace in reverse order to ensure that latest items are loaded first (and
1912 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001913 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001914
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 try {
1916 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1917 final int intentIndex = c.getColumnIndexOrThrow
1918 (LauncherSettings.Favorites.INTENT);
1919 final int titleIndex = c.getColumnIndexOrThrow
1920 (LauncherSettings.Favorites.TITLE);
1921 final int iconTypeIndex = c.getColumnIndexOrThrow(
1922 LauncherSettings.Favorites.ICON_TYPE);
1923 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1924 final int iconPackageIndex = c.getColumnIndexOrThrow(
1925 LauncherSettings.Favorites.ICON_PACKAGE);
1926 final int iconResourceIndex = c.getColumnIndexOrThrow(
1927 LauncherSettings.Favorites.ICON_RESOURCE);
1928 final int containerIndex = c.getColumnIndexOrThrow(
1929 LauncherSettings.Favorites.CONTAINER);
1930 final int itemTypeIndex = c.getColumnIndexOrThrow(
1931 LauncherSettings.Favorites.ITEM_TYPE);
1932 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1933 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001934 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1935 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001936 final int screenIndex = c.getColumnIndexOrThrow(
1937 LauncherSettings.Favorites.SCREEN);
1938 final int cellXIndex = c.getColumnIndexOrThrow
1939 (LauncherSettings.Favorites.CELLX);
1940 final int cellYIndex = c.getColumnIndexOrThrow
1941 (LauncherSettings.Favorites.CELLY);
1942 final int spanXIndex = c.getColumnIndexOrThrow
1943 (LauncherSettings.Favorites.SPANX);
1944 final int spanYIndex = c.getColumnIndexOrThrow(
1945 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001946 final int restoredIndex = c.getColumnIndexOrThrow(
1947 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001948 final int profileIdIndex = c.getColumnIndexOrThrow(
1949 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001950 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1951 //final int displayModeIndex = c.getColumnIndexOrThrow(
1952 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001953
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001954 ShortcutInfo info;
1955 String intentDescription;
1956 LauncherAppWidgetInfo appWidgetInfo;
1957 int container;
1958 long id;
1959 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001960 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001961
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001962 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001963 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 try {
1965 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001966 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001967 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001968
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001969 switch (itemType) {
1970 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1971 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001972 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001973 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001974 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001975 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001976 int promiseType = c.getInt(restoredIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001977 if (user == null) {
1978 // User has been deleted remove the item.
1979 itemsToRemove.add(id);
1980 continue;
1981 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001982 try {
1983 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001984 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001985 if (cn != null && cn.getPackageName() != null) {
1986 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1987 cn.getPackageName(), user);
1988 boolean validComponent = validPkg &&
1989 launcherApps.isActivityEnabledForProfile(cn, user);
1990
1991 if (validComponent) {
1992 if (restored) {
1993 // no special handling necessary for this item
1994 restoredRows.add(id);
1995 restored = false;
1996 }
1997 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001998 intent = null;
1999 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2000 // We allow auto install apps to have their intent
2001 // updated after an install.
2002 intent = manager.getLaunchIntentForPackage(
2003 cn.getPackageName());
2004 if (intent != null) {
2005 ContentValues values = new ContentValues();
2006 values.put(LauncherSettings.Favorites.INTENT,
2007 intent.toUri(0));
2008 String where = BaseColumns._ID + "= ?";
2009 String[] args = {Long.toString(id)};
2010 contentResolver.update(contentUri, values, where, args);
2011 }
2012 }
2013
2014 if (intent == null) {
2015 // The app is installed but the component is no
2016 // longer available.
2017 Launcher.addDumpLog(TAG,
2018 "Invalid component removed: " + cn, true);
2019 itemsToRemove.add(id);
2020 continue;
2021 } else {
2022 // no special handling necessary for this item
2023 restoredRows.add(id);
2024 restored = false;
2025 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002026 } else if (restored) {
2027 // Package is not yet available but might be
2028 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002029 Launcher.addDumpLog(TAG,
2030 "package not yet restored: " + cn, true);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002031 } else if (isSdCardReady) {
2032 // Do not wait for external media load anymore.
2033 // Log the invalid package, and remove it
2034 Launcher.addDumpLog(TAG,
2035 "Invalid package removed: " + cn, true);
2036 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002037 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002038 } else {
2039 // SdCard is not ready yet. Package might get available,
2040 // once it is ready.
2041 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2042 + " (check again later)", true);
2043 HashSet<String> pkgs = sPendingPackages.get(user);
2044 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002045 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002046 sPendingPackages.put(user, pkgs);
2047 }
2048 pkgs.add(cn.getPackageName());
2049 allowMissingTarget = true;
2050 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002051 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002052 } else if (cn == null) {
2053 // For shortcuts with no component, keep them as they are
2054 restoredRows.add(id);
2055 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002056 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002058 Launcher.addDumpLog(TAG,
2059 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002060 continue;
2061 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002062
Chris Wrenf4d08112014-01-16 18:13:56 -05002063 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002064 if (user.equals(UserHandleCompat.myUserHandle())) {
2065 Launcher.addDumpLog(TAG,
2066 "constructing info for partially restored package",
2067 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002068 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002069 intent = getRestoredItemIntent(c, context, intent);
2070 } else {
2071 // Don't restore items for other profiles.
2072 itemsToRemove.add(id);
2073 continue;
2074 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002075 } else if (itemType ==
2076 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002077 info = getShortcutInfo(manager, intent, user, context, c,
2078 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 } else {
2080 info = getShortcutInfo(c, context, iconTypeIndex,
2081 iconPackageIndex, iconResourceIndex, iconIndex,
2082 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002083
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 // App shortcuts that used to be automatically added to Launcher
2085 // didn't always have the correct intent flags set, so do that
2086 // here
2087 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002088 intent.getCategories() != null &&
2089 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002090 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 intent.addFlags(
2092 Intent.FLAG_ACTIVITY_NEW_TASK |
2093 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2094 }
Michael Jurka96879562012-03-22 05:54:33 -07002095 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002096
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002097 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002098 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002100 container = c.getInt(containerIndex);
2101 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002102 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002103 info.cellX = c.getInt(cellXIndex);
2104 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002105 info.spanX = 1;
2106 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002107 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002108 info.isDisabled = isSafeMode
2109 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002110
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002112 deleteOnInvalidPlacement.set(false);
2113 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2114 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002115 itemsToRemove.add(id);
2116 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002117 break;
2118 }
2119
2120 switch (container) {
2121 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2122 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2123 sBgWorkspaceItems.add(info);
2124 break;
2125 default:
2126 // Item is in a user folder
2127 FolderInfo folderInfo =
2128 findOrMakeFolder(sBgFolders, container);
2129 folderInfo.add(info);
2130 break;
2131 }
2132 sBgItemsIdMap.put(info.id, info);
2133
2134 // now that we've loaded everthing re-save it with the
2135 // icon in case it disappears somehow.
2136 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002137 } else {
2138 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002139 }
2140 break;
2141
2142 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2143 id = c.getLong(idIndex);
2144 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2145
2146 folderInfo.title = c.getString(titleIndex);
2147 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002148 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002150 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 folderInfo.cellX = c.getInt(cellXIndex);
2152 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002153 folderInfo.spanX = 1;
2154 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002155
Daniel Sandler8802e962010-05-26 16:28:16 -04002156 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002157 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002158 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002159 deleteOnInvalidPlacement)) {
2160 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002161 itemsToRemove.add(id);
2162 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002163 break;
2164 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002165
Joe Onorato9c1289c2009-08-17 11:03:03 -04002166 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002167 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2168 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2169 sBgWorkspaceItems.add(folderInfo);
2170 break;
Joe Onorato36115782010-06-17 13:28:48 -04002171 }
Joe Onorato17a89222011-02-08 17:26:11 -08002172
Chris Wrenf4d08112014-01-16 18:13:56 -05002173 if (restored) {
2174 // no special handling required for restored folders
2175 restoredRows.add(id);
2176 }
2177
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002178 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2179 sBgFolders.put(folderInfo.id, folderInfo);
2180 break;
2181
2182 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2183 // Read all Launcher-specific widget details
2184 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002185 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002186 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002187 final ComponentName component =
2188 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002189
Sunny Goyal651077b2014-06-30 14:15:31 -07002190 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002191 final boolean isIdValid = (restoreStatus &
2192 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002193
Sunny Goyalff572272014-07-23 13:58:07 -07002194 final boolean wasProviderReady = (restoreStatus &
2195 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002196
Sunny Goyalff572272014-07-23 13:58:07 -07002197 final AppWidgetProviderInfo provider = isIdValid
2198 ? widgets.getAppWidgetInfo(appWidgetId)
2199 : findAppWidgetProviderInfoWithComponent(context, component);
2200
2201 final boolean isProviderReady = isValidProvider(provider);
2202 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002203 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002204 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002205 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002206 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002207 itemsToRemove.add(id);
2208 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002209 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002210 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2211 provider.provider);
2212 int[] minSpan =
2213 Launcher.getMinSpanForWidget(context, provider);
2214 appWidgetInfo.minSpanX = minSpan[0];
2215 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002216
2217 int status = restoreStatus;
2218 if (!wasProviderReady) {
2219 // If provider was not previously ready, update the
2220 // status and UI flag.
2221
2222 // Id would be valid only if the widget restore broadcast was received.
2223 if (isIdValid) {
2224 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2225 } else {
2226 status &= ~LauncherAppWidgetInfo
2227 .FLAG_PROVIDER_NOT_READY;
2228 }
2229 }
2230 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002231 } else {
2232 Log.v(TAG, "Widget restore pending id=" + id
2233 + " appWidgetId=" + appWidgetId
2234 + " status =" + restoreStatus);
2235 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002236 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002237 appWidgetInfo.restoreStatus = restoreStatus;
2238 }
Sunny Goyalff572272014-07-23 13:58:07 -07002239
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002241 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002242 appWidgetInfo.cellX = c.getInt(cellXIndex);
2243 appWidgetInfo.cellY = c.getInt(cellYIndex);
2244 appWidgetInfo.spanX = c.getInt(spanXIndex);
2245 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002246
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247 container = c.getInt(containerIndex);
2248 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2249 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2250 Log.e(TAG, "Widget found where container != " +
2251 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2252 continue;
2253 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002254
Adam Cohene25af792013-06-06 23:08:25 -07002255 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002256 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002257 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002258 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002259 deleteOnInvalidPlacement)) {
2260 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002261 itemsToRemove.add(id);
2262 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 break;
2264 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002265
Sunny Goyalff572272014-07-23 13:58:07 -07002266 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002267 String providerName = provider.provider.flattenToString();
Sunny Goyalff572272014-07-23 13:58:07 -07002268 if (!providerName.equals(savedProvider) ||
2269 (appWidgetInfo.restoreStatus != restoreStatus)) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002270 ContentValues values = new ContentValues();
2271 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2272 providerName);
2273 values.put(LauncherSettings.Favorites.RESTORED,
Sunny Goyalff572272014-07-23 13:58:07 -07002274 appWidgetInfo.restoreStatus);
Sunny Goyal651077b2014-06-30 14:15:31 -07002275 String where = BaseColumns._ID + "= ?";
2276 String[] args = {Long.toString(id)};
2277 contentResolver.update(contentUri, values, where, args);
2278 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002279 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2281 sBgAppWidgets.add(appWidgetInfo);
2282 }
Joe Onorato36115782010-06-17 13:28:48 -04002283 break;
2284 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002286 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 }
2289 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002290 if (c != null) {
2291 c.close();
2292 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 }
2294
Winson Chungba9c37f2013-08-30 14:11:37 -07002295 // Break early if we've stopped loading
2296 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002297 clearSBgDataStructures();
2298 return false;
2299 }
2300
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 if (itemsToRemove.size() > 0) {
2302 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002303 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002304 // Remove dead items
2305 for (long id : itemsToRemove) {
2306 if (DEBUG_LOADERS) {
2307 Log.d(TAG, "Removed id = " + id);
2308 }
2309 // Don't notify content observers
2310 try {
2311 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2312 null, null);
2313 } catch (RemoteException e) {
2314 Log.w(TAG, "Could not remove id = " + id);
2315 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002316 }
2317 }
2318
Chris Wrenf4d08112014-01-16 18:13:56 -05002319 if (restoredRows.size() > 0) {
2320 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2321 LauncherSettings.Favorites.CONTENT_URI);
2322 // Update restored items that no longer require special handling
2323 try {
2324 StringBuilder selectionBuilder = new StringBuilder();
2325 selectionBuilder.append(LauncherSettings.Favorites._ID);
2326 selectionBuilder.append(" IN (");
2327 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2328 selectionBuilder.append(")");
2329 ContentValues values = new ContentValues();
2330 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002331 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002332 values, selectionBuilder.toString(), null);
2333 } catch (RemoteException e) {
2334 Log.w(TAG, "Could not update restored rows");
2335 }
2336 }
2337
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002338 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2339 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002340 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002341 null, sWorker);
2342 }
2343
Winson Chungc763c4e2013-07-19 13:49:06 -07002344 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002345 long maxScreenId = 0;
2346 // If we're importing we use the old screen order.
2347 for (ItemInfo item: sBgItemsIdMap.values()) {
2348 long screenId = item.screenId;
2349 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2350 !sBgWorkspaceScreens.contains(screenId)) {
2351 sBgWorkspaceScreens.add(screenId);
2352 if (screenId > maxScreenId) {
2353 maxScreenId = screenId;
2354 }
2355 }
2356 }
2357 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002358 // Log to disk
2359 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2360 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2361 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002362
Michael Jurka414300a2013-08-27 15:42:35 +02002363 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002364 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002365
2366 // Update the max item id after we load an old db
2367 long maxItemId = 0;
2368 // If we're importing we use the old screen order.
2369 for (ItemInfo item: sBgItemsIdMap.values()) {
2370 maxItemId = Math.max(maxItemId, item.id);
2371 }
Michael Jurka414300a2013-08-27 15:42:35 +02002372 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002373 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002374 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2375 for (Integer i : orderedScreens.keySet()) {
2376 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002378 // Log to disk
2379 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2380 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002381
2382 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002383 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002384 for (ItemInfo item: sBgItemsIdMap.values()) {
2385 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002386 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2387 unusedScreens.contains(screenId)) {
2388 unusedScreens.remove(screenId);
2389 }
2390 }
2391
2392 // If there are any empty screens remove them, and update.
2393 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002394 // Log to disk
2395 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2396 TextUtils.join(", ", unusedScreens), true);
2397
Winson Chung933bae62013-08-29 11:42:30 -07002398 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002399 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2400 }
2401 }
2402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 if (DEBUG_LOADERS) {
2404 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2405 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002406 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002407 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002408 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002409
Daniel Sandler566da102013-06-25 23:43:45 -04002410 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002411 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002412 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002413 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002414 line += " | ";
2415 }
Winson Chung892c74d2013-08-22 16:15:50 -07002416 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002417 ItemInfo[][] screen = occupied.get(screenId);
2418 if (x < screen.length && y < screen[x].length) {
2419 line += (screen[x][y] != null) ? "#" : ".";
2420 } else {
2421 line += "!";
2422 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002423 }
Joe Onorato36115782010-06-17 13:28:48 -04002424 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002425 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002426 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002427 }
Joe Onorato36115782010-06-17 13:28:48 -04002428 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002429 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002430 }
2431
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432 /** Filters the set of items who are directly or indirectly (via another container) on the
2433 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002434 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 ArrayList<ItemInfo> allWorkspaceItems,
2436 ArrayList<ItemInfo> currentScreenItems,
2437 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002438 // Purge any null ItemInfos
2439 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2440 while (iter.hasNext()) {
2441 ItemInfo i = iter.next();
2442 if (i == null) {
2443 iter.remove();
2444 }
2445 }
2446
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002447 // Order the set of items by their containers first, this allows use to walk through the
2448 // list sequentially, build up a list of containers that are in the specified screen,
2449 // as well as all items in those containers.
2450 Set<Long> itemsOnScreen = new HashSet<Long>();
2451 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2452 @Override
2453 public int compare(ItemInfo lhs, ItemInfo rhs) {
2454 return (int) (lhs.container - rhs.container);
2455 }
2456 });
2457 for (ItemInfo info : allWorkspaceItems) {
2458 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002459 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002460 currentScreenItems.add(info);
2461 itemsOnScreen.add(info.id);
2462 } else {
2463 otherScreenItems.add(info);
2464 }
2465 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2466 currentScreenItems.add(info);
2467 itemsOnScreen.add(info.id);
2468 } else {
2469 if (itemsOnScreen.contains(info.container)) {
2470 currentScreenItems.add(info);
2471 itemsOnScreen.add(info.id);
2472 } else {
2473 otherScreenItems.add(info);
2474 }
2475 }
2476 }
2477 }
2478
2479 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002480 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002481 ArrayList<LauncherAppWidgetInfo> appWidgets,
2482 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2483 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484
2485 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002486 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002487 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002488 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 currentScreenWidgets.add(widget);
2490 } else {
2491 otherScreenWidgets.add(widget);
2492 }
2493 }
2494 }
2495
2496 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002497 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002498 HashMap<Long, ItemInfo> itemsIdMap,
2499 HashMap<Long, FolderInfo> folders,
2500 HashMap<Long, FolderInfo> currentScreenFolders,
2501 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002502
2503 for (long id : folders.keySet()) {
2504 ItemInfo info = itemsIdMap.get(id);
2505 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002506 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002508 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002509 currentScreenFolders.put(id, folder);
2510 } else {
2511 otherScreenFolders.put(id, folder);
2512 }
2513 }
2514 }
2515
2516 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2517 * right) */
2518 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002519 final LauncherAppState app = LauncherAppState.getInstance();
2520 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 // XXX: review this
2522 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002523 @Override
2524 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002525 int cellCountX = (int) grid.numColumns;
2526 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002527 int screenOffset = cellCountX * cellCountY;
2528 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002529 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002530 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002531 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002532 rhs.cellY * cellCountX + rhs.cellX);
2533 return (int) (lr - rr);
2534 }
2535 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002537
Adam Cohendcd297f2013-06-18 13:13:40 -07002538 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2539 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002540 final Runnable r = new Runnable() {
2541 @Override
2542 public void run() {
2543 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2544 if (callbacks != null) {
2545 callbacks.bindScreens(orderedScreens);
2546 }
2547 }
2548 };
2549 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2550 }
2551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2553 final ArrayList<ItemInfo> workspaceItems,
2554 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2555 final HashMap<Long, FolderInfo> folders,
2556 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002557
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 final boolean postOnMainThread = (deferredBindRunnables != null);
2559
2560 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002561 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002563 final int start = i;
2564 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002565 final Runnable r = new Runnable() {
2566 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002567 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002568 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002569 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002570 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2571 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002572 }
2573 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002574 };
2575 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002576 synchronized (deferredBindRunnables) {
2577 deferredBindRunnables.add(r);
2578 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002579 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002580 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002581 }
Joe Onorato36115782010-06-17 13:28:48 -04002582 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583
2584 // Bind the folders
2585 if (!folders.isEmpty()) {
2586 final Runnable r = new Runnable() {
2587 public void run() {
2588 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2589 if (callbacks != null) {
2590 callbacks.bindFolders(folders);
2591 }
2592 }
2593 };
2594 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002595 synchronized (deferredBindRunnables) {
2596 deferredBindRunnables.add(r);
2597 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002599 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002600 }
2601 }
2602
2603 // Bind the widgets, one at a time
2604 N = appWidgets.size();
2605 for (int i = 0; i < N; i++) {
2606 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2607 final Runnable r = new Runnable() {
2608 public void run() {
2609 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2610 if (callbacks != null) {
2611 callbacks.bindAppWidget(widget);
2612 }
2613 }
2614 };
2615 if (postOnMainThread) {
2616 deferredBindRunnables.add(r);
2617 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002618 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002619 }
2620 }
2621 }
2622
2623 /**
2624 * Binds all loaded data to actual views on the main thread.
2625 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002626 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 final long t = SystemClock.uptimeMillis();
2628 Runnable r;
2629
2630 // Don't use these two variables in any of the callback runnables.
2631 // Otherwise we hold a reference to them.
2632 final Callbacks oldCallbacks = mCallbacks.get();
2633 if (oldCallbacks == null) {
2634 // This launcher has exited and nobody bothered to tell us. Just bail.
2635 Log.w(TAG, "LoaderTask running with no launcher");
2636 return;
2637 }
2638
Winson Chung9b9fb962013-11-15 15:39:34 -08002639 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2641 ArrayList<LauncherAppWidgetInfo> appWidgets =
2642 new ArrayList<LauncherAppWidgetInfo>();
2643 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2644 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002645 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002646 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002647 workspaceItems.addAll(sBgWorkspaceItems);
2648 appWidgets.addAll(sBgAppWidgets);
2649 folders.putAll(sBgFolders);
2650 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002651 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 }
2653
Derek Prothro7aff3992013-12-10 14:00:37 -05002654 final boolean isLoadingSynchronously =
2655 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002656 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002657 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002658 if (currScreen >= orderedScreenIds.size()) {
2659 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002660 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002661 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002662 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002663 final long currentScreenId = currentScreen < 0
2664 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002665
2666 // Load all the items that are on the current page first (and in the process, unbind
2667 // all the existing workspace items before we call startBinding() below.
2668 unbindWorkspaceItemsOnMainThread();
2669
2670 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2672 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2673 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2674 new ArrayList<LauncherAppWidgetInfo>();
2675 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2676 new ArrayList<LauncherAppWidgetInfo>();
2677 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2678 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2679
Winson Chung9b9fb962013-11-15 15:39:34 -08002680 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002682 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002683 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002684 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002685 otherFolders);
2686 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2687 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2688
2689 // Tell the workspace that we're about to start binding items
2690 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002691 public void run() {
2692 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2693 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002694 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002695 }
2696 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002697 };
Winson Chung81b52252012-08-27 15:34:29 -07002698 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002699
Adam Cohendcd297f2013-06-18 13:13:40 -07002700 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2701
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002702 // Load items on the current page
2703 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2704 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002705 if (isLoadingSynchronously) {
2706 r = new Runnable() {
2707 public void run() {
2708 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002709 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002710 callbacks.onPageBoundSynchronously(currentScreen);
2711 }
2712 }
2713 };
Winson Chung81b52252012-08-27 15:34:29 -07002714 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002715 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002716
Winson Chung4a2afa32012-07-19 14:53:05 -07002717 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2718 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002719 synchronized (mDeferredBindRunnables) {
2720 mDeferredBindRunnables.clear();
2721 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002722 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002723 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002724
2725 // Tell the workspace that we're done binding items
2726 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002727 public void run() {
2728 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2729 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002730 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002731 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002732
Winson Chung98e030b2012-05-07 16:01:11 -07002733 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002734 if (DEBUG_LOADERS) {
2735 Log.d(TAG, "bound workspace in "
2736 + (SystemClock.uptimeMillis()-t) + "ms");
2737 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002738
2739 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002740 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002741 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002742 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002743 synchronized (mDeferredBindRunnables) {
2744 mDeferredBindRunnables.add(r);
2745 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002746 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002747 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002748 }
Joe Onorato36115782010-06-17 13:28:48 -04002749 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002750
Joe Onorato36115782010-06-17 13:28:48 -04002751 private void loadAndBindAllApps() {
2752 if (DEBUG_LOADERS) {
2753 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2754 }
2755 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002756 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002757 synchronized (LoaderTask.this) {
2758 if (mStopped) {
2759 return;
2760 }
2761 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002762 }
Joe Onorato36115782010-06-17 13:28:48 -04002763 } else {
2764 onlyBindAllApps();
2765 }
2766 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002767
Joe Onorato36115782010-06-17 13:28:48 -04002768 private void onlyBindAllApps() {
2769 final Callbacks oldCallbacks = mCallbacks.get();
2770 if (oldCallbacks == null) {
2771 // This launcher has exited and nobody bothered to tell us. Just bail.
2772 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2773 return;
2774 }
2775
2776 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002777 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002778 final ArrayList<AppInfo> list
2779 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002780 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002781 public void run() {
2782 final long t = SystemClock.uptimeMillis();
2783 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2784 if (callbacks != null) {
2785 callbacks.bindAllApplications(list);
2786 }
2787 if (DEBUG_LOADERS) {
2788 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2789 + (SystemClock.uptimeMillis()-t) + "ms");
2790 }
2791 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002792 };
2793 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002794 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002795 r.run();
2796 } else {
2797 mHandler.post(r);
2798 }
Joe Onorato36115782010-06-17 13:28:48 -04002799 }
2800
Winson Chung64359a52013-07-08 17:17:08 -07002801 private void loadAllApps() {
2802 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002803
Joe Onorato36115782010-06-17 13:28:48 -04002804 final Callbacks oldCallbacks = mCallbacks.get();
2805 if (oldCallbacks == null) {
2806 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002807 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002808 return;
2809 }
2810
2811 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2812 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2813
Kenny Guyed131872014-04-30 03:02:21 +01002814 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2815
Winson Chung64359a52013-07-08 17:17:08 -07002816 // Clear the list of apps
2817 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002818 for (UserHandleCompat user : profiles) {
2819 // Query for the set of apps
2820 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2821 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2822 if (DEBUG_LOADERS) {
2823 Log.d(TAG, "getActivityList took "
2824 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2825 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2826 }
2827 // Fail if we don't have any apps
2828 if (apps == null || apps.isEmpty()) {
2829 return;
2830 }
2831 // Sort the applications by name
2832 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2833 Collections.sort(apps,
2834 new LauncherModel.ShortcutNameComparator(mLabelCache));
2835 if (DEBUG_LOADERS) {
2836 Log.d(TAG, "sort took "
2837 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2838 }
Joe Onorato36115782010-06-17 13:28:48 -04002839
Kenny Guyed131872014-04-30 03:02:21 +01002840 // Create the ApplicationInfos
2841 for (int i = 0; i < apps.size(); i++) {
2842 LauncherActivityInfoCompat app = apps.get(i);
2843 // This builds the icon bitmaps.
2844 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2845 }
Winson Chung64359a52013-07-08 17:17:08 -07002846 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002847 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002848 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2849 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002850
2851 // Post callback on main thread
2852 mHandler.post(new Runnable() {
2853 public void run() {
2854 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002855 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002856 if (callbacks != null) {
2857 callbacks.bindAllApplications(added);
2858 if (DEBUG_LOADERS) {
2859 Log.d(TAG, "bound " + added.size() + " apps in "
2860 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2861 }
2862 } else {
2863 Log.i(TAG, "not binding apps: no Launcher activity");
2864 }
2865 }
2866 });
2867
Joe Onorato36115782010-06-17 13:28:48 -04002868 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002869 Log.d(TAG, "Icons processed in "
2870 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002871 }
2872 }
2873
2874 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002875 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002876 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2877 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2878 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2879 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2880 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2881 }
Joe Onorato36115782010-06-17 13:28:48 -04002882 }
2883 }
2884
2885 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002886 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002887 }
2888
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002889 private class AppsAvailabilityCheck extends BroadcastReceiver {
2890
2891 @Override
2892 public void onReceive(Context context, Intent intent) {
2893 synchronized (sBgLock) {
2894 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2895 .getInstance(mApp.getContext());
2896 ArrayList<String> packagesRemoved;
2897 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2898 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002899 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002900 for (String pkg : entry.getValue()) {
2901 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2902 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2903 packagesRemoved.add(pkg);
2904 }
2905 }
2906 if (!packagesRemoved.isEmpty()) {
2907 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2908 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2909 }
2910 }
Sunny Goyal34942622014-08-29 17:20:55 -07002911 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002912 }
2913 }
2914 }
2915
Joe Onorato36115782010-06-17 13:28:48 -04002916 private class PackageUpdatedTask implements Runnable {
2917 int mOp;
2918 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002919 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002920
2921 public static final int OP_NONE = 0;
2922 public static final int OP_ADD = 1;
2923 public static final int OP_UPDATE = 2;
2924 public static final int OP_REMOVE = 3; // uninstlled
2925 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2926
2927
Kenny Guyed131872014-04-30 03:02:21 +01002928 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002929 mOp = op;
2930 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002931 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002932 }
2933
2934 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002935 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002936
2937 final String[] packages = mPackages;
2938 final int N = packages.length;
2939 switch (mOp) {
2940 case OP_ADD:
2941 for (int i=0; i<N; i++) {
2942 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002943 mIconCache.remove(packages[i], mUser);
2944 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002945 }
2946 break;
2947 case OP_UPDATE:
2948 for (int i=0; i<N; i++) {
2949 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002950 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002951 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002952 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002953 }
2954 break;
2955 case OP_REMOVE:
2956 case OP_UNAVAILABLE:
2957 for (int i=0; i<N; i++) {
2958 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002959 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002960 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002961 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002962 }
2963 break;
2964 }
2965
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002966 ArrayList<AppInfo> added = null;
2967 ArrayList<AppInfo> modified = null;
2968 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002969
Adam Cohen487f7dd2012-06-28 18:12:10 -07002970 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002971 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002972 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002973 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002974 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002975 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002976 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002977 }
Winson Chung5d55f332012-07-16 20:45:03 -07002978 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002979 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002980 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002981 }
2982
Joe Onorato36115782010-06-17 13:28:48 -04002983 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2984 if (callbacks == null) {
2985 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2986 return;
2987 }
2988
2989 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002990 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002991 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002992 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002993 addAndBindAddedWorkspaceApps(context, addedInfos);
2994 } else {
2995 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002996 }
Joe Onorato36115782010-06-17 13:28:48 -04002997 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002998
Joe Onorato36115782010-06-17 13:28:48 -04002999 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003000 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07003001
3002 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003003 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07003004 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01003005 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07003006 for (ItemInfo i : infos) {
3007 if (isShortcutInfoUpdateable(i)) {
3008 ShortcutInfo info = (ShortcutInfo) i;
3009 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003010 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07003011 updateItemInDatabase(context, info);
3012 }
3013 }
3014 }
3015
Joe Onorato36115782010-06-17 13:28:48 -04003016 mHandler.post(new Runnable() {
3017 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003018 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3019 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003020 callbacks.bindAppsUpdated(modifiedFinal);
3021 }
3022 }
3023 });
3024 }
Winson Chung83892cc2013-05-01 16:53:33 -07003025
Winson Chungdf95eb12013-10-16 14:57:07 -07003026 final ArrayList<String> removedPackageNames =
3027 new ArrayList<String>();
3028 if (mOp == OP_REMOVE) {
3029 // Mark all packages in the broadcast to be removed
3030 removedPackageNames.addAll(Arrays.asList(packages));
3031 } else if (mOp == OP_UPDATE) {
3032 // Mark disabled packages in the broadcast to be removed
3033 final PackageManager pm = context.getPackageManager();
3034 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003035 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003036 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003037 }
3038 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003039 }
3040 // Remove all the components associated with this package
3041 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003042 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003043 }
3044 // Remove all the specific components
3045 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003046 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003047 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003048 }
3049 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3050 // Remove any queued items from the install queue
3051 String spKey = LauncherAppState.getSharedPreferencesKey();
3052 SharedPreferences sp =
3053 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3054 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3055 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003056 mHandler.post(new Runnable() {
3057 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003058 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3059 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003060 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003061 }
3062 }
3063 });
Joe Onoratobe386092009-11-17 17:32:16 -08003064 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003065
Michael Jurkac402cd92013-05-20 15:49:32 +02003066 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003067 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003068 mHandler.post(new Runnable() {
3069 @Override
3070 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003071 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3072 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003073 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003074 }
3075 }
3076 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003077
3078 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003079 mHandler.post(new Runnable() {
3080 public void run() {
3081 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3082 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003083 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003084 }
3085 }
3086 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003087 }
3088 }
3089
Michael Jurkac402cd92013-05-20 15:49:32 +02003090 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3091 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3092 PackageManager packageManager = context.getPackageManager();
3093 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003094 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3095
Michael Jurkac402cd92013-05-20 15:49:32 +02003096 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3097 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003098 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003099 return widgetsAndShortcuts;
3100 }
3101
Kenny Guyed131872014-04-30 03:02:21 +01003102 private static boolean isPackageDisabled(Context context, String packageName,
3103 UserHandleCompat user) {
3104 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3105 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003106 }
Adam Cohen556f6132014-01-15 15:18:08 -08003107
Kenny Guyed131872014-04-30 03:02:21 +01003108 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3109 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003110 if (cn == null) {
3111 return false;
3112 }
Kenny Guyed131872014-04-30 03:02:21 +01003113 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3114 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003115 return false;
3116 }
Kenny Guyed131872014-04-30 03:02:21 +01003117 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003118 }
3119
Adam Cohena28b78e2014-05-20 17:03:04 -07003120 public static boolean isValidPackage(Context context, String packageName,
3121 UserHandleCompat user) {
3122 if (packageName == null) {
3123 return false;
3124 }
3125 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3126 return launcherApps.isPackageEnabledForProfile(packageName, user);
3127 }
3128
Joe Onorato9c1289c2009-08-17 11:03:03 -04003129 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003130 * Make an ShortcutInfo object for a restored application or shortcut item that points
3131 * to a package that is not yet installed on the system.
3132 */
Sunny Goyal34942622014-08-29 17:20:55 -07003133 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3134 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003135 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003136 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003137 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3138
3139 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3140 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3141 if (!TextUtils.isEmpty(title)) {
3142 info.title = title;
3143 }
3144 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3145 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3146 if (TextUtils.isEmpty(info.title)) {
3147 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3148 }
3149 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3150 } else {
3151 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3152 }
3153
Kenny Guyc2bd8102014-06-30 12:30:31 +01003154 info.contentDescription = mUserManager.getBadgedLabelForUser(
3155 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003156 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003157 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003158 return info;
3159 }
3160
3161 /**
3162 * Make an Intent object for a restored application or shortcut item that points
3163 * to the market page for the item.
3164 */
3165 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3166 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003167 return getMarketIntent(componentName.getPackageName());
3168 }
3169
3170 static Intent getMarketIntent(String packageName) {
3171 return new Intent(Intent.ACTION_VIEW)
3172 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003173 .scheme("market")
3174 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003175 .appendQueryParameter("id", packageName)
3176 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003177 }
3178
3179 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003180 * This is called from the code that adds shortcuts from the intent receiver. This
3181 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003182 */
Kenny Guyed131872014-04-30 03:02:21 +01003183 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3184 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003185 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003186 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003187
Joe Onorato56d82912010-03-07 14:32:10 -05003188 /**
3189 * Make an ShortcutInfo object for a shortcut that is an application.
3190 *
3191 * If c is not null, then it will be used to fill in missing data like the title and icon.
3192 */
Kenny Guyed131872014-04-30 03:02:21 +01003193 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3194 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003195 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003196 if (user == null) {
3197 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003198 return null;
3199 }
3200
Kenny Guyed131872014-04-30 03:02:21 +01003201 ComponentName componentName = intent.getComponent();
3202 if (componentName == null) {
3203 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3204 return null;
3205 }
3206
3207 Intent newIntent = new Intent(intent.getAction(), null);
3208 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3209 newIntent.setComponent(componentName);
3210 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003211 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003212 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3213 return null;
3214 }
3215
3216 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003217
Joe Onorato56d82912010-03-07 14:32:10 -05003218 // the resource -- This may implicitly give us back the fallback icon,
3219 // but don't worry about that. All we're doing with usingFallbackIcon is
3220 // to avoid saving lots of copies of that in the database, and most apps
3221 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003222 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003223
Joe Onorato56d82912010-03-07 14:32:10 -05003224 // the db
3225 if (icon == null) {
3226 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003227 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003228 }
3229 }
3230 // the fallback icon
3231 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003232 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003233 info.usingFallbackIcon = true;
3234 }
3235 info.setIcon(icon);
3236
Kenny Guyed131872014-04-30 03:02:21 +01003237 // From the cache.
3238 if (labelCache != null) {
3239 info.title = labelCache.get(componentName);
3240 }
3241
Joe Onorato56d82912010-03-07 14:32:10 -05003242 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003243 if (info.title == null && lai != null) {
3244 info.title = lai.getLabel();
3245 if (labelCache != null) {
3246 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003247 }
Joe Onorato56d82912010-03-07 14:32:10 -05003248 }
3249 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003250 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003251 if (c != null) {
3252 info.title = c.getString(titleIndex);
3253 }
3254 }
3255 // fall back to the class name of the activity
3256 if (info.title == null) {
3257 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003258 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003259 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003260 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003261 info.contentDescription = mUserManager.getBadgedLabelForUser(
3262 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003263 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003264 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003265
Winson Chung64359a52013-07-08 17:17:08 -07003266 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3267 ItemInfoFilter f) {
3268 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3269 for (ItemInfo i : infos) {
3270 if (i instanceof ShortcutInfo) {
3271 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003272 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003273 if (cn != null && f.filterItem(null, info, cn)) {
3274 filtered.add(info);
3275 }
3276 } else if (i instanceof FolderInfo) {
3277 FolderInfo info = (FolderInfo) i;
3278 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003279 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003280 if (cn != null && f.filterItem(info, s, cn)) {
3281 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003282 }
3283 }
Winson Chung64359a52013-07-08 17:17:08 -07003284 } else if (i instanceof LauncherAppWidgetInfo) {
3285 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3286 ComponentName cn = info.providerName;
3287 if (cn != null && f.filterItem(null, info, cn)) {
3288 filtered.add(info);
3289 }
Winson Chung8a435102012-08-30 17:16:53 -07003290 }
3291 }
Winson Chung64359a52013-07-08 17:17:08 -07003292 return new ArrayList<ItemInfo>(filtered);
3293 }
3294
Kenny Guyed131872014-04-30 03:02:21 +01003295 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3296 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003297 ItemInfoFilter filter = new ItemInfoFilter() {
3298 @Override
3299 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003300 if (info.user == null) {
3301 return cn.equals(cname);
3302 } else {
3303 return cn.equals(cname) && info.user.equals(user);
3304 }
Winson Chung64359a52013-07-08 17:17:08 -07003305 }
3306 };
3307 return filterItemInfos(sBgItemsIdMap.values(), filter);
3308 }
3309
3310 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3311 if (i instanceof ShortcutInfo) {
3312 ShortcutInfo info = (ShortcutInfo) i;
3313 // We need to check for ACTION_MAIN otherwise getComponent() might
3314 // return null for some shortcuts (for instance, for shortcuts to
3315 // web pages.)
3316 Intent intent = info.intent;
3317 ComponentName name = intent.getComponent();
3318 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3319 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3320 return true;
3321 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003322 // placeholder shortcuts get special treatment, let them through too.
Sunny Goyal34942622014-08-29 17:20:55 -07003323 if (info.isPromise()) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003324 return true;
3325 }
Winson Chung64359a52013-07-08 17:17:08 -07003326 }
3327 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003328 }
3329
3330 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003331 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003332 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003333 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003334 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3335 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003336
Joe Onorato56d82912010-03-07 14:32:10 -05003337 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003338 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003339 // Non-app shortcuts are only supported for current user.
3340 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003341 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003342
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003343 // TODO: If there's an explicit component and we can't install that, delete it.
3344
Joe Onorato56d82912010-03-07 14:32:10 -05003345 info.title = c.getString(titleIndex);
3346
Joe Onorato9c1289c2009-08-17 11:03:03 -04003347 int iconType = c.getInt(iconTypeIndex);
3348 switch (iconType) {
3349 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3350 String packageName = c.getString(iconPackageIndex);
3351 String resourceName = c.getString(iconResourceIndex);
3352 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003353 info.customIcon = false;
3354 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003355 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003356 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003357 if (resources != null) {
3358 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003359 icon = Utilities.createIconBitmap(
3360 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003361 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003362 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003363 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003364 }
Joe Onorato56d82912010-03-07 14:32:10 -05003365 // the db
3366 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003367 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003368 }
3369 // the fallback icon
3370 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003371 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003372 info.usingFallbackIcon = true;
3373 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003374 break;
3375 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003376 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003377 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003378 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003379 info.customIcon = false;
3380 info.usingFallbackIcon = true;
3381 } else {
3382 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003383 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003384 break;
3385 default:
Kenny Guyed131872014-04-30 03:02:21 +01003386 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003387 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003388 info.customIcon = false;
3389 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003390 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003391 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003392 return info;
3393 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003394
Michael Jurka931dc972011-08-05 15:08:15 -07003395 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003396 @SuppressWarnings("all") // suppress dead code warning
3397 final boolean debug = false;
3398 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003399 Log.d(TAG, "getIconFromCursor app="
3400 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3401 }
3402 byte[] data = c.getBlob(iconIndex);
3403 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003404 return Utilities.createIconBitmap(
3405 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003406 } catch (Exception e) {
3407 return null;
3408 }
3409 }
3410
Winson Chung3d503fb2011-07-13 17:25:49 -07003411 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3412 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003413 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003414 if (info == null) {
3415 return null;
3416 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003417 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003418
3419 return info;
3420 }
3421
Winson Chunga9abd0e2010-10-27 17:18:37 -07003422 /**
Winson Chung55cef262010-10-28 14:14:18 -07003423 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3424 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003425 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003426 ComponentName component) {
3427 List<AppWidgetProviderInfo> widgets =
3428 AppWidgetManager.getInstance(context).getInstalledProviders();
3429 for (AppWidgetProviderInfo info : widgets) {
3430 if (info.provider.equals(component)) {
3431 return info;
3432 }
3433 }
3434 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003435 }
3436
3437 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003438 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3439 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3440 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3441
Adam Cohend9198822011-11-22 16:42:47 -08003442 if (intent == null) {
3443 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3444 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3445 return null;
3446 }
3447
Joe Onorato0589f0f2010-02-08 13:44:00 -08003448 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003449 boolean customIcon = false;
3450 ShortcutIconResource iconResource = null;
3451
3452 if (bitmap != null && bitmap instanceof Bitmap) {
3453 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003454 customIcon = true;
3455 } else {
3456 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3457 if (extra != null && extra instanceof ShortcutIconResource) {
3458 try {
3459 iconResource = (ShortcutIconResource) extra;
3460 final PackageManager packageManager = context.getPackageManager();
3461 Resources resources = packageManager.getResourcesForApplication(
3462 iconResource.packageName);
3463 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003464 icon = Utilities.createIconBitmap(
Kenny Guyed131872014-04-30 03:02:21 +01003465 mIconCache.getFullResIcon(resources, id),
3466 context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003467 } catch (Exception e) {
3468 Log.w(TAG, "Could not load shortcut icon: " + extra);
3469 }
3470 }
3471 }
3472
Michael Jurkac9d95c52011-08-29 14:03:34 -07003473 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003474
Kenny Guyed131872014-04-30 03:02:21 +01003475 // Only support intents for current user for now. Intents sent from other
3476 // users wouldn't get here without intent forwarding anyway.
3477 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003478 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003479 if (fallbackIcon != null) {
3480 icon = fallbackIcon;
3481 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003482 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003483 info.usingFallbackIcon = true;
3484 }
Joe Onorato56d82912010-03-07 14:32:10 -05003485 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003486 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003487
Joe Onorato0589f0f2010-02-08 13:44:00 -08003488 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003489 info.contentDescription = mUserManager.getBadgedLabelForUser(
3490 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003491 info.intent = intent;
3492 info.customIcon = customIcon;
3493 info.iconResource = iconResource;
3494
3495 return info;
3496 }
3497
Winson Chungaac01e12011-08-17 10:37:13 -07003498 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3499 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003500 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003501 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003502 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003503 }
Joe Onorato56d82912010-03-07 14:32:10 -05003504 // If this icon doesn't have a custom icon, check to see
3505 // what's stored in the DB, and if it doesn't match what
3506 // we're going to show, store what we are going to show back
3507 // into the DB. We do this so when we're loading, if the
3508 // package manager can't find an icon (for example because
3509 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003510 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003511 cache.put(info, c.getBlob(iconIndex));
3512 return true;
3513 }
3514 return false;
3515 }
3516 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3517 boolean needSave = false;
3518 try {
3519 if (data != null) {
3520 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3521 Bitmap loaded = info.getIcon(mIconCache);
3522 needSave = !saved.sameAs(loaded);
3523 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003524 needSave = true;
3525 }
Winson Chungaac01e12011-08-17 10:37:13 -07003526 } catch (Exception e) {
3527 needSave = true;
3528 }
3529 if (needSave) {
3530 Log.d(TAG, "going to save icon bitmap for info=" + info);
3531 // This is slower than is ideal, but this only happens once
3532 // or when the app is updated with a new icon.
3533 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003534 }
3535 }
3536
Joe Onorato9c1289c2009-08-17 11:03:03 -04003537 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003538 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003539 * or make a new one.
3540 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003541 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003542 // See if a placeholder was created for us already
3543 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003544 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003545 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003546 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003547 folders.put(id, folderInfo);
3548 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003549 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003550 }
3551
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003552 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003553 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003554 return new Comparator<AppInfo>() {
3555 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003556 if (a.user.equals(b.user)) {
3557 int result = collator.compare(a.title.toString().trim(),
3558 b.title.toString().trim());
3559 if (result == 0) {
3560 result = a.componentName.compareTo(b.componentName);
3561 }
3562 return result;
3563 } else {
3564 // TODO Need to figure out rules for sorting
3565 // profiles, this puts work second.
3566 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003567 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003568 }
Winson Chung11904872012-09-17 16:58:46 -07003569 };
3570 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003571 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3572 = new Comparator<AppInfo>() {
3573 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003574 if (a.firstInstallTime < b.firstInstallTime) return 1;
3575 if (a.firstInstallTime > b.firstInstallTime) return -1;
3576 return 0;
3577 }
3578 };
Winson Chung5308f242011-08-18 12:12:41 -07003579 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3580 if (info.activityInfo != null) {
3581 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3582 } else {
3583 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3584 }
3585 }
Kenny Guyed131872014-04-30 03:02:21 +01003586 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003587 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003588 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003589 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003590 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003591 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003592 }
Kenny Guyed131872014-04-30 03:02:21 +01003593 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003594 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003595 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003596 }
Kenny Guyed131872014-04-30 03:02:21 +01003597 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003598 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003599 ComponentName keyA = a.getComponentName();
3600 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003601 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003602 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003603 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003604 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003605
Winson Chung5308f242011-08-18 12:12:41 -07003606 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003607 }
Winson Chung5308f242011-08-18 12:12:41 -07003608 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003609 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003610 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003611 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003612
Winson Chung5308f242011-08-18 12:12:41 -07003613 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003614 }
Winson Chung11904872012-09-17 16:58:46 -07003615 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003616 }
3617 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003618 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003619 private final AppWidgetManagerCompat mManager;
3620 private final PackageManager mPackageManager;
3621 private final HashMap<Object, String> mLabelCache;
3622 private final Collator mCollator;
3623
3624 WidgetAndShortcutNameComparator(Context context) {
3625 mManager = AppWidgetManagerCompat.getInstance(context);
3626 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003627 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003628 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003629 }
3630 public final int compare(Object a, Object b) {
3631 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003632 if (mLabelCache.containsKey(a)) {
3633 labelA = mLabelCache.get(a);
3634 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003635 labelA = (a instanceof AppWidgetProviderInfo)
3636 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3637 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003638 mLabelCache.put(a, labelA);
3639 }
3640 if (mLabelCache.containsKey(b)) {
3641 labelB = mLabelCache.get(b);
3642 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003643 labelB = (b instanceof AppWidgetProviderInfo)
3644 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3645 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003646 mLabelCache.put(b, labelB);
3647 }
Winson Chung11904872012-09-17 16:58:46 -07003648 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003649 }
3650 };
Joe Onoratobe386092009-11-17 17:32:16 -08003651
Sunny Goyal651077b2014-06-30 14:15:31 -07003652 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3653 return (provider != null) && (provider.provider != null)
3654 && (provider.provider.getPackageName() != null);
3655 }
3656
Joe Onoratobe386092009-11-17 17:32:16 -08003657 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003658 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003659 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3660 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3661 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3662 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003663 if (mLoaderTask != null) {
3664 mLoaderTask.dumpState();
3665 } else {
3666 Log.d(TAG, "mLoaderTask=null");
3667 }
Joe Onoratobe386092009-11-17 17:32:16 -08003668 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003669}