blob: eb4210f385650e602393f07f82e066852e3f86fc [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;
Sunny Goyal94485362014-09-18 16:13:58 -070089 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Chris Wrenb358f812014-04-16 13:37:00 -040090
Joe Onorato9c1289c2009-08-17 11:03:03 -040091 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070092
Daniel Sandler8707e0f2013-08-15 15:54:18 -070093 // true = use a "More Apps" folder for non-workspace apps on upgrade
94 // false = strew non-workspace apps across the workspace on upgrade
95 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050096 public static final int LOADER_FLAG_NONE = 0;
97 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
98 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
99
Joe Onorato36115782010-06-17 13:28:48 -0400100 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500101 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800102
Winson Chungee055712013-07-30 14:46:24 -0700103 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800104 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400105
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400106 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400107 private final Object mLock = new Object();
108 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400109 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700110 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200111 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Winson Chung81b52252012-08-27 15:34:29 -0700113 // Specific runnable types that are run on the main thread deferred handler, this allows us to
114 // clear all queued binding runnables when the Launcher activity is destroyed.
115 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
116 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
117
Jason Monkbbe1e242014-05-16 17:37:34 -0400118 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700119
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700120 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
121 static {
122 sWorkerThread.start();
123 }
124 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
125
Joe Onoratocc67f472010-06-08 10:54:30 -0700126 // We start off with everything not loaded. After that, we assume that
127 // our monitoring of the package manager provides all updates and we never
128 // need to do a requery. These are only ever touched from the loader thread.
129 private boolean mWorkspaceLoaded;
130 private boolean mAllAppsLoaded;
131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // When we are loading pages synchronously, we can't just post the binding of items on the side
133 // pages as this delays the rotation process. Instead, we wait for a callback from the first
134 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
135 // a normal load, we also clear this set of Runnables.
136 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
137
Joe Onorato9c1289c2009-08-17 11:03:03 -0400138 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700141 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800142
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700143 // The lock that must be acquired before referencing any static bg data structures. Unlike
144 // other locks, this one can generally be held long-term because we never expect any of these
145 // static data structures to be referenced outside of the worker thread except on the first
146 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700147 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
154 // created by LauncherModel that are directly on the home screen (however, no widgets or
155 // shortcuts within folders).
156 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
159 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 new ArrayList<LauncherAppWidgetInfo>();
161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
163 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700164
Adam Cohen487f7dd2012-06-28 18:12:10 -0700165 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
166 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700167
168 // sBgWorkspaceScreens is the ordered set of workspace screens.
169 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
170
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700172 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
173 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700174
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 // </ only access in worker thread >
176
177 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
Reena Lee99a73f32011-10-24 17:27:37 -0700179 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700180
Kenny Guyed131872014-04-30 03:02:21 +0100181 private final LauncherAppsCompat mLauncherApps;
182 private final UserManagerCompat mUserManager;
183
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700185 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public int getCurrentWorkspaceScreen();
187 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
189 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700190 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700191 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500192 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700193 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200195 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700196 public void bindAppsAdded(ArrayList<Long> newScreens,
197 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700198 ArrayList<ItemInfo> addAnimated,
199 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200200 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700201 public void bindShortcutsUpdated(ArrayList<ShortcutInfo> shortcuts);
Sunny Goyale755d462014-07-22 13:48:29 -0700202 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700203 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700204 public void bindComponentsRemoved(ArrayList<String> packageNames,
Kenny Guyed131872014-04-30 03:02:21 +0100205 ArrayList<AppInfo> appInfos, UserHandleCompat user);
Michael Jurkac402cd92013-05-20 15:49:32 +0200206 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100207 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700208 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700209 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700210 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400211 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212
Winson Chung64359a52013-07-08 17:17:08 -0700213 public interface ItemInfoFilter {
214 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
215 }
216
Bjorn Bringert1307f632013-10-03 22:31:03 +0100217 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800218 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400219
Winson Chungee055712013-07-30 14:46:24 -0700220 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700221 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400222 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
223 // resource string.
224 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
225 ProviderInfo providerInfo =
226 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
227 ProviderInfo redirectProvider =
228 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700229
230 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400231 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700232
233 if (mOldContentProviderExists) {
234 Log.d(TAG, "Old launcher provider exists.");
235 } else {
236 Log.d(TAG, "Old launcher provider does not exist.");
237 }
238
Daniel Sandlere4f98912013-06-25 15:13:26 -0400239 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100240 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800241 mIconCache = iconCache;
242
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400243 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700244 Configuration config = res.getConfiguration();
245 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100246 mLauncherApps = LauncherAppsCompat.getInstance(context);
247 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800248 }
249
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700250 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
251 * posted on the main thread handler. */
252 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700253 runOnMainThread(r, 0);
254 }
255 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700256 if (sWorkerThread.getThreadId() == Process.myTid()) {
257 // If we are on the worker thread, post onto the main handler
258 mHandler.post(r);
259 } else {
260 r.run();
261 }
262 }
263
264 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
265 * posted on the worker thread handler. */
266 private static void runOnWorkerThread(Runnable r) {
267 if (sWorkerThread.getThreadId() == Process.myTid()) {
268 r.run();
269 } else {
270 // If we are not on the worker thread, then post to the worker handler
271 sWorker.post(r);
272 }
273 }
274
Winson Chunge43a1e72014-01-15 10:33:02 -0800275 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
276 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800277 }
278
Winson Chungc9168342013-06-26 14:54:55 -0700279 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
280 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700281 LauncherAppState app = LauncherAppState.getInstance();
282 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
283 final int xCount = (int) grid.numColumns;
284 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700285 boolean[][] occupied = new boolean[xCount][yCount];
286
287 int cellX, cellY, spanX, spanY;
288 for (int i = 0; i < items.size(); ++i) {
289 final ItemInfo item = items.get(i);
290 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
291 if (item.screenId == screen) {
292 cellX = item.cellX;
293 cellY = item.cellY;
294 spanX = item.spanX;
295 spanY = item.spanY;
296 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
297 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
298 occupied[x][y] = true;
299 }
300 }
301 }
302 }
303 }
304
305 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
306 }
307 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700308 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700309 int firstScreenIndex,
310 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700311 // Lock on the app so that we don't try and get the items while apps are being added
312 LauncherAppState app = LauncherAppState.getInstance();
313 LauncherModel model = app.getModel();
314 boolean found = false;
315 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700316 if (sWorkerThread.getThreadId() != Process.myTid()) {
317 // Flush the LauncherModel worker thread, so that if we just did another
318 // processInstallShortcut, we give it time for its shortcut to get added to the
319 // database (getItemsInLocalCoordinates reads the database)
320 model.flushWorkerThread();
321 }
Winson Chungc9168342013-06-26 14:54:55 -0700322 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700323
324 // Try adding to the workspace screens incrementally, starting at the default or center
325 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700326 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
327 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700328 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700329 int[] tmpCoordinates = new int[2];
330 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700331 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700332 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700333 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700334 }
335 }
336 }
Winson Chungc9168342013-06-26 14:54:55 -0700337 return null;
338 }
339
Sunny Goyale755d462014-07-22 13:48:29 -0700340 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500341 // Process the updated package state
342 Runnable r = new Runnable() {
343 public void run() {
344 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
345 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700346 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500347 }
348 }
349 };
350 mHandler.post(r);
351 }
352
Sunny Goyala22666f2014-09-18 13:25:15 -0700353 public void updatePackageBadge(final String packageName) {
354 // Process the updated package badge
355 Runnable r = new Runnable() {
356 public void run() {
357 Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
358 if (callbacks != null) {
359 callbacks.updatePackageBadge(packageName);
360 }
361 }
362 };
363 mHandler.post(r);
364 }
365
Adam Cohen76a47a12014-02-05 11:47:43 -0800366 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
367 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
368
369 if (allAppsApps == null) {
370 throw new RuntimeException("allAppsApps must not be null");
371 }
372 if (allAppsApps.isEmpty()) {
373 return;
374 }
375
Chris Wrenb6d4c282014-01-27 14:17:08 -0500376 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
377 Iterator<AppInfo> iter = allAppsApps.iterator();
378 while (iter.hasNext()) {
379 ItemInfo a = iter.next();
Sunny Goyal34942622014-08-29 17:20:55 -0700380 if (LauncherModel.appWasPromise(ctx, a.getIntent(), a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500381 restoredAppsFinal.add((AppInfo) a);
382 }
383 }
384
Adam Cohen76a47a12014-02-05 11:47:43 -0800385 // Process the newly added applications and add them to the database first
386 Runnable r = new Runnable() {
387 public void run() {
388 runOnMainThread(new Runnable() {
389 public void run() {
390 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
391 if (callbacks == cb && cb != null) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500392 if (!restoredAppsFinal.isEmpty()) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500393 for (AppInfo info : restoredAppsFinal) {
394 final Intent intent = info.getIntent();
395 if (intent != null) {
Kenny Guyed131872014-04-30 03:02:21 +0100396 mIconCache.deletePreloadedIcon(intent.getComponent(),
397 info.user);
Chris Wren6d0dde02014-02-10 12:16:54 -0500398 }
399 }
Chris Wrenb6d4c282014-01-27 14:17:08 -0500400 callbacks.bindAppsUpdated(restoredAppsFinal);
401 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500402 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800403 }
404 }
405 });
406 }
407 };
408 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700409 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800410
411 public void addAndBindAddedWorkspaceApps(final Context context,
412 final ArrayList<ItemInfo> workspaceApps) {
413 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
414
415 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800416 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
417 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800418 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700419 return;
Winson Chung997a9232013-07-24 15:33:46 -0700420 }
Winson Chung64359a52013-07-08 17:17:08 -0700421 // Process the newly added applications and add them to the database first
422 Runnable r = new Runnable() {
423 public void run() {
424 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
425 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500426 final ArrayList<AppInfo> restoredAppsFinal = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -0700427
Winson Chung76828c82013-08-19 15:43:29 -0700428 // Get the list of workspace screens. We need to append to this list and
429 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
430 // called.
431 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
432 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
433 for (Integer i : orderedScreens.keySet()) {
434 long screenId = orderedScreens.get(i);
435 workspaceScreens.add(screenId);
436 }
437
Winson Chung64359a52013-07-08 17:17:08 -0700438 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700439 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700440 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700441 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700442 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700443 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700444
445 // Short-circuit this logic if the icon exists somewhere on the workspace
446 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500447 // Only InstallShortcutReceiver sends us shortcutInfos, ignore them
448 if (a instanceof AppInfo &&
Sunny Goyal34942622014-08-29 17:20:55 -0700449 LauncherModel.appWasPromise(context, launchIntent, a.user)) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500450 restoredAppsFinal.add((AppInfo) a);
451 }
Winson Chung64359a52013-07-08 17:17:08 -0700452 continue;
453 }
454
Winson Chung87412982013-10-03 18:34:14 -0700455 // Add this icon to the db, creating a new page if necessary. If there
456 // is only the empty page then we just add items to the first page.
457 // Otherwise, we add them to the next pages.
458 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700459 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700460 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700461 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200462 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700463
464 // If we can't find a valid position, then just add a new screen.
465 // This takes time so we need to re-queue the add until the new
466 // page is added. Create as many screens as necessary to satisfy
467 // the startSearchPageIndex.
468 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700469 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700470 while (numPagesToAdd > 0) {
471 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700472 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700473 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700474 addedWorkspaceScreensFinal.add(screenId);
475 numPagesToAdd--;
476 }
Winson Chung76828c82013-08-19 15:43:29 -0700477
Winson Chung64359a52013-07-08 17:17:08 -0700478 // Find the coordinate again
479 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700480 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700481 }
482 if (coords == null) {
483 throw new RuntimeException("Coordinates should not be null");
484 }
485
Winson Chung997a9232013-07-24 15:33:46 -0700486 ShortcutInfo shortcutInfo;
487 if (a instanceof ShortcutInfo) {
488 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200489 } else if (a instanceof AppInfo) {
490 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700491 } else {
492 throw new RuntimeException("Unexpected info type");
493 }
Winson Chung94d67682013-09-25 16:29:40 -0700494
Winson Chung64359a52013-07-08 17:17:08 -0700495 // Add the shortcut to the db
496 addItemToDatabase(context, shortcutInfo,
497 LauncherSettings.Favorites.CONTAINER_DESKTOP,
498 coords.first, coords.second[0], coords.second[1], false);
499 // Save the ShortcutInfo for binding in the workspace
500 addedShortcutsFinal.add(shortcutInfo);
501 }
502 }
503
Winson Chung76828c82013-08-19 15:43:29 -0700504 // Update the workspace screens
505 updateWorkspaceScreenOrder(context, workspaceScreens);
506
Adam Cohen76a47a12014-02-05 11:47:43 -0800507 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700508 runOnMainThread(new Runnable() {
509 public void run() {
510 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
511 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700512 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
513 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700514 if (!addedShortcutsFinal.isEmpty()) {
515 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
516 long lastScreenId = info.screenId;
517 for (ItemInfo i : addedShortcutsFinal) {
518 if (i.screenId == lastScreenId) {
519 addAnimated.add(i);
520 } else {
521 addNotAnimated.add(i);
522 }
Winson Chung997a9232013-07-24 15:33:46 -0700523 }
524 }
Winson Chungd64d1762013-08-20 14:37:16 -0700525 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800526 addNotAnimated, addAnimated, null);
Chris Wrenb6d4c282014-01-27 14:17:08 -0500527 if (!restoredAppsFinal.isEmpty()) {
528 callbacks.bindAppsUpdated(restoredAppsFinal);
529 }
Winson Chung997a9232013-07-24 15:33:46 -0700530 }
Winson Chung64359a52013-07-08 17:17:08 -0700531 }
Winson Chung997a9232013-07-24 15:33:46 -0700532 });
533 }
Winson Chung64359a52013-07-08 17:17:08 -0700534 }
535 };
536 runOnWorkerThread(r);
537 }
538
Winson Chung81b52252012-08-27 15:34:29 -0700539 public void unbindItemInfosAndClearQueuedBindRunnables() {
540 if (sWorkerThread.getThreadId() == Process.myTid()) {
541 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
542 "main thread");
543 }
544
545 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400546 synchronized (mDeferredBindRunnables) {
547 mDeferredBindRunnables.clear();
548 }
Winson Chung81b52252012-08-27 15:34:29 -0700549 // Remove any queued bind runnables
550 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
551 // Unbind all the workspace items
552 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700553 }
554
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700555 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700556 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700557 // Ensure that we don't use the same workspace items data structure on the main thread
558 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700559 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
560 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700561 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700562 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
563 tmpAppWidgets.addAll(sBgAppWidgets);
564 }
565 Runnable r = new Runnable() {
566 @Override
567 public void run() {
568 for (ItemInfo item : tmpWorkspaceItems) {
569 item.unbind();
570 }
571 for (ItemInfo item : tmpAppWidgets) {
572 item.unbind();
573 }
574 }
575 };
576 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700577 }
578
Joe Onorato9c1289c2009-08-17 11:03:03 -0400579 /**
580 * Adds an item to the DB if it was not created previously, or move it to a new
581 * <container, screen, cellX, cellY>
582 */
583 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700584 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400585 if (item.container == ItemInfo.NO_ID) {
586 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700587 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400588 } else {
589 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700590 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800591 }
592 }
593
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700594 static void checkItemInfoLocked(
595 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
596 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
597 if (modelItem != null && item != modelItem) {
598 // check all the data is consistent
599 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
600 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
601 ShortcutInfo shortcut = (ShortcutInfo) item;
602 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
603 modelShortcut.intent.filterEquals(shortcut.intent) &&
604 modelShortcut.id == shortcut.id &&
605 modelShortcut.itemType == shortcut.itemType &&
606 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700607 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700608 modelShortcut.cellX == shortcut.cellX &&
609 modelShortcut.cellY == shortcut.cellY &&
610 modelShortcut.spanX == shortcut.spanX &&
611 modelShortcut.spanY == shortcut.spanY &&
612 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
613 (modelShortcut.dropPos != null &&
614 shortcut.dropPos != null &&
615 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
616 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
617 // For all intents and purposes, this is the same object
618 return;
619 }
620 }
621
622 // the modelItem needs to match up perfectly with item if our model is
623 // to be consistent with the database-- for now, just require
624 // modelItem == item or the equality check above
625 String msg = "item: " + ((item != null) ? item.toString() : "null") +
626 "modelItem: " +
627 ((modelItem != null) ? modelItem.toString() : "null") +
628 "Error: ItemInfo passed to checkItemInfo doesn't match original";
629 RuntimeException e = new RuntimeException(msg);
630 if (stackTrace != null) {
631 e.setStackTrace(stackTrace);
632 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800633 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700634 }
635 }
636
Michael Jurka816474f2012-06-25 14:49:02 -0700637 static void checkItemInfo(final ItemInfo item) {
638 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
639 final long itemId = item.id;
640 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700641 public void run() {
642 synchronized (sBgLock) {
643 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700644 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700645 }
646 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700647 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700648 }
649
Michael Jurkac9d95c52011-08-29 14:03:34 -0700650 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
651 final ItemInfo item, final String callingFunction) {
652 final long itemId = item.id;
653 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
654 final ContentResolver cr = context.getContentResolver();
655
Adam Cohen487f7dd2012-06-28 18:12:10 -0700656 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700657 Runnable r = new Runnable() {
658 public void run() {
659 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700660 updateItemArrays(item, itemId, stackTrace);
661 }
662 };
663 runOnWorkerThread(r);
664 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700665
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700666 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
667 final ArrayList<ItemInfo> items, final String callingFunction) {
668 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700669
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700670 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
671 Runnable r = new Runnable() {
672 public void run() {
673 ArrayList<ContentProviderOperation> ops =
674 new ArrayList<ContentProviderOperation>();
675 int count = items.size();
676 for (int i = 0; i < count; i++) {
677 ItemInfo item = items.get(i);
678 final long itemId = item.id;
679 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
680 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700681
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700682 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
683 updateItemArrays(item, itemId, stackTrace);
684
685 }
686 try {
687 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
688 } catch (Exception e) {
689 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700690 }
691 }
692 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700693 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700694 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700695
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700696 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
697 // Lock on mBgLock *after* the db operation
698 synchronized (sBgLock) {
699 checkItemInfoLocked(itemId, item, stackTrace);
700
701 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
702 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
703 // Item is in a folder, make sure this folder exists
704 if (!sBgFolders.containsKey(item.container)) {
705 // An items container is being set to a that of an item which is not in
706 // the list of Folders.
707 String msg = "item: " + item + " container being set to: " +
708 item.container + ", not in the list of folders";
709 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700710 }
711 }
712
713 // Items are added/removed from the corresponding FolderInfo elsewhere, such
714 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
715 // that are on the desktop, as appropriate
716 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800717 if (modelItem != null &&
718 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
719 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700720 switch (modelItem.itemType) {
721 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
722 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
723 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
724 if (!sBgWorkspaceItems.contains(modelItem)) {
725 sBgWorkspaceItems.add(modelItem);
726 }
727 break;
728 default:
729 break;
730 }
731 } else {
732 sBgWorkspaceItems.remove(modelItem);
733 }
734 }
735 }
736
Michael Jurkac7700af2013-05-14 20:17:58 +0200737 public void flushWorkerThread() {
738 mFlushingWorkerThread = true;
739 Runnable waiter = new Runnable() {
740 public void run() {
741 synchronized (this) {
742 notifyAll();
743 mFlushingWorkerThread = false;
744 }
745 }
746 };
747
748 synchronized(waiter) {
749 runOnWorkerThread(waiter);
750 if (mLoaderTask != null) {
751 synchronized(mLoaderTask) {
752 mLoaderTask.notify();
753 }
754 }
755 boolean success = false;
756 while (!success) {
757 try {
758 waiter.wait();
759 success = true;
760 } catch (InterruptedException e) {
761 }
762 }
763 }
764 }
765
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800766 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400767 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700768 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700769 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400771 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400772 item.cellX = cellX;
773 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700774
Winson Chung3d503fb2011-07-13 17:25:49 -0700775 // We store hotseat items in canonical form which is this orientation invariant position
776 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700777 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700778 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700779 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700780 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700781 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700782 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400783
784 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400785 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700786 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
787 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700788 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400789
Michael Jurkac9d95c52011-08-29 14:03:34 -0700790 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700791 }
792
793 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700794 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
795 * cellX, cellY have already been updated on the ItemInfos.
796 */
797 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
798 final long container, final int screen) {
799
800 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
801 int count = items.size();
802
803 for (int i = 0; i < count; i++) {
804 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700805 item.container = container;
806
807 // We store hotseat items in canonical form which is this orientation invariant position
808 // in the hotseat
809 if (context instanceof Launcher && screen < 0 &&
810 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700811 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700812 item.cellY);
813 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700815 }
816
817 final ContentValues values = new ContentValues();
818 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
819 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
820 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700821 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700822
823 contentValues.add(values);
824 }
825 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
826 }
827
828 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800830 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700831 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700832 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700833 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800834 item.cellX = cellX;
835 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700836 item.spanX = spanX;
837 item.spanY = spanY;
838
839 // We store hotseat items in canonical form which is this orientation invariant position
840 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700841 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700842 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700843 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700844 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700845 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700846 }
Adam Cohend4844c32011-02-18 19:25:06 -0800847
Adam Cohend4844c32011-02-18 19:25:06 -0800848 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800849 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700850 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
851 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
852 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
853 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800855
Michael Jurka816474f2012-06-25 14:49:02 -0700856 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700857 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700858
859 /**
860 * Update an item to the database in a specified container.
861 */
862 static void updateItemInDatabase(Context context, final ItemInfo item) {
863 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100864 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700865 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
866 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800867 }
868
869 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400870 * Returns true if the shortcuts already exists in the database.
871 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400873 static boolean shortcutExists(Context context, String title, Intent intent) {
874 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700875 final Intent intentWithPkg, intentWithoutPkg;
876
877 if (intent.getComponent() != null) {
878 // If component is not null, an intent with null package will produce
879 // the same result and should also be a match.
880 if (intent.getPackage() != null) {
881 intentWithPkg = intent;
882 intentWithoutPkg = new Intent(intent).setPackage(null);
883 } else {
884 intentWithPkg = new Intent(intent).setPackage(
885 intent.getComponent().getPackageName());
886 intentWithoutPkg = intent;
887 }
888 } else {
889 intentWithPkg = intent;
890 intentWithoutPkg = intent;
891 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400892 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700893 new String[] { "title", "intent" }, "title=? and (intent=? or intent=?)",
894 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0) }, null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400895 boolean result = false;
896 try {
897 result = c.moveToFirst();
898 } finally {
899 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400901 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700902 }
903
Joe Onorato9c1289c2009-08-17 11:03:03 -0400904 /**
Sunny Goyal34942622014-08-29 17:20:55 -0700905 * Returns true if the promise shortcuts with the same package name exists on the workspace.
Chris Wrenb6d4c282014-01-27 14:17:08 -0500906 */
Sunny Goyal34942622014-08-29 17:20:55 -0700907 static boolean appWasPromise(Context context, Intent intent, UserHandleCompat user) {
Chris Wrenb6d4c282014-01-27 14:17:08 -0500908 final ComponentName component = intent.getComponent();
909 if (component == null) {
910 return false;
911 }
Sunny Goyal34942622014-08-29 17:20:55 -0700912 return !getItemsByPackageName(component.getPackageName(), user).isEmpty();
Chris Wrenb6d4c282014-01-27 14:17:08 -0500913 }
914
915 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 * Returns an ItemInfo array containing all the items in the LauncherModel.
917 * The ItemInfo.id is not set through this function.
918 */
919 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
920 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
921 final ContentResolver cr = context.getContentResolver();
922 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
923 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100924 LauncherSettings.Favorites.SCREEN,
925 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
926 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
927 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700928
929 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
930 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
931 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
932 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
933 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
934 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
935 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100936 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
937 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700938 try {
939 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700940 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700941 item.cellX = c.getInt(cellXIndex);
942 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700943 item.spanX = Math.max(1, c.getInt(spanXIndex));
944 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700945 item.container = c.getInt(containerIndex);
946 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100948 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100949 item.user = userManager.getUserForSerialNumber(serialNumber);
950 // Skip if user has been deleted.
951 if (item.user != null) {
952 items.add(item);
953 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700954 }
955 } catch (Exception e) {
956 items.clear();
957 } finally {
958 c.close();
959 }
960
961 return items;
962 }
963
964 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
966 */
967 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
968 final ContentResolver cr = context.getContentResolver();
969 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
970 "_id=? and (itemType=? or itemType=?)",
971 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700972 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700973
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 try {
975 if (c.moveToFirst()) {
976 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
977 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
978 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
979 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
980 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
981 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800982
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 FolderInfo folderInfo = null;
984 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700985 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
986 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400987 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700988 }
989
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 folderInfo.title = c.getString(titleIndex);
991 folderInfo.id = id;
992 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700994 folderInfo.cellX = c.getInt(cellXIndex);
995 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996
997 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700998 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999 } finally {
1000 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001001 }
1002
1003 return null;
1004 }
1005
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006 /**
1007 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1008 * cellY fields of the item. Also assigns an ID to the item.
1009 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001010 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013 item.cellX = cellX;
1014 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001015 // We store hotseat items in canonical form which is this orientation invariant position
1016 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001017 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001018 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001019 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001020 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001022 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001023
1024 final ContentValues values = new ContentValues();
1025 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001026 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001027
Michael Jurka414300a2013-08-27 15:42:35 +02001028 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001029 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001030 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001031
Jason Monk8e19cf22014-03-20 15:06:57 -04001032 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001033 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001034 public void run() {
1035 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1036 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001037
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001039 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001040 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 sBgItemsIdMap.put(item.id, item);
1042 switch (item.itemType) {
1043 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1044 sBgFolders.put(item.id, (FolderInfo) item);
1045 // Fall through
1046 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1047 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1048 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1049 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1050 sBgWorkspaceItems.add(item);
1051 } else {
1052 if (!sBgFolders.containsKey(item.container)) {
1053 // Adding an item to a folder that doesn't exist.
1054 String msg = "adding item: " + item + " to a folder that " +
1055 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001056 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001058 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001059 break;
1060 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1061 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1062 break;
1063 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001064 }
1065 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001066 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001067 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001068 }
1069
Joe Onorato9c1289c2009-08-17 11:03:03 -04001070 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001071 * Creates a new unique child id, for a given cell span across all layouts.
1072 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001073 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001075 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001077 }
1078
Sunny Goyal34942622014-08-29 17:20:55 -07001079 private static ArrayList<ItemInfo> getItemsByPackageName(
1080 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001081 ItemInfoFilter filter = new ItemInfoFilter() {
1082 @Override
1083 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1084 return cn.getPackageName().equals(pn) && info.user.equals(user);
1085 }
1086 };
Sunny Goyal34942622014-08-29 17:20:55 -07001087 return filterItemInfos(sBgItemsIdMap.values(), filter);
1088 }
1089
1090 /**
1091 * Removes all the items from the database corresponding to the specified package.
1092 */
1093 static void deletePackageFromDatabase(Context context, final String pn,
1094 final UserHandleCompat user) {
1095 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001096 }
1097
1098 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001099 * Removes the specified item from the database
1100 * @param context
1101 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001102 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001103 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001104 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1105 items.add(item);
1106 deleteItemsFromDatabase(context, items);
1107 }
1108
1109 /**
1110 * Removes the specified items from the database
1111 * @param context
1112 * @param item
1113 */
1114 static void deleteItemsFromDatabase(Context context, final ArrayList<ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001115 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001116
Michael Jurka83df1882011-08-31 20:59:26 -07001117 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001118 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001119 for (ItemInfo item : items) {
1120 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1121 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001122
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001123 // Lock on mBgLock *after* the db operation
1124 synchronized (sBgLock) {
1125 switch (item.itemType) {
1126 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1127 sBgFolders.remove(item.id);
1128 for (ItemInfo info: sBgItemsIdMap.values()) {
1129 if (info.container == item.id) {
1130 // We are deleting a folder which still contains items that
1131 // think they are contained by that folder.
1132 String msg = "deleting a folder (" + item + ") which still " +
1133 "contains items (" + info + ")";
1134 Log.e(TAG, msg);
1135 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001136 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001137 sBgWorkspaceItems.remove(item);
1138 break;
1139 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1140 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1141 sBgWorkspaceItems.remove(item);
1142 break;
1143 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1144 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1145 break;
1146 }
1147 sBgItemsIdMap.remove(item.id);
1148 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001149 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001150 }
1151 }
Michael Jurka83df1882011-08-31 20:59:26 -07001152 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001153 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001154 }
1155
1156 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001157 * Update the order of the workspace screens in the database. The array list contains
1158 * a list of screen ids in the order that they should appear.
1159 */
Winson Chungc9168342013-06-26 14:54:55 -07001160 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001161 // Log to disk
1162 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1163 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1164
Winson Chung64359a52013-07-08 17:17:08 -07001165 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 final ContentResolver cr = context.getContentResolver();
1167 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1168
1169 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001170 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 while (iter.hasNext()) {
1172 long id = iter.next();
1173 if (id < 0) {
1174 iter.remove();
1175 }
1176 }
1177
1178 Runnable r = new Runnable() {
1179 @Override
1180 public void run() {
Yura085c8532014-02-11 15:15:29 +00001181 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001182 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001183 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001184 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001185 for (int i = 0; i < count; i++) {
1186 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001187 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001188 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1189 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001190 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001191 }
Yura085c8532014-02-11 15:15:29 +00001192
1193 try {
1194 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1195 } catch (Exception ex) {
1196 throw new RuntimeException(ex);
1197 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001198
Winson Chungba9c37f2013-08-30 14:11:37 -07001199 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001200 sBgWorkspaceScreens.clear();
1201 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001202 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001203 }
1204 };
1205 runOnWorkerThread(r);
1206 }
1207
1208 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001209 * Remove the contents of the specified folder from the database
1210 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001211 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001212 final ContentResolver cr = context.getContentResolver();
1213
Michael Jurkac9d95c52011-08-29 14:03:34 -07001214 Runnable r = new Runnable() {
1215 public void run() {
1216 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001217 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001218 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001219 sBgItemsIdMap.remove(info.id);
1220 sBgFolders.remove(info.id);
1221 sBgDbIconCache.remove(info);
1222 sBgWorkspaceItems.remove(info);
1223 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001224
Michael Jurkac9d95c52011-08-29 14:03:34 -07001225 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1226 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001227 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001228 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001229 for (ItemInfo childInfo : info.contents) {
1230 sBgItemsIdMap.remove(childInfo.id);
1231 sBgDbIconCache.remove(childInfo);
1232 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001233 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001234 }
1235 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001236 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001237 }
1238
1239 /**
1240 * Set this as the current Launcher activity object for the loader.
1241 */
1242 public void initialize(Callbacks callbacks) {
1243 synchronized (mLock) {
1244 mCallbacks = new WeakReference<Callbacks>(callbacks);
1245 }
1246 }
1247
Kenny Guyed131872014-04-30 03:02:21 +01001248 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001249 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001250 int op = PackageUpdatedTask.OP_UPDATE;
1251 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1252 user));
1253 }
1254
1255 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001256 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001257 int op = PackageUpdatedTask.OP_REMOVE;
1258 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1259 user));
1260 }
1261
1262 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001263 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001264 int op = PackageUpdatedTask.OP_ADD;
1265 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1266 user));
1267 }
1268
1269 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001270 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001271 boolean replacing) {
1272 if (!replacing) {
1273 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1274 user));
1275 if (mAppsCanBeOnRemoveableStorage) {
1276 // Only rebind if we support removable storage. It catches the
1277 // case where
1278 // apps on the external sd card need to be reloaded
1279 startLoaderFromBackground();
1280 }
1281 } else {
1282 // If we are replacing then just update the packages in the list
1283 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1284 packageNames, user));
1285 }
1286 }
1287
1288 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001289 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001290 boolean replacing) {
1291 if (!replacing) {
1292 enqueuePackageUpdated(new PackageUpdatedTask(
1293 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1294 user));
1295 }
1296
1297 }
1298
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001299 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001300 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1301 * ACTION_PACKAGE_CHANGED.
1302 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001303 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001304 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001305 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001306
Joe Onorato36115782010-06-17 13:28:48 -04001307 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001308 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001309 // If we have changed locale we need to clear out the labels in all apps/workspace.
1310 forceReload();
1311 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1312 // Check if configuration change was an mcc/mnc change which would affect app resources
1313 // and we would need to clear out the labels in all apps/workspace. Same handling as
1314 // above for ACTION_LOCALE_CHANGED
1315 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001316 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001317 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001318 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001319 forceReload();
1320 }
1321 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001322 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001323 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1324 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001325 if (mCallbacks != null) {
1326 Callbacks callbacks = mCallbacks.get();
1327 if (callbacks != null) {
1328 callbacks.bindSearchablesChanged();
1329 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001330 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001331 }
1332 }
1333
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001334 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001335 resetLoadedState(true, true);
1336
Reena Lee93f824a2011-09-23 17:20:28 -07001337 // Do this here because if the launcher activity is running it will be restarted.
1338 // If it's not running startLoaderFromBackground will merely tell it that it needs
1339 // to reload.
1340 startLoaderFromBackground();
1341 }
1342
Winson Chungf0c6ae02012-03-21 16:10:31 -07001343 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1344 synchronized (mLock) {
1345 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1346 // mWorkspaceLoaded to true later
1347 stopLoaderLocked();
1348 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1349 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1350 }
1351 }
1352
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001353 /**
1354 * When the launcher is in the background, it's possible for it to miss paired
1355 * configuration changes. So whenever we trigger the loader from the background
1356 * tell the launcher that it needs to re-run the loader when it comes back instead
1357 * of doing it now.
1358 */
1359 public void startLoaderFromBackground() {
1360 boolean runLoader = false;
1361 if (mCallbacks != null) {
1362 Callbacks callbacks = mCallbacks.get();
1363 if (callbacks != null) {
1364 // Only actually run the loader if they're not paused.
1365 if (!callbacks.setLoadOnResume()) {
1366 runLoader = true;
1367 }
1368 }
1369 }
1370 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001371 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001372 }
Joe Onorato36115782010-06-17 13:28:48 -04001373 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001374
Reena Lee93f824a2011-09-23 17:20:28 -07001375 // If there is already a loader task running, tell it to stop.
1376 // returns true if isLaunching() was true on the old task
1377 private boolean stopLoaderLocked() {
1378 boolean isLaunching = false;
1379 LoaderTask oldTask = mLoaderTask;
1380 if (oldTask != null) {
1381 if (oldTask.isLaunching()) {
1382 isLaunching = true;
1383 }
1384 oldTask.stopLocked();
1385 }
1386 return isLaunching;
1387 }
1388
Adam Cohen1a85c582014-09-30 09:48:49 -07001389 public boolean isCurrentCallbacks(Callbacks callbacks) {
1390 return (mCallbacks != null && mCallbacks.get() == callbacks);
1391 }
1392
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001393 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001394 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1395 }
1396
1397 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001398 synchronized (mLock) {
1399 if (DEBUG_LOADERS) {
1400 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1401 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 // Clear any deferred bind-runnables from the synchronized load process
1404 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001405 synchronized (mDeferredBindRunnables) {
1406 mDeferredBindRunnables.clear();
1407 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001408
Joe Onorato36115782010-06-17 13:28:48 -04001409 // Don't bother to start the thread if we know it's not going to do anything
1410 if (mCallbacks != null && mCallbacks.get() != null) {
1411 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001412 // also, don't downgrade isLaunching if we're already running
1413 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001414 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001415 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1416 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001417 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1418 } else {
1419 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1420 sWorker.post(mLoaderTask);
1421 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001422 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001423 }
1424 }
1425
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001426 void bindRemainingSynchronousPages() {
1427 // Post the remaining side pages to be loaded
1428 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001429 Runnable[] deferredBindRunnables = null;
1430 synchronized (mDeferredBindRunnables) {
1431 deferredBindRunnables = mDeferredBindRunnables.toArray(
1432 new Runnable[mDeferredBindRunnables.size()]);
1433 mDeferredBindRunnables.clear();
1434 }
1435 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001436 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001437 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001438 }
1439 }
1440
Joe Onorato36115782010-06-17 13:28:48 -04001441 public void stopLoader() {
1442 synchronized (mLock) {
1443 if (mLoaderTask != null) {
1444 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001445 }
1446 }
Joe Onorato36115782010-06-17 13:28:48 -04001447 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001448
Winson Chung76828c82013-08-19 15:43:29 -07001449 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1450 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1451 final ContentResolver contentResolver = context.getContentResolver();
1452 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1453 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1454 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1455
1456 try {
1457 final int idIndex = sc.getColumnIndexOrThrow(
1458 LauncherSettings.WorkspaceScreens._ID);
1459 final int rankIndex = sc.getColumnIndexOrThrow(
1460 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1461 while (sc.moveToNext()) {
1462 try {
1463 long screenId = sc.getLong(idIndex);
1464 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001465 orderedScreens.put(rank, screenId);
1466 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001467 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001468 }
1469 }
1470 } finally {
1471 sc.close();
1472 }
Winson Chunga90303b2013-11-15 13:05:06 -08001473
1474 // Log to disk
1475 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1476 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1477 for (Integer i : orderedScreens.keySet()) {
1478 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1479 }
1480 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1481 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001482 return orderedScreens;
1483 }
1484
Michael Jurkac57b7a82011-08-09 22:02:20 -07001485 public boolean isAllAppsLoaded() {
1486 return mAllAppsLoaded;
1487 }
1488
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 boolean isLoadingWorkspace() {
1490 synchronized (mLock) {
1491 if (mLoaderTask != null) {
1492 return mLoaderTask.isLoadingWorkspace();
1493 }
1494 }
1495 return false;
1496 }
1497
Joe Onorato36115782010-06-17 13:28:48 -04001498 /**
1499 * Runnable for the thread that loads the contents of the launcher:
1500 * - workspace icons
1501 * - widgets
1502 * - all apps icons
1503 */
1504 private class LoaderTask implements Runnable {
1505 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001506 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001507 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001508 private boolean mStopped;
1509 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001510 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001511
Winson Chungc3eecff2011-07-11 17:44:15 -07001512 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001513
Dan Sandlerd5024042014-01-09 15:01:33 -05001514 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001515 mContext = context;
1516 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001517 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001518 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001519 }
1520
Joe Onorato36115782010-06-17 13:28:48 -04001521 boolean isLaunching() {
1522 return mIsLaunching;
1523 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001524
Winson Chung36a62fe2012-05-06 18:04:42 -07001525 boolean isLoadingWorkspace() {
1526 return mIsLoadingAndBindingWorkspace;
1527 }
1528
Winson Chungc763c4e2013-07-19 13:49:06 -07001529 /** Returns whether this is an upgrade path */
1530 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001531 mIsLoadingAndBindingWorkspace = true;
1532
Joe Onorato36115782010-06-17 13:28:48 -04001533 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001534 if (DEBUG_LOADERS) {
1535 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001536 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001537
Winson Chungc763c4e2013-07-19 13:49:06 -07001538 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001539 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001540 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001541 synchronized (LoaderTask.this) {
1542 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001543 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001544 }
1545 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001546 }
1547 }
1548
Joe Onorato36115782010-06-17 13:28:48 -04001549 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001550 bindWorkspace(-1, isUpgradePath);
1551 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001552 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001553
Joe Onorato36115782010-06-17 13:28:48 -04001554 private void waitForIdle() {
1555 // Wait until the either we're stopped or the other threads are done.
1556 // This way we don't start loading all apps until the workspace has settled
1557 // down.
1558 synchronized (LoaderTask.this) {
1559 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001560
Joe Onorato36115782010-06-17 13:28:48 -04001561 mHandler.postIdle(new Runnable() {
1562 public void run() {
1563 synchronized (LoaderTask.this) {
1564 mLoadAndBindStepFinished = true;
1565 if (DEBUG_LOADERS) {
1566 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001567 }
Joe Onorato36115782010-06-17 13:28:48 -04001568 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001569 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001570 }
Joe Onorato36115782010-06-17 13:28:48 -04001571 });
1572
Michael Jurkac7700af2013-05-14 20:17:58 +02001573 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001574 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001575 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1576 // wait no longer than 1sec at a time
1577 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001578 } catch (InterruptedException ex) {
1579 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001580 }
1581 }
Joe Onorato36115782010-06-17 13:28:48 -04001582 if (DEBUG_LOADERS) {
1583 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001584 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001585 + "ms for previous step to finish binding");
1586 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001587 }
Joe Onorato36115782010-06-17 13:28:48 -04001588 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001589
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001590 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001591 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001592 // Ensure that we have a valid page index to load synchronously
1593 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1594 "valid page index");
1595 }
1596 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1597 // Ensure that we don't try and bind a specified page when the pages have not been
1598 // loaded already (we should load everything asynchronously in that case)
1599 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1600 }
1601 synchronized (mLock) {
1602 if (mIsLoaderTaskRunning) {
1603 // Ensure that we are never running the background loading at this point since
1604 // we also touch the background collections
1605 throw new RuntimeException("Error! Background loading is already running");
1606 }
1607 }
1608
1609 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1610 // data structures, we can't allow any other thread to touch that data, but because
1611 // this call is synchronous, we can get away with not locking).
1612
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001613 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001614 // operations from the previous activity. We need to ensure that all queued operations
1615 // are executed before any synchronous binding work is done.
1616 mHandler.flush();
1617
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001618 // Divide the set of loaded items into those that we are binding synchronously, and
1619 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001620 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001621 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1622 // arise from that.
1623 onlyBindAllApps();
1624 }
1625
Joe Onorato36115782010-06-17 13:28:48 -04001626 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001627 boolean isUpgrade = false;
1628
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001629 synchronized (mLock) {
1630 mIsLoaderTaskRunning = true;
1631 }
Joe Onorato36115782010-06-17 13:28:48 -04001632 // Optimize for end-user experience: if the Launcher is up and // running with the
1633 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1634 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001635 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001636 // Elevate priority when Home launches for the first time to avoid
1637 // starving at boot time. Staring at a blank home is not cool.
1638 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001639 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1640 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001641 android.os.Process.setThreadPriority(mIsLaunching
1642 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1643 }
Winson Chung64359a52013-07-08 17:17:08 -07001644 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001645 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001646
Joe Onorato36115782010-06-17 13:28:48 -04001647 if (mStopped) {
1648 break keep_running;
1649 }
1650
1651 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1652 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001653 synchronized (mLock) {
1654 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001655 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001656 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657 }
1658 }
Joe Onorato36115782010-06-17 13:28:48 -04001659 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001660
1661 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001662 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1663 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001664
1665 // Restore the default thread priority after we are done loading items
1666 synchronized (mLock) {
1667 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1668 }
Joe Onorato36115782010-06-17 13:28:48 -04001669 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001670
Winson Chungaac01e12011-08-17 10:37:13 -07001671 // Update the saved icons if necessary
1672 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001673 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001674 for (Object key : sBgDbIconCache.keySet()) {
1675 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1676 }
1677 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001678 }
Winson Chungaac01e12011-08-17 10:37:13 -07001679
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001680 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001681 // Ensure that all the applications that are in the system are
1682 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001683 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001684 verifyApplications();
1685 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001686 }
1687
Joe Onorato36115782010-06-17 13:28:48 -04001688 // Clear out this reference, otherwise we end up holding it until all of the
1689 // callback runnables are done.
1690 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001691
Joe Onorato36115782010-06-17 13:28:48 -04001692 synchronized (mLock) {
1693 // If we are still the last one to be scheduled, remove ourselves.
1694 if (mLoaderTask == this) {
1695 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001696 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001697 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001698 }
Joe Onorato36115782010-06-17 13:28:48 -04001699 }
1700
1701 public void stopLocked() {
1702 synchronized (LoaderTask.this) {
1703 mStopped = true;
1704 this.notify();
1705 }
1706 }
1707
1708 /**
1709 * Gets the callbacks object. If we've been stopped, or if the launcher object
1710 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1711 * object that was around when the deferred message was scheduled, and if there's
1712 * a new Callbacks object around then also return null. This will save us from
1713 * calling onto it with data that will be ignored.
1714 */
1715 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1716 synchronized (mLock) {
1717 if (mStopped) {
1718 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001719 }
Joe Onorato36115782010-06-17 13:28:48 -04001720
1721 if (mCallbacks == null) {
1722 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001723 }
Joe Onorato36115782010-06-17 13:28:48 -04001724
1725 final Callbacks callbacks = mCallbacks.get();
1726 if (callbacks != oldCallbacks) {
1727 return null;
1728 }
1729 if (callbacks == null) {
1730 Log.w(TAG, "no mCallbacks");
1731 return null;
1732 }
1733
1734 return callbacks;
1735 }
1736 }
1737
Winson Chungc763c4e2013-07-19 13:49:06 -07001738 private void verifyApplications() {
1739 final Context context = mApp.getContext();
1740
1741 // Cross reference all the applications in our apps list with items in the workspace
1742 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001743 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001744 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001745 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001746 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001747 if (tmpInfos.isEmpty()) {
1748 // We are missing an application icon, so add this to the workspace
1749 added.add(app);
1750 // This is a rare event, so lets log it
1751 Log.e(TAG, "Missing Application on load: " + app);
1752 }
1753 }
1754 }
1755 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001756 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001757 }
1758 }
1759
Joe Onorato36115782010-06-17 13:28:48 -04001760 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001761 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001762 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001763 LauncherAppState app = LauncherAppState.getInstance();
1764 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001765 final int countX = (int) grid.numColumns;
1766 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001767
Adam Cohendcd297f2013-06-18 13:13:40 -07001768 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001769 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001770 // Return early if we detect that an item is under the hotseat button
1771 if (mCallbacks == null ||
1772 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001773 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001774 Log.e(TAG, "Error loading shortcut into hotseat " + item
1775 + " into position (" + item.screenId + ":" + item.cellX + ","
1776 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001777 return false;
1778 }
1779
Dan Sandler295ae182013-12-10 16:05:47 -05001780 final ItemInfo[][] hotseatItems =
1781 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1782
Adam Cohenae4409d2013-11-26 10:34:59 -08001783 if (item.screenId >= grid.numHotseatIcons) {
1784 Log.e(TAG, "Error loading shortcut " + item
1785 + " into hotseat position " + item.screenId
1786 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1787 + ")");
1788 return false;
1789 }
1790
Dan Sandler295ae182013-12-10 16:05:47 -05001791 if (hotseatItems != null) {
1792 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001793 Log.e(TAG, "Error loading shortcut into hotseat " + item
1794 + " into position (" + item.screenId + ":" + item.cellX + ","
1795 + item.cellY + ") occupied by "
1796 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1797 [(int) item.screenId][0]);
1798 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001799 } else {
1800 hotseatItems[(int) item.screenId][0] = item;
1801 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001802 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001803 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001804 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001805 items[(int) item.screenId][0] = item;
1806 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001807 return true;
1808 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001809 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1810 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001811 return true;
1812 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001813
Adam Cohendcd297f2013-06-18 13:13:40 -07001814 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001815 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001816 occupied.put(item.screenId, items);
1817 }
1818
Dan Sandler295ae182013-12-10 16:05:47 -05001819 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001820 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1821 item.cellX < 0 || item.cellY < 0 ||
1822 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1823 Log.e(TAG, "Error loading shortcut " + item
1824 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1825 + item.cellX + "," + item.cellY
1826 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1827 return false;
1828 }
1829
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001830 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001831 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1832 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001834 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001835 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001836 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001837 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001838 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001839 return false;
1840 }
1841 }
1842 }
1843 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1844 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001845 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001846 }
1847 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001848
Joe Onorato36115782010-06-17 13:28:48 -04001849 return true;
1850 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001851
Winson Chungba9c37f2013-08-30 14:11:37 -07001852 /** Clears all the sBg data structures */
1853 private void clearSBgDataStructures() {
1854 synchronized (sBgLock) {
1855 sBgWorkspaceItems.clear();
1856 sBgAppWidgets.clear();
1857 sBgFolders.clear();
1858 sBgItemsIdMap.clear();
1859 sBgDbIconCache.clear();
1860 sBgWorkspaceScreens.clear();
1861 }
1862 }
1863
Dan Sandlerd5024042014-01-09 15:01:33 -05001864 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001865 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001866 // Log to disk
1867 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1868
Joe Onorato36115782010-06-17 13:28:48 -04001869 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001870
Joe Onorato36115782010-06-17 13:28:48 -04001871 final Context context = mContext;
1872 final ContentResolver contentResolver = context.getContentResolver();
1873 final PackageManager manager = context.getPackageManager();
1874 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1875 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001876 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1877 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001878 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001879
Winson Chung892c74d2013-08-22 16:15:50 -07001880 LauncherAppState app = LauncherAppState.getInstance();
1881 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1882 int countX = (int) grid.numColumns;
1883 int countY = (int) grid.numRows;
1884
Dan Sandlerd5024042014-01-09 15:01:33 -05001885 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1886 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1887 LauncherAppState.getLauncherProvider().deleteDatabase();
1888 }
1889
1890 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1891 // append the user's Launcher2 shortcuts
1892 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1893 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1894 } else {
1895 // Make sure the default workspace is loaded
1896 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001897 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001898 }
Adam Cohene25af792013-06-06 23:08:25 -07001899
Adam Cohen71483f42014-05-15 14:04:01 -07001900 // This code path is for our old migration code and should no longer be exercised
1901 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001902
Winson Chung9f9f00b2013-11-15 13:27:00 -08001903 // Log to disk
1904 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001905
Winson Chung2abf94d2012-07-18 18:16:38 -07001906 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001907 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001908 final HashSet<String> installingPkgs = PackageInstallerCompat
1909 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001910
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001911 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001912 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001913 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001914 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001915 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001916
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001917 // +1 for the hotseat (it can be larger than the workspace)
1918 // Load workspace in reverse order to ensure that latest items are loaded first (and
1919 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001920 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001921
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001922 try {
1923 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1924 final int intentIndex = c.getColumnIndexOrThrow
1925 (LauncherSettings.Favorites.INTENT);
1926 final int titleIndex = c.getColumnIndexOrThrow
1927 (LauncherSettings.Favorites.TITLE);
1928 final int iconTypeIndex = c.getColumnIndexOrThrow(
1929 LauncherSettings.Favorites.ICON_TYPE);
1930 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1931 final int iconPackageIndex = c.getColumnIndexOrThrow(
1932 LauncherSettings.Favorites.ICON_PACKAGE);
1933 final int iconResourceIndex = c.getColumnIndexOrThrow(
1934 LauncherSettings.Favorites.ICON_RESOURCE);
1935 final int containerIndex = c.getColumnIndexOrThrow(
1936 LauncherSettings.Favorites.CONTAINER);
1937 final int itemTypeIndex = c.getColumnIndexOrThrow(
1938 LauncherSettings.Favorites.ITEM_TYPE);
1939 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1940 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001941 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1942 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 final int screenIndex = c.getColumnIndexOrThrow(
1944 LauncherSettings.Favorites.SCREEN);
1945 final int cellXIndex = c.getColumnIndexOrThrow
1946 (LauncherSettings.Favorites.CELLX);
1947 final int cellYIndex = c.getColumnIndexOrThrow
1948 (LauncherSettings.Favorites.CELLY);
1949 final int spanXIndex = c.getColumnIndexOrThrow
1950 (LauncherSettings.Favorites.SPANX);
1951 final int spanYIndex = c.getColumnIndexOrThrow(
1952 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001953 final int restoredIndex = c.getColumnIndexOrThrow(
1954 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001955 final int profileIdIndex = c.getColumnIndexOrThrow(
1956 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001957 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1958 //final int displayModeIndex = c.getColumnIndexOrThrow(
1959 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001960
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001961 ShortcutInfo info;
1962 String intentDescription;
1963 LauncherAppWidgetInfo appWidgetInfo;
1964 int container;
1965 long id;
1966 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001967 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001968
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001969 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001970 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001971 try {
1972 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001973 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001974 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001975
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001976 switch (itemType) {
1977 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1978 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001979 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001980 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001981 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001982 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001983 int promiseType = c.getInt(restoredIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001984 if (user == null) {
1985 // User has been deleted remove the item.
1986 itemsToRemove.add(id);
1987 continue;
1988 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001989 try {
1990 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001991 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001992 if (cn != null && cn.getPackageName() != null) {
1993 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1994 cn.getPackageName(), user);
1995 boolean validComponent = validPkg &&
1996 launcherApps.isActivityEnabledForProfile(cn, user);
1997
1998 if (validComponent) {
1999 if (restored) {
2000 // no special handling necessary for this item
2001 restoredRows.add(id);
2002 restored = false;
2003 }
2004 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07002005 intent = null;
2006 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2007 // We allow auto install apps to have their intent
2008 // updated after an install.
2009 intent = manager.getLaunchIntentForPackage(
2010 cn.getPackageName());
2011 if (intent != null) {
2012 ContentValues values = new ContentValues();
2013 values.put(LauncherSettings.Favorites.INTENT,
2014 intent.toUri(0));
2015 String where = BaseColumns._ID + "= ?";
2016 String[] args = {Long.toString(id)};
2017 contentResolver.update(contentUri, values, where, args);
2018 }
2019 }
2020
2021 if (intent == null) {
2022 // The app is installed but the component is no
2023 // longer available.
2024 Launcher.addDumpLog(TAG,
2025 "Invalid component removed: " + cn, true);
2026 itemsToRemove.add(id);
2027 continue;
2028 } else {
2029 // no special handling necessary for this item
2030 restoredRows.add(id);
2031 restored = false;
2032 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002033 } else if (restored) {
2034 // Package is not yet available but might be
2035 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002036 Launcher.addDumpLog(TAG,
2037 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002038
2039 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2040 // Restore has started once.
2041 } else if (installingPkgs.contains(cn.getPackageName())) {
2042 // App restore has started. Update the flag
2043 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2044 ContentValues values = new ContentValues();
2045 values.put(LauncherSettings.Favorites.RESTORED,
2046 promiseType);
2047 String where = BaseColumns._ID + "= ?";
2048 String[] args = {Long.toString(id)};
2049 contentResolver.update(contentUri, values, where, args);
2050
2051 } else if (REMOVE_UNRESTORED_ICONS) {
2052 Launcher.addDumpLog(TAG,
2053 "Unrestored package removed: " + cn, true);
2054 itemsToRemove.add(id);
2055 continue;
2056 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002057 } else if (isSdCardReady) {
2058 // Do not wait for external media load anymore.
2059 // Log the invalid package, and remove it
2060 Launcher.addDumpLog(TAG,
2061 "Invalid package removed: " + cn, true);
2062 itemsToRemove.add(id);
Chris Wrenf4d08112014-01-16 18:13:56 -05002063 continue;
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002064 } else {
2065 // SdCard is not ready yet. Package might get available,
2066 // once it is ready.
2067 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2068 + " (check again later)", true);
2069 HashSet<String> pkgs = sPendingPackages.get(user);
2070 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002071 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002072 sPendingPackages.put(user, pkgs);
2073 }
2074 pkgs.add(cn.getPackageName());
2075 allowMissingTarget = true;
2076 // Add the icon on the workspace anyway.
Winson Chungee055712013-07-30 14:46:24 -07002077 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002078 } else if (cn == null) {
2079 // For shortcuts with no component, keep them as they are
2080 restoredRows.add(id);
2081 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002082 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002084 Launcher.addDumpLog(TAG,
2085 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 continue;
2087 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002088
Chris Wrenf4d08112014-01-16 18:13:56 -05002089 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002090 if (user.equals(UserHandleCompat.myUserHandle())) {
2091 Launcher.addDumpLog(TAG,
2092 "constructing info for partially restored package",
2093 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002094 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002095 intent = getRestoredItemIntent(c, context, intent);
2096 } else {
2097 // Don't restore items for other profiles.
2098 itemsToRemove.add(id);
2099 continue;
2100 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002101 } else if (itemType ==
2102 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002103 info = getShortcutInfo(manager, intent, user, context, c,
2104 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 } else {
2106 info = getShortcutInfo(c, context, iconTypeIndex,
2107 iconPackageIndex, iconResourceIndex, iconIndex,
2108 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002109
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 // App shortcuts that used to be automatically added to Launcher
2111 // didn't always have the correct intent flags set, so do that
2112 // here
2113 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002114 intent.getCategories() != null &&
2115 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002116 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002117 intent.addFlags(
2118 Intent.FLAG_ACTIVITY_NEW_TASK |
2119 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2120 }
Michael Jurka96879562012-03-22 05:54:33 -07002121 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002122
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002123 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002124 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002125 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 container = c.getInt(containerIndex);
2127 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002128 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 info.cellX = c.getInt(cellXIndex);
2130 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002131 info.spanX = 1;
2132 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002133 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyalc5c60ad2014-07-14 12:02:01 -07002134 info.isDisabled = isSafeMode
2135 && !Utilities.isSystemApp(context, intent);
Adam Cohenae4409d2013-11-26 10:34:59 -08002136
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002138 deleteOnInvalidPlacement.set(false);
2139 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
2140 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002141 itemsToRemove.add(id);
2142 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143 break;
2144 }
2145
2146 switch (container) {
2147 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2148 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2149 sBgWorkspaceItems.add(info);
2150 break;
2151 default:
2152 // Item is in a user folder
2153 FolderInfo folderInfo =
2154 findOrMakeFolder(sBgFolders, container);
2155 folderInfo.add(info);
2156 break;
2157 }
2158 sBgItemsIdMap.put(info.id, info);
2159
2160 // now that we've loaded everthing re-save it with the
2161 // icon in case it disappears somehow.
2162 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002163 } else {
2164 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002165 }
2166 break;
2167
2168 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2169 id = c.getLong(idIndex);
2170 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2171
2172 folderInfo.title = c.getString(titleIndex);
2173 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002174 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002175 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002176 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002177 folderInfo.cellX = c.getInt(cellXIndex);
2178 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002179 folderInfo.spanX = 1;
2180 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002181
Daniel Sandler8802e962010-05-26 16:28:16 -04002182 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002183 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002184 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002185 deleteOnInvalidPlacement)) {
2186 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002187 itemsToRemove.add(id);
2188 }
Daniel Sandler8802e962010-05-26 16:28:16 -04002189 break;
2190 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002191
Joe Onorato9c1289c2009-08-17 11:03:03 -04002192 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002193 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2194 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2195 sBgWorkspaceItems.add(folderInfo);
2196 break;
Joe Onorato36115782010-06-17 13:28:48 -04002197 }
Joe Onorato17a89222011-02-08 17:26:11 -08002198
Chris Wrenf4d08112014-01-16 18:13:56 -05002199 if (restored) {
2200 // no special handling required for restored folders
2201 restoredRows.add(id);
2202 }
2203
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002204 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2205 sBgFolders.put(folderInfo.id, folderInfo);
2206 break;
2207
2208 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2209 // Read all Launcher-specific widget details
2210 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002211 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002212 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002213 final ComponentName component =
2214 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002215
Sunny Goyal651077b2014-06-30 14:15:31 -07002216 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002217 final boolean isIdValid = (restoreStatus &
2218 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002219
Sunny Goyalff572272014-07-23 13:58:07 -07002220 final boolean wasProviderReady = (restoreStatus &
2221 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002222
Sunny Goyalff572272014-07-23 13:58:07 -07002223 final AppWidgetProviderInfo provider = isIdValid
2224 ? widgets.getAppWidgetInfo(appWidgetId)
2225 : findAppWidgetProviderInfoWithComponent(context, component);
2226
2227 final boolean isProviderReady = isValidProvider(provider);
2228 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002229 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002230 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002231 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002232 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002233 itemsToRemove.add(id);
2234 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002235 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002236 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2237 provider.provider);
2238 int[] minSpan =
2239 Launcher.getMinSpanForWidget(context, provider);
2240 appWidgetInfo.minSpanX = minSpan[0];
2241 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002242
2243 int status = restoreStatus;
2244 if (!wasProviderReady) {
2245 // If provider was not previously ready, update the
2246 // status and UI flag.
2247
2248 // Id would be valid only if the widget restore broadcast was received.
2249 if (isIdValid) {
2250 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2251 } else {
2252 status &= ~LauncherAppWidgetInfo
2253 .FLAG_PROVIDER_NOT_READY;
2254 }
2255 }
2256 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002257 } else {
2258 Log.v(TAG, "Widget restore pending id=" + id
2259 + " appWidgetId=" + appWidgetId
2260 + " status =" + restoreStatus);
2261 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002262 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002263 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002264
2265 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2266 // Restore has started once.
2267 } else if (installingPkgs.contains(component.getPackageName())) {
2268 // App restore has started. Update the flag
2269 appWidgetInfo.restoreStatus |=
2270 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
2271 } else if (REMOVE_UNRESTORED_ICONS) {
2272 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002273 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002274 itemsToRemove.add(id);
2275 continue;
2276 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002277 }
Sunny Goyalff572272014-07-23 13:58:07 -07002278
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002279 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002280 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 appWidgetInfo.cellX = c.getInt(cellXIndex);
2282 appWidgetInfo.cellY = c.getInt(cellYIndex);
2283 appWidgetInfo.spanX = c.getInt(spanXIndex);
2284 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002285
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002286 container = c.getInt(containerIndex);
2287 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2288 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2289 Log.e(TAG, "Widget found where container != " +
2290 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2291 continue;
2292 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293
Adam Cohene25af792013-06-06 23:08:25 -07002294 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002295 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08002296 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07002297 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08002298 deleteOnInvalidPlacement)) {
2299 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07002300 itemsToRemove.add(id);
2301 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002302 break;
2303 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002304
Sunny Goyal94485362014-09-18 16:13:58 -07002305 String providerName = appWidgetInfo.providerName.flattenToString();
2306 if (!providerName.equals(savedProvider) ||
2307 (appWidgetInfo.restoreStatus != restoreStatus)) {
2308 ContentValues values = new ContentValues();
2309 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2310 providerName);
2311 values.put(LauncherSettings.Favorites.RESTORED,
2312 appWidgetInfo.restoreStatus);
2313 String where = BaseColumns._ID + "= ?";
2314 String[] args = {Long.toString(id)};
2315 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002316 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002317 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2318 sBgAppWidgets.add(appWidgetInfo);
2319 }
Joe Onorato36115782010-06-17 13:28:48 -04002320 break;
2321 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002322 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002323 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002324 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002325 }
2326 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002327 if (c != null) {
2328 c.close();
2329 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002330 }
2331
Winson Chungba9c37f2013-08-30 14:11:37 -07002332 // Break early if we've stopped loading
2333 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002334 clearSBgDataStructures();
2335 return false;
2336 }
2337
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002338 if (itemsToRemove.size() > 0) {
2339 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002340 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002341 // Remove dead items
2342 for (long id : itemsToRemove) {
2343 if (DEBUG_LOADERS) {
2344 Log.d(TAG, "Removed id = " + id);
2345 }
2346 // Don't notify content observers
2347 try {
2348 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2349 null, null);
2350 } catch (RemoteException e) {
2351 Log.w(TAG, "Could not remove id = " + id);
2352 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002353 }
2354 }
2355
Chris Wrenf4d08112014-01-16 18:13:56 -05002356 if (restoredRows.size() > 0) {
2357 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002358 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002359 // Update restored items that no longer require special handling
2360 try {
2361 StringBuilder selectionBuilder = new StringBuilder();
2362 selectionBuilder.append(LauncherSettings.Favorites._ID);
2363 selectionBuilder.append(" IN (");
2364 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2365 selectionBuilder.append(")");
2366 ContentValues values = new ContentValues();
2367 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002368 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002369 values, selectionBuilder.toString(), null);
2370 } catch (RemoteException e) {
2371 Log.w(TAG, "Could not update restored rows");
2372 }
2373 }
2374
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002375 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2376 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002377 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002378 null, sWorker);
2379 }
2380
Winson Chungc763c4e2013-07-19 13:49:06 -07002381 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002382 long maxScreenId = 0;
2383 // If we're importing we use the old screen order.
2384 for (ItemInfo item: sBgItemsIdMap.values()) {
2385 long screenId = item.screenId;
2386 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2387 !sBgWorkspaceScreens.contains(screenId)) {
2388 sBgWorkspaceScreens.add(screenId);
2389 if (screenId > maxScreenId) {
2390 maxScreenId = screenId;
2391 }
2392 }
2393 }
2394 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002395 // Log to disk
2396 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2397 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2398 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002399
Michael Jurka414300a2013-08-27 15:42:35 +02002400 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002401 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002402
2403 // Update the max item id after we load an old db
2404 long maxItemId = 0;
2405 // If we're importing we use the old screen order.
2406 for (ItemInfo item: sBgItemsIdMap.values()) {
2407 maxItemId = Math.max(maxItemId, item.id);
2408 }
Michael Jurka414300a2013-08-27 15:42:35 +02002409 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002410 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002411 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2412 for (Integer i : orderedScreens.keySet()) {
2413 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002414 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002415 // Log to disk
2416 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2417 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002418
2419 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002420 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002421 for (ItemInfo item: sBgItemsIdMap.values()) {
2422 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002423 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2424 unusedScreens.contains(screenId)) {
2425 unusedScreens.remove(screenId);
2426 }
2427 }
2428
2429 // If there are any empty screens remove them, and update.
2430 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002431 // Log to disk
2432 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2433 TextUtils.join(", ", unusedScreens), true);
2434
Winson Chung933bae62013-08-29 11:42:30 -07002435 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002436 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2437 }
2438 }
2439
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 if (DEBUG_LOADERS) {
2441 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2442 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002443 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002444 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002445 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002446
Daniel Sandler566da102013-06-25 23:43:45 -04002447 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002448 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002449 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002450 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 line += " | ";
2452 }
Winson Chung892c74d2013-08-22 16:15:50 -07002453 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002454 ItemInfo[][] screen = occupied.get(screenId);
2455 if (x < screen.length && y < screen[x].length) {
2456 line += (screen[x][y] != null) ? "#" : ".";
2457 } else {
2458 line += "!";
2459 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002460 }
Joe Onorato36115782010-06-17 13:28:48 -04002461 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002462 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002463 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002464 }
Joe Onorato36115782010-06-17 13:28:48 -04002465 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002466 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002467 }
2468
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002469 /** Filters the set of items who are directly or indirectly (via another container) on the
2470 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002471 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002472 ArrayList<ItemInfo> allWorkspaceItems,
2473 ArrayList<ItemInfo> currentScreenItems,
2474 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002475 // Purge any null ItemInfos
2476 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2477 while (iter.hasNext()) {
2478 ItemInfo i = iter.next();
2479 if (i == null) {
2480 iter.remove();
2481 }
2482 }
2483
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484 // Order the set of items by their containers first, this allows use to walk through the
2485 // list sequentially, build up a list of containers that are in the specified screen,
2486 // as well as all items in those containers.
2487 Set<Long> itemsOnScreen = new HashSet<Long>();
2488 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2489 @Override
2490 public int compare(ItemInfo lhs, ItemInfo rhs) {
2491 return (int) (lhs.container - rhs.container);
2492 }
2493 });
2494 for (ItemInfo info : allWorkspaceItems) {
2495 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002496 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002497 currentScreenItems.add(info);
2498 itemsOnScreen.add(info.id);
2499 } else {
2500 otherScreenItems.add(info);
2501 }
2502 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2503 currentScreenItems.add(info);
2504 itemsOnScreen.add(info.id);
2505 } else {
2506 if (itemsOnScreen.contains(info.container)) {
2507 currentScreenItems.add(info);
2508 itemsOnScreen.add(info.id);
2509 } else {
2510 otherScreenItems.add(info);
2511 }
2512 }
2513 }
2514 }
2515
2516 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002517 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002518 ArrayList<LauncherAppWidgetInfo> appWidgets,
2519 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2520 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521
2522 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002523 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002524 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002525 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526 currentScreenWidgets.add(widget);
2527 } else {
2528 otherScreenWidgets.add(widget);
2529 }
2530 }
2531 }
2532
2533 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002534 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002535 HashMap<Long, ItemInfo> itemsIdMap,
2536 HashMap<Long, FolderInfo> folders,
2537 HashMap<Long, FolderInfo> currentScreenFolders,
2538 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539
2540 for (long id : folders.keySet()) {
2541 ItemInfo info = itemsIdMap.get(id);
2542 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002543 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002545 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002546 currentScreenFolders.put(id, folder);
2547 } else {
2548 otherScreenFolders.put(id, folder);
2549 }
2550 }
2551 }
2552
2553 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2554 * right) */
2555 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002556 final LauncherAppState app = LauncherAppState.getInstance();
2557 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 // XXX: review this
2559 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002560 @Override
2561 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002562 int cellCountX = (int) grid.numColumns;
2563 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002564 int screenOffset = cellCountX * cellCountY;
2565 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002566 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002567 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002568 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002569 rhs.cellY * cellCountX + rhs.cellX);
2570 return (int) (lr - rr);
2571 }
2572 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002573 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002574
Adam Cohendcd297f2013-06-18 13:13:40 -07002575 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2576 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002577 final Runnable r = new Runnable() {
2578 @Override
2579 public void run() {
2580 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2581 if (callbacks != null) {
2582 callbacks.bindScreens(orderedScreens);
2583 }
2584 }
2585 };
2586 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2587 }
2588
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002589 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2590 final ArrayList<ItemInfo> workspaceItems,
2591 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2592 final HashMap<Long, FolderInfo> folders,
2593 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002594
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002595 final boolean postOnMainThread = (deferredBindRunnables != null);
2596
2597 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002598 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002599 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002600 final int start = i;
2601 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002602 final Runnable r = new Runnable() {
2603 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002604 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002605 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002606 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002607 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2608 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002609 }
2610 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 };
2612 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002613 synchronized (deferredBindRunnables) {
2614 deferredBindRunnables.add(r);
2615 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002617 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002618 }
Joe Onorato36115782010-06-17 13:28:48 -04002619 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002620
2621 // Bind the folders
2622 if (!folders.isEmpty()) {
2623 final Runnable r = new Runnable() {
2624 public void run() {
2625 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2626 if (callbacks != null) {
2627 callbacks.bindFolders(folders);
2628 }
2629 }
2630 };
2631 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002632 synchronized (deferredBindRunnables) {
2633 deferredBindRunnables.add(r);
2634 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002635 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002636 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002637 }
2638 }
2639
2640 // Bind the widgets, one at a time
2641 N = appWidgets.size();
2642 for (int i = 0; i < N; i++) {
2643 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2644 final Runnable r = new Runnable() {
2645 public void run() {
2646 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2647 if (callbacks != null) {
2648 callbacks.bindAppWidget(widget);
2649 }
2650 }
2651 };
2652 if (postOnMainThread) {
2653 deferredBindRunnables.add(r);
2654 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002655 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002656 }
2657 }
2658 }
2659
2660 /**
2661 * Binds all loaded data to actual views on the main thread.
2662 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002663 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002664 final long t = SystemClock.uptimeMillis();
2665 Runnable r;
2666
2667 // Don't use these two variables in any of the callback runnables.
2668 // Otherwise we hold a reference to them.
2669 final Callbacks oldCallbacks = mCallbacks.get();
2670 if (oldCallbacks == null) {
2671 // This launcher has exited and nobody bothered to tell us. Just bail.
2672 Log.w(TAG, "LoaderTask running with no launcher");
2673 return;
2674 }
2675
Winson Chung9b9fb962013-11-15 15:39:34 -08002676 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002677 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2678 ArrayList<LauncherAppWidgetInfo> appWidgets =
2679 new ArrayList<LauncherAppWidgetInfo>();
2680 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2681 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002682 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002683 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 workspaceItems.addAll(sBgWorkspaceItems);
2685 appWidgets.addAll(sBgAppWidgets);
2686 folders.putAll(sBgFolders);
2687 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002688 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002689 }
2690
Derek Prothro7aff3992013-12-10 14:00:37 -05002691 final boolean isLoadingSynchronously =
2692 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002693 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002694 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002695 if (currScreen >= orderedScreenIds.size()) {
2696 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002697 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002698 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002699 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002700 final long currentScreenId = currentScreen < 0
2701 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002702
2703 // Load all the items that are on the current page first (and in the process, unbind
2704 // all the existing workspace items before we call startBinding() below.
2705 unbindWorkspaceItemsOnMainThread();
2706
2707 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002708 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2709 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2710 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2711 new ArrayList<LauncherAppWidgetInfo>();
2712 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2713 new ArrayList<LauncherAppWidgetInfo>();
2714 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2715 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2716
Winson Chung9b9fb962013-11-15 15:39:34 -08002717 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002718 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002719 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002720 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002721 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002722 otherFolders);
2723 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2724 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2725
2726 // Tell the workspace that we're about to start binding items
2727 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002728 public void run() {
2729 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2730 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002731 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002732 }
2733 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002734 };
Winson Chung81b52252012-08-27 15:34:29 -07002735 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002736
Adam Cohendcd297f2013-06-18 13:13:40 -07002737 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2738
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002739 // Load items on the current page
2740 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2741 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002742 if (isLoadingSynchronously) {
2743 r = new Runnable() {
2744 public void run() {
2745 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002746 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002747 callbacks.onPageBoundSynchronously(currentScreen);
2748 }
2749 }
2750 };
Winson Chung81b52252012-08-27 15:34:29 -07002751 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002752 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002753
Winson Chung4a2afa32012-07-19 14:53:05 -07002754 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2755 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002756 synchronized (mDeferredBindRunnables) {
2757 mDeferredBindRunnables.clear();
2758 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002759 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002760 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002761
2762 // Tell the workspace that we're done binding items
2763 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002764 public void run() {
2765 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2766 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002767 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002768 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002769
Winson Chung98e030b2012-05-07 16:01:11 -07002770 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002771 if (DEBUG_LOADERS) {
2772 Log.d(TAG, "bound workspace in "
2773 + (SystemClock.uptimeMillis()-t) + "ms");
2774 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002775
2776 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002777 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002778 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002779 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002780 synchronized (mDeferredBindRunnables) {
2781 mDeferredBindRunnables.add(r);
2782 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002783 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002784 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002785 }
Joe Onorato36115782010-06-17 13:28:48 -04002786 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002787
Joe Onorato36115782010-06-17 13:28:48 -04002788 private void loadAndBindAllApps() {
2789 if (DEBUG_LOADERS) {
2790 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2791 }
2792 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002793 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002794 synchronized (LoaderTask.this) {
2795 if (mStopped) {
2796 return;
2797 }
2798 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002799 }
Joe Onorato36115782010-06-17 13:28:48 -04002800 } else {
2801 onlyBindAllApps();
2802 }
2803 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002804
Joe Onorato36115782010-06-17 13:28:48 -04002805 private void onlyBindAllApps() {
2806 final Callbacks oldCallbacks = mCallbacks.get();
2807 if (oldCallbacks == null) {
2808 // This launcher has exited and nobody bothered to tell us. Just bail.
2809 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2810 return;
2811 }
2812
2813 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002814 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002815 final ArrayList<AppInfo> list
2816 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002817 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002818 public void run() {
2819 final long t = SystemClock.uptimeMillis();
2820 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2821 if (callbacks != null) {
2822 callbacks.bindAllApplications(list);
2823 }
2824 if (DEBUG_LOADERS) {
2825 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2826 + (SystemClock.uptimeMillis()-t) + "ms");
2827 }
2828 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002829 };
2830 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002831 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002832 r.run();
2833 } else {
2834 mHandler.post(r);
2835 }
Joe Onorato36115782010-06-17 13:28:48 -04002836 }
2837
Winson Chung64359a52013-07-08 17:17:08 -07002838 private void loadAllApps() {
2839 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002840
Joe Onorato36115782010-06-17 13:28:48 -04002841 final Callbacks oldCallbacks = mCallbacks.get();
2842 if (oldCallbacks == null) {
2843 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002844 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002845 return;
2846 }
2847
2848 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2849 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2850
Kenny Guyed131872014-04-30 03:02:21 +01002851 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2852
Winson Chung64359a52013-07-08 17:17:08 -07002853 // Clear the list of apps
2854 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002855 for (UserHandleCompat user : profiles) {
2856 // Query for the set of apps
2857 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2858 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2859 if (DEBUG_LOADERS) {
2860 Log.d(TAG, "getActivityList took "
2861 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2862 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2863 }
2864 // Fail if we don't have any apps
2865 if (apps == null || apps.isEmpty()) {
2866 return;
2867 }
2868 // Sort the applications by name
2869 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2870 Collections.sort(apps,
2871 new LauncherModel.ShortcutNameComparator(mLabelCache));
2872 if (DEBUG_LOADERS) {
2873 Log.d(TAG, "sort took "
2874 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2875 }
Joe Onorato36115782010-06-17 13:28:48 -04002876
Kenny Guyed131872014-04-30 03:02:21 +01002877 // Create the ApplicationInfos
2878 for (int i = 0; i < apps.size(); i++) {
2879 LauncherActivityInfoCompat app = apps.get(i);
2880 // This builds the icon bitmaps.
2881 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2882 }
Winson Chung64359a52013-07-08 17:17:08 -07002883 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002884 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002885 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2886 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002887
2888 // Post callback on main thread
2889 mHandler.post(new Runnable() {
2890 public void run() {
2891 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002892 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002893 if (callbacks != null) {
2894 callbacks.bindAllApplications(added);
2895 if (DEBUG_LOADERS) {
2896 Log.d(TAG, "bound " + added.size() + " apps in "
2897 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2898 }
2899 } else {
2900 Log.i(TAG, "not binding apps: no Launcher activity");
2901 }
2902 }
2903 });
2904
Joe Onorato36115782010-06-17 13:28:48 -04002905 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002906 Log.d(TAG, "Icons processed in "
2907 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002908 }
2909 }
2910
2911 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002912 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002913 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2914 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2915 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2916 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2917 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2918 }
Joe Onorato36115782010-06-17 13:28:48 -04002919 }
2920 }
2921
2922 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002923 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002924 }
2925
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002926 private class AppsAvailabilityCheck extends BroadcastReceiver {
2927
2928 @Override
2929 public void onReceive(Context context, Intent intent) {
2930 synchronized (sBgLock) {
2931 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2932 .getInstance(mApp.getContext());
2933 ArrayList<String> packagesRemoved;
2934 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2935 UserHandleCompat user = entry.getKey();
Sameer Padala513edae2014-07-29 16:17:08 -07002936 packagesRemoved = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002937 for (String pkg : entry.getValue()) {
2938 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
2939 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2940 packagesRemoved.add(pkg);
2941 }
2942 }
2943 if (!packagesRemoved.isEmpty()) {
2944 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2945 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2946 }
2947 }
Sunny Goyal34942622014-08-29 17:20:55 -07002948 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002949 }
2950 }
2951 }
2952
Joe Onorato36115782010-06-17 13:28:48 -04002953 private class PackageUpdatedTask implements Runnable {
2954 int mOp;
2955 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002956 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002957
2958 public static final int OP_NONE = 0;
2959 public static final int OP_ADD = 1;
2960 public static final int OP_UPDATE = 2;
2961 public static final int OP_REMOVE = 3; // uninstlled
2962 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2963
2964
Kenny Guyed131872014-04-30 03:02:21 +01002965 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002966 mOp = op;
2967 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002968 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002969 }
2970
2971 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002972 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002973
2974 final String[] packages = mPackages;
2975 final int N = packages.length;
2976 switch (mOp) {
2977 case OP_ADD:
2978 for (int i=0; i<N; i++) {
2979 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002980 mIconCache.remove(packages[i], mUser);
2981 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002982 }
2983 break;
2984 case OP_UPDATE:
2985 for (int i=0; i<N; i++) {
2986 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002987 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002988 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002989 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002990 }
2991 break;
2992 case OP_REMOVE:
2993 case OP_UNAVAILABLE:
2994 for (int i=0; i<N; i++) {
2995 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002996 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002997 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002998 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002999 }
3000 break;
3001 }
3002
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003003 ArrayList<AppInfo> added = null;
3004 ArrayList<AppInfo> modified = null;
3005 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003006
Adam Cohen487f7dd2012-06-28 18:12:10 -07003007 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003008 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003009 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003010 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003011 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003012 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003013 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003014 }
Winson Chung5d55f332012-07-16 20:45:03 -07003015 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003016 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003017 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003018 }
3019
Joe Onorato36115782010-06-17 13:28:48 -04003020 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
3021 if (callbacks == null) {
3022 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3023 return;
3024 }
3025
3026 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003027 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003028 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003029 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003030 addAndBindAddedWorkspaceApps(context, addedInfos);
3031 } else {
3032 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003033 }
Joe Onorato36115782010-06-17 13:28:48 -04003034 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003035
Joe Onorato36115782010-06-17 13:28:48 -04003036 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003037 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07003038
3039 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003040 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07003041 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01003042 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07003043 for (ItemInfo i : infos) {
3044 if (isShortcutInfoUpdateable(i)) {
3045 ShortcutInfo info = (ShortcutInfo) i;
3046 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003047 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07003048 updateItemInDatabase(context, info);
3049 }
3050 }
3051 }
3052
Joe Onorato36115782010-06-17 13:28:48 -04003053 mHandler.post(new Runnable() {
3054 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003055 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3056 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003057 callbacks.bindAppsUpdated(modifiedFinal);
3058 }
3059 }
3060 });
3061 }
Winson Chung83892cc2013-05-01 16:53:33 -07003062
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003063 // Update shortcuts which use an iconResource
3064 if (mOp == OP_ADD || mOp == OP_UPDATE) {
3065 final ArrayList<ShortcutInfo> iconsChanged = new ArrayList<ShortcutInfo>();
3066 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
3067 // We need to iteration over the items here, so that we can avoid new Bitmap
3068 // creation on the UI thread.
3069 synchronized (sBgLock) {
3070 for (ItemInfo info : sBgWorkspaceItems) {
3071 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3072 ShortcutInfo si = (ShortcutInfo) info;
3073 if ((si.iconResource != null)
3074 && packageSet.contains(si.getTargetComponent().getPackageName())){
3075 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3076 si.iconResource.resourceName, mIconCache, context);
3077 if (icon != null) {
3078 si.setIcon(icon);
3079 si.usingFallbackIcon = false;
3080 iconsChanged.add(si);
3081 updateItemInDatabase(context, si);
3082 }
3083 }
3084 }
3085 }
3086 }
3087
3088 if (!iconsChanged.isEmpty()) {
3089 mHandler.post(new Runnable() {
3090 public void run() {
3091 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3092 if (callbacks == cb && cb != null) {
3093 callbacks.bindShortcutsUpdated(iconsChanged);
3094 }
3095 }
3096 });
3097 }
3098 }
3099
Winson Chungdf95eb12013-10-16 14:57:07 -07003100 final ArrayList<String> removedPackageNames =
3101 new ArrayList<String>();
3102 if (mOp == OP_REMOVE) {
3103 // Mark all packages in the broadcast to be removed
3104 removedPackageNames.addAll(Arrays.asList(packages));
3105 } else if (mOp == OP_UPDATE) {
3106 // Mark disabled packages in the broadcast to be removed
3107 final PackageManager pm = context.getPackageManager();
3108 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003109 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003110 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003111 }
3112 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003113 }
3114 // Remove all the components associated with this package
3115 for (String pn : removedPackageNames) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003116 deletePackageFromDatabase(context, pn, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003117 }
3118 // Remove all the specific components
3119 for (AppInfo a : removedApps) {
Kenny Guyed131872014-04-30 03:02:21 +01003120 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003121 deleteItemsFromDatabase(context, infos);
Winson Chungdf95eb12013-10-16 14:57:07 -07003122 }
3123 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
3124 // Remove any queued items from the install queue
3125 String spKey = LauncherAppState.getSharedPreferencesKey();
3126 SharedPreferences sp =
3127 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3128 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3129 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003130 mHandler.post(new Runnable() {
3131 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003132 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3133 if (callbacks == cb && cb != null) {
Kenny Guyed131872014-04-30 03:02:21 +01003134 callbacks.bindComponentsRemoved(removedPackageNames, removedApps, mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003135 }
3136 }
3137 });
Joe Onoratobe386092009-11-17 17:32:16 -08003138 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003139
Michael Jurkac402cd92013-05-20 15:49:32 +02003140 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003141 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003142 mHandler.post(new Runnable() {
3143 @Override
3144 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003145 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3146 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003147 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003148 }
3149 }
3150 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003151
3152 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003153 mHandler.post(new Runnable() {
3154 public void run() {
3155 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3156 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003157 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003158 }
3159 }
3160 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003161 }
3162 }
3163
Michael Jurkac402cd92013-05-20 15:49:32 +02003164 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3165 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3166 PackageManager packageManager = context.getPackageManager();
3167 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003168 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3169
Michael Jurkac402cd92013-05-20 15:49:32 +02003170 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3171 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003172 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003173 return widgetsAndShortcuts;
3174 }
3175
Kenny Guyed131872014-04-30 03:02:21 +01003176 private static boolean isPackageDisabled(Context context, String packageName,
3177 UserHandleCompat user) {
3178 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3179 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003180 }
Adam Cohen556f6132014-01-15 15:18:08 -08003181
Kenny Guyed131872014-04-30 03:02:21 +01003182 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3183 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003184 if (cn == null) {
3185 return false;
3186 }
Kenny Guyed131872014-04-30 03:02:21 +01003187 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3188 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003189 return false;
3190 }
Kenny Guyed131872014-04-30 03:02:21 +01003191 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003192 }
3193
Adam Cohena28b78e2014-05-20 17:03:04 -07003194 public static boolean isValidPackage(Context context, String packageName,
3195 UserHandleCompat user) {
3196 if (packageName == null) {
3197 return false;
3198 }
3199 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3200 return launcherApps.isPackageEnabledForProfile(packageName, user);
3201 }
3202
Joe Onorato9c1289c2009-08-17 11:03:03 -04003203 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003204 * Make an ShortcutInfo object for a restored application or shortcut item that points
3205 * to a package that is not yet installed on the system.
3206 */
Sunny Goyal34942622014-08-29 17:20:55 -07003207 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3208 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003209 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003210 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003211 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3212
3213 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3214 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3215 if (!TextUtils.isEmpty(title)) {
3216 info.title = title;
3217 }
3218 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3219 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3220 if (TextUtils.isEmpty(info.title)) {
3221 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3222 }
3223 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3224 } else {
3225 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3226 }
3227
Kenny Guyc2bd8102014-06-30 12:30:31 +01003228 info.contentDescription = mUserManager.getBadgedLabelForUser(
3229 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003230 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003231 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003232 return info;
3233 }
3234
3235 /**
3236 * Make an Intent object for a restored application or shortcut item that points
3237 * to the market page for the item.
3238 */
3239 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3240 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003241 return getMarketIntent(componentName.getPackageName());
3242 }
3243
3244 static Intent getMarketIntent(String packageName) {
3245 return new Intent(Intent.ACTION_VIEW)
3246 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003247 .scheme("market")
3248 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003249 .appendQueryParameter("id", packageName)
3250 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003251 }
3252
3253 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003254 * This is called from the code that adds shortcuts from the intent receiver. This
3255 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003256 */
Kenny Guyed131872014-04-30 03:02:21 +01003257 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3258 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003259 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003260 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003261
Joe Onorato56d82912010-03-07 14:32:10 -05003262 /**
3263 * Make an ShortcutInfo object for a shortcut that is an application.
3264 *
3265 * If c is not null, then it will be used to fill in missing data like the title and icon.
3266 */
Kenny Guyed131872014-04-30 03:02:21 +01003267 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3268 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003269 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003270 if (user == null) {
3271 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003272 return null;
3273 }
3274
Kenny Guyed131872014-04-30 03:02:21 +01003275 ComponentName componentName = intent.getComponent();
3276 if (componentName == null) {
3277 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3278 return null;
3279 }
3280
3281 Intent newIntent = new Intent(intent.getAction(), null);
3282 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3283 newIntent.setComponent(componentName);
3284 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003285 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003286 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3287 return null;
3288 }
3289
3290 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003291
Joe Onorato56d82912010-03-07 14:32:10 -05003292 // the resource -- This may implicitly give us back the fallback icon,
3293 // but don't worry about that. All we're doing with usingFallbackIcon is
3294 // to avoid saving lots of copies of that in the database, and most apps
3295 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003296 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003297
Joe Onorato56d82912010-03-07 14:32:10 -05003298 // the db
3299 if (icon == null) {
3300 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003301 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003302 }
3303 }
3304 // the fallback icon
3305 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003306 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003307 info.usingFallbackIcon = true;
3308 }
3309 info.setIcon(icon);
3310
Kenny Guyed131872014-04-30 03:02:21 +01003311 // From the cache.
3312 if (labelCache != null) {
3313 info.title = labelCache.get(componentName);
3314 }
3315
Joe Onorato56d82912010-03-07 14:32:10 -05003316 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003317 if (info.title == null && lai != null) {
3318 info.title = lai.getLabel();
3319 if (labelCache != null) {
3320 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003321 }
Joe Onorato56d82912010-03-07 14:32:10 -05003322 }
3323 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003324 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003325 if (c != null) {
3326 info.title = c.getString(titleIndex);
3327 }
3328 }
3329 // fall back to the class name of the activity
3330 if (info.title == null) {
3331 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003332 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003333 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003334 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003335 info.contentDescription = mUserManager.getBadgedLabelForUser(
3336 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003337 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003338 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003339
Winson Chung64359a52013-07-08 17:17:08 -07003340 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3341 ItemInfoFilter f) {
3342 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3343 for (ItemInfo i : infos) {
3344 if (i instanceof ShortcutInfo) {
3345 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003346 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003347 if (cn != null && f.filterItem(null, info, cn)) {
3348 filtered.add(info);
3349 }
3350 } else if (i instanceof FolderInfo) {
3351 FolderInfo info = (FolderInfo) i;
3352 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003353 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003354 if (cn != null && f.filterItem(info, s, cn)) {
3355 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003356 }
3357 }
Winson Chung64359a52013-07-08 17:17:08 -07003358 } else if (i instanceof LauncherAppWidgetInfo) {
3359 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3360 ComponentName cn = info.providerName;
3361 if (cn != null && f.filterItem(null, info, cn)) {
3362 filtered.add(info);
3363 }
Winson Chung8a435102012-08-30 17:16:53 -07003364 }
3365 }
Winson Chung64359a52013-07-08 17:17:08 -07003366 return new ArrayList<ItemInfo>(filtered);
3367 }
3368
Kenny Guyed131872014-04-30 03:02:21 +01003369 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3370 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003371 ItemInfoFilter filter = new ItemInfoFilter() {
3372 @Override
3373 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003374 if (info.user == null) {
3375 return cn.equals(cname);
3376 } else {
3377 return cn.equals(cname) && info.user.equals(user);
3378 }
Winson Chung64359a52013-07-08 17:17:08 -07003379 }
3380 };
3381 return filterItemInfos(sBgItemsIdMap.values(), filter);
3382 }
3383
3384 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
3385 if (i instanceof ShortcutInfo) {
3386 ShortcutInfo info = (ShortcutInfo) i;
3387 // We need to check for ACTION_MAIN otherwise getComponent() might
3388 // return null for some shortcuts (for instance, for shortcuts to
3389 // web pages.)
3390 Intent intent = info.intent;
3391 ComponentName name = intent.getComponent();
3392 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3393 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3394 return true;
3395 }
Chris Wrenb6d4c282014-01-27 14:17:08 -05003396 // placeholder shortcuts get special treatment, let them through too.
Sunny Goyal34942622014-08-29 17:20:55 -07003397 if (info.isPromise()) {
Chris Wrenb6d4c282014-01-27 14:17:08 -05003398 return true;
3399 }
Winson Chung64359a52013-07-08 17:17:08 -07003400 }
3401 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003402 }
3403
3404 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003405 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003406 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003407 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003408 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3409 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003410
Joe Onorato56d82912010-03-07 14:32:10 -05003411 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003412 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003413 // Non-app shortcuts are only supported for current user.
3414 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003415 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003416
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003417 // TODO: If there's an explicit component and we can't install that, delete it.
3418
Joe Onorato56d82912010-03-07 14:32:10 -05003419 info.title = c.getString(titleIndex);
3420
Joe Onorato9c1289c2009-08-17 11:03:03 -04003421 int iconType = c.getInt(iconTypeIndex);
3422 switch (iconType) {
3423 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3424 String packageName = c.getString(iconPackageIndex);
3425 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003426 info.customIcon = false;
3427 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003428 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003429 // the db
3430 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003431 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003432 }
3433 // the fallback icon
3434 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003435 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003436 info.usingFallbackIcon = true;
3437 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003438 break;
3439 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003440 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003441 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003442 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003443 info.customIcon = false;
3444 info.usingFallbackIcon = true;
3445 } else {
3446 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003447 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003448 break;
3449 default:
Kenny Guyed131872014-04-30 03:02:21 +01003450 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003451 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003452 info.customIcon = false;
3453 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003454 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003455 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003456 return info;
3457 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003458
Michael Jurka931dc972011-08-05 15:08:15 -07003459 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003460 @SuppressWarnings("all") // suppress dead code warning
3461 final boolean debug = false;
3462 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003463 Log.d(TAG, "getIconFromCursor app="
3464 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3465 }
3466 byte[] data = c.getBlob(iconIndex);
3467 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003468 return Utilities.createIconBitmap(
3469 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003470 } catch (Exception e) {
3471 return null;
3472 }
3473 }
3474
Winson Chung3d503fb2011-07-13 17:25:49 -07003475 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3476 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003477 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003478 if (info == null) {
3479 return null;
3480 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003481 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003482
3483 return info;
3484 }
3485
Winson Chunga9abd0e2010-10-27 17:18:37 -07003486 /**
Winson Chung55cef262010-10-28 14:14:18 -07003487 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3488 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003489 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003490 ComponentName component) {
3491 List<AppWidgetProviderInfo> widgets =
3492 AppWidgetManager.getInstance(context).getInstalledProviders();
3493 for (AppWidgetProviderInfo info : widgets) {
3494 if (info.provider.equals(component)) {
3495 return info;
3496 }
3497 }
3498 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003499 }
3500
3501 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003502 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3503 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3504 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3505
Adam Cohend9198822011-11-22 16:42:47 -08003506 if (intent == null) {
3507 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3508 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3509 return null;
3510 }
3511
Joe Onorato0589f0f2010-02-08 13:44:00 -08003512 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003513 boolean customIcon = false;
3514 ShortcutIconResource iconResource = null;
3515
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003516 if (bitmap instanceof Bitmap) {
3517 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003518 customIcon = true;
3519 } else {
3520 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003521 if (extra instanceof ShortcutIconResource) {
3522 iconResource = (ShortcutIconResource) extra;
3523 icon = Utilities.createIconBitmap(iconResource.packageName,
3524 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003525 }
3526 }
3527
Michael Jurkac9d95c52011-08-29 14:03:34 -07003528 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003529
Kenny Guyed131872014-04-30 03:02:21 +01003530 // Only support intents for current user for now. Intents sent from other
3531 // users wouldn't get here without intent forwarding anyway.
3532 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003533 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003534 if (fallbackIcon != null) {
3535 icon = fallbackIcon;
3536 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003537 icon = mIconCache.getDefaultIcon(info.user);
Winson Chunga9abd0e2010-10-27 17:18:37 -07003538 info.usingFallbackIcon = true;
3539 }
Joe Onorato56d82912010-03-07 14:32:10 -05003540 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003541 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003542
Joe Onorato0589f0f2010-02-08 13:44:00 -08003543 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003544 info.contentDescription = mUserManager.getBadgedLabelForUser(
3545 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003546 info.intent = intent;
3547 info.customIcon = customIcon;
3548 info.iconResource = iconResource;
3549
3550 return info;
3551 }
3552
Winson Chungaac01e12011-08-17 10:37:13 -07003553 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3554 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003555 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003556 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003557 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003558 }
Joe Onorato56d82912010-03-07 14:32:10 -05003559 // If this icon doesn't have a custom icon, check to see
3560 // what's stored in the DB, and if it doesn't match what
3561 // we're going to show, store what we are going to show back
3562 // into the DB. We do this so when we're loading, if the
3563 // package manager can't find an icon (for example because
3564 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003565 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003566 cache.put(info, c.getBlob(iconIndex));
3567 return true;
3568 }
3569 return false;
3570 }
3571 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3572 boolean needSave = false;
3573 try {
3574 if (data != null) {
3575 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3576 Bitmap loaded = info.getIcon(mIconCache);
3577 needSave = !saved.sameAs(loaded);
3578 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003579 needSave = true;
3580 }
Winson Chungaac01e12011-08-17 10:37:13 -07003581 } catch (Exception e) {
3582 needSave = true;
3583 }
3584 if (needSave) {
3585 Log.d(TAG, "going to save icon bitmap for info=" + info);
3586 // This is slower than is ideal, but this only happens once
3587 // or when the app is updated with a new icon.
3588 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003589 }
3590 }
3591
Joe Onorato9c1289c2009-08-17 11:03:03 -04003592 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003593 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003594 * or make a new one.
3595 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003596 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003597 // See if a placeholder was created for us already
3598 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003599 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003600 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003601 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003602 folders.put(id, folderInfo);
3603 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003604 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003605 }
3606
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003607 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003608 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003609 return new Comparator<AppInfo>() {
3610 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003611 if (a.user.equals(b.user)) {
3612 int result = collator.compare(a.title.toString().trim(),
3613 b.title.toString().trim());
3614 if (result == 0) {
3615 result = a.componentName.compareTo(b.componentName);
3616 }
3617 return result;
3618 } else {
3619 // TODO Need to figure out rules for sorting
3620 // profiles, this puts work second.
3621 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003622 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003623 }
Winson Chung11904872012-09-17 16:58:46 -07003624 };
3625 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003626 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3627 = new Comparator<AppInfo>() {
3628 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003629 if (a.firstInstallTime < b.firstInstallTime) return 1;
3630 if (a.firstInstallTime > b.firstInstallTime) return -1;
3631 return 0;
3632 }
3633 };
Winson Chung5308f242011-08-18 12:12:41 -07003634 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3635 if (info.activityInfo != null) {
3636 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3637 } else {
3638 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3639 }
3640 }
Kenny Guyed131872014-04-30 03:02:21 +01003641 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003642 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003643 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003644 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003645 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003646 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003647 }
Kenny Guyed131872014-04-30 03:02:21 +01003648 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003649 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003650 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003651 }
Kenny Guyed131872014-04-30 03:02:21 +01003652 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003653 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003654 ComponentName keyA = a.getComponentName();
3655 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003656 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003657 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003658 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003659 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003660
Winson Chung5308f242011-08-18 12:12:41 -07003661 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003662 }
Winson Chung5308f242011-08-18 12:12:41 -07003663 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003664 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003665 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003666 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003667
Winson Chung5308f242011-08-18 12:12:41 -07003668 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003669 }
Winson Chung11904872012-09-17 16:58:46 -07003670 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003671 }
3672 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003673 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003674 private final AppWidgetManagerCompat mManager;
3675 private final PackageManager mPackageManager;
3676 private final HashMap<Object, String> mLabelCache;
3677 private final Collator mCollator;
3678
3679 WidgetAndShortcutNameComparator(Context context) {
3680 mManager = AppWidgetManagerCompat.getInstance(context);
3681 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003682 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003683 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003684 }
3685 public final int compare(Object a, Object b) {
3686 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003687 if (mLabelCache.containsKey(a)) {
3688 labelA = mLabelCache.get(a);
3689 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003690 labelA = (a instanceof AppWidgetProviderInfo)
3691 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3692 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003693 mLabelCache.put(a, labelA);
3694 }
3695 if (mLabelCache.containsKey(b)) {
3696 labelB = mLabelCache.get(b);
3697 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003698 labelB = (b instanceof AppWidgetProviderInfo)
3699 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3700 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003701 mLabelCache.put(b, labelB);
3702 }
Winson Chung11904872012-09-17 16:58:46 -07003703 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003704 }
3705 };
Joe Onoratobe386092009-11-17 17:32:16 -08003706
Sunny Goyal651077b2014-06-30 14:15:31 -07003707 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3708 return (provider != null) && (provider.provider != null)
3709 && (provider.provider.getPackageName() != null);
3710 }
3711
Joe Onoratobe386092009-11-17 17:32:16 -08003712 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003713 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003714 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3715 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3716 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3717 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003718 if (mLoaderTask != null) {
3719 mLoaderTask.dumpState();
3720 } else {
3721 Log.d(TAG, "mLoaderTask=null");
3722 }
Joe Onoratobe386092009-11-17 17:32:16 -08003723 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003724}