blob: 3055dd099b24ee077dbcc2ab8ebd09cee8bd5006 [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,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700205 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
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
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001761 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001762 LauncherAppState app = LauncherAppState.getInstance();
1763 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001764 final int countX = (int) grid.numColumns;
1765 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001766
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001768 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001769 // Return early if we detect that an item is under the hotseat button
1770 if (mCallbacks == null ||
1771 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001772 Log.e(TAG, "Error loading shortcut into hotseat " + item
1773 + " into position (" + item.screenId + ":" + item.cellX + ","
1774 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001775 return false;
1776 }
1777
Dan Sandler295ae182013-12-10 16:05:47 -05001778 final ItemInfo[][] hotseatItems =
1779 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1780
Adam Cohenae4409d2013-11-26 10:34:59 -08001781 if (item.screenId >= grid.numHotseatIcons) {
1782 Log.e(TAG, "Error loading shortcut " + item
1783 + " into hotseat position " + item.screenId
1784 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1785 + ")");
1786 return false;
1787 }
1788
Dan Sandler295ae182013-12-10 16:05:47 -05001789 if (hotseatItems != null) {
1790 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001791 Log.e(TAG, "Error loading shortcut into hotseat " + item
1792 + " into position (" + item.screenId + ":" + item.cellX + ","
1793 + item.cellY + ") occupied by "
1794 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1795 [(int) item.screenId][0]);
1796 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001797 } else {
1798 hotseatItems[(int) item.screenId][0] = item;
1799 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001801 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001802 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 items[(int) item.screenId][0] = item;
1804 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001805 return true;
1806 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001807 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1808 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001809 return true;
1810 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001811
Adam Cohendcd297f2013-06-18 13:13:40 -07001812 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001813 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001814 occupied.put(item.screenId, items);
1815 }
1816
Dan Sandler295ae182013-12-10 16:05:47 -05001817 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001818 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1819 item.cellX < 0 || item.cellY < 0 ||
1820 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1821 Log.e(TAG, "Error loading shortcut " + item
1822 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1823 + item.cellX + "," + item.cellY
1824 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1825 return false;
1826 }
1827
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001828 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001829 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1830 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001831 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001832 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001834 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001835 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001836 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001837 return false;
1838 }
1839 }
1840 }
1841 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1842 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001843 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001844 }
1845 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001846
Joe Onorato36115782010-06-17 13:28:48 -04001847 return true;
1848 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001849
Winson Chungba9c37f2013-08-30 14:11:37 -07001850 /** Clears all the sBg data structures */
1851 private void clearSBgDataStructures() {
1852 synchronized (sBgLock) {
1853 sBgWorkspaceItems.clear();
1854 sBgAppWidgets.clear();
1855 sBgFolders.clear();
1856 sBgItemsIdMap.clear();
1857 sBgDbIconCache.clear();
1858 sBgWorkspaceScreens.clear();
1859 }
1860 }
1861
Dan Sandlerd5024042014-01-09 15:01:33 -05001862 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001863 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001864 // Log to disk
1865 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1866
Joe Onorato36115782010-06-17 13:28:48 -04001867 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001868
Joe Onorato36115782010-06-17 13:28:48 -04001869 final Context context = mContext;
1870 final ContentResolver contentResolver = context.getContentResolver();
1871 final PackageManager manager = context.getPackageManager();
1872 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1873 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001874 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1875 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001876 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001877
Winson Chung892c74d2013-08-22 16:15:50 -07001878 LauncherAppState app = LauncherAppState.getInstance();
1879 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1880 int countX = (int) grid.numColumns;
1881 int countY = (int) grid.numRows;
1882
Dan Sandlerd5024042014-01-09 15:01:33 -05001883 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1884 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1885 LauncherAppState.getLauncherProvider().deleteDatabase();
1886 }
1887
1888 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1889 // append the user's Launcher2 shortcuts
1890 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1891 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1892 } else {
1893 // Make sure the default workspace is loaded
1894 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001895 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001896 }
Adam Cohene25af792013-06-06 23:08:25 -07001897
Adam Cohen71483f42014-05-15 14:04:01 -07001898 // This code path is for our old migration code and should no longer be exercised
1899 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001900
Winson Chung9f9f00b2013-11-15 13:27:00 -08001901 // Log to disk
1902 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001903
Winson Chung2abf94d2012-07-18 18:16:38 -07001904 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001905 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001906 final HashSet<String> installingPkgs = PackageInstallerCompat
1907 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001908
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001909 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001910 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001911 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001912 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001913 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001914
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 // +1 for the hotseat (it can be larger than the workspace)
1916 // Load workspace in reverse order to ensure that latest items are loaded first (and
1917 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001918 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001919
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001920 try {
1921 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1922 final int intentIndex = c.getColumnIndexOrThrow
1923 (LauncherSettings.Favorites.INTENT);
1924 final int titleIndex = c.getColumnIndexOrThrow
1925 (LauncherSettings.Favorites.TITLE);
1926 final int iconTypeIndex = c.getColumnIndexOrThrow(
1927 LauncherSettings.Favorites.ICON_TYPE);
1928 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1929 final int iconPackageIndex = c.getColumnIndexOrThrow(
1930 LauncherSettings.Favorites.ICON_PACKAGE);
1931 final int iconResourceIndex = c.getColumnIndexOrThrow(
1932 LauncherSettings.Favorites.ICON_RESOURCE);
1933 final int containerIndex = c.getColumnIndexOrThrow(
1934 LauncherSettings.Favorites.CONTAINER);
1935 final int itemTypeIndex = c.getColumnIndexOrThrow(
1936 LauncherSettings.Favorites.ITEM_TYPE);
1937 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1938 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001939 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1940 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 final int screenIndex = c.getColumnIndexOrThrow(
1942 LauncherSettings.Favorites.SCREEN);
1943 final int cellXIndex = c.getColumnIndexOrThrow
1944 (LauncherSettings.Favorites.CELLX);
1945 final int cellYIndex = c.getColumnIndexOrThrow
1946 (LauncherSettings.Favorites.CELLY);
1947 final int spanXIndex = c.getColumnIndexOrThrow
1948 (LauncherSettings.Favorites.SPANX);
1949 final int spanYIndex = c.getColumnIndexOrThrow(
1950 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001951 final int restoredIndex = c.getColumnIndexOrThrow(
1952 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001953 final int profileIdIndex = c.getColumnIndexOrThrow(
1954 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001955 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1956 //final int displayModeIndex = c.getColumnIndexOrThrow(
1957 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001958
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001959 ShortcutInfo info;
1960 String intentDescription;
1961 LauncherAppWidgetInfo appWidgetInfo;
1962 int container;
1963 long id;
1964 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001965 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001966
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001967 while (!mStopped && c.moveToNext()) {
1968 try {
1969 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001970 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001971 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001972
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001973 switch (itemType) {
1974 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1975 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001976 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001977 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001978 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001979 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001980 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001981 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001982 if (user == null) {
1983 // User has been deleted remove the item.
1984 itemsToRemove.add(id);
1985 continue;
1986 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001987 try {
1988 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001989 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001990 if (cn != null && cn.getPackageName() != null) {
1991 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1992 cn.getPackageName(), user);
1993 boolean validComponent = validPkg &&
1994 launcherApps.isActivityEnabledForProfile(cn, user);
1995
1996 if (validComponent) {
1997 if (restored) {
1998 // no special handling necessary for this item
1999 restoredRows.add(id);
2000 restored = false;
2001 }
2002 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07002003 intent = null;
2004 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2005 // We allow auto install apps to have their intent
2006 // updated after an install.
2007 intent = manager.getLaunchIntentForPackage(
2008 cn.getPackageName());
2009 if (intent != null) {
2010 ContentValues values = new ContentValues();
2011 values.put(LauncherSettings.Favorites.INTENT,
2012 intent.toUri(0));
2013 String where = BaseColumns._ID + "= ?";
2014 String[] args = {Long.toString(id)};
2015 contentResolver.update(contentUri, values, where, args);
2016 }
2017 }
2018
2019 if (intent == null) {
2020 // The app is installed but the component is no
2021 // longer available.
2022 Launcher.addDumpLog(TAG,
2023 "Invalid component removed: " + cn, true);
2024 itemsToRemove.add(id);
2025 continue;
2026 } else {
2027 // no special handling necessary for this item
2028 restoredRows.add(id);
2029 restored = false;
2030 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002031 } else if (restored) {
2032 // Package is not yet available but might be
2033 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002034 Launcher.addDumpLog(TAG,
2035 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002036
2037 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2038 // Restore has started once.
2039 } else if (installingPkgs.contains(cn.getPackageName())) {
2040 // App restore has started. Update the flag
2041 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2042 ContentValues values = new ContentValues();
2043 values.put(LauncherSettings.Favorites.RESTORED,
2044 promiseType);
2045 String where = BaseColumns._ID + "= ?";
2046 String[] args = {Long.toString(id)};
2047 contentResolver.update(contentUri, values, where, args);
2048
2049 } else if (REMOVE_UNRESTORED_ICONS) {
2050 Launcher.addDumpLog(TAG,
2051 "Unrestored package removed: " + cn, true);
2052 itemsToRemove.add(id);
2053 continue;
2054 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002055 } else if (launcherApps.isAppEnabled(
2056 manager, cn.getPackageName(),
2057 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2058 // Package is present but not available.
2059 allowMissingTarget = true;
2060 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2061 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002062 // SdCard is not ready yet. Package might get available,
2063 // once it is ready.
2064 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2065 + " (check again later)", true);
2066 HashSet<String> pkgs = sPendingPackages.get(user);
2067 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002068 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002069 sPendingPackages.put(user, pkgs);
2070 }
2071 pkgs.add(cn.getPackageName());
2072 allowMissingTarget = true;
2073 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002074
2075 } else {
2076 // Do not wait for external media load anymore.
2077 // Log the invalid package, and remove it
2078 Launcher.addDumpLog(TAG,
2079 "Invalid package removed: " + cn, true);
2080 itemsToRemove.add(id);
2081 continue;
Winson Chungee055712013-07-30 14:46:24 -07002082 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002083 } else if (cn == null) {
2084 // For shortcuts with no component, keep them as they are
2085 restoredRows.add(id);
2086 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002087 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002089 Launcher.addDumpLog(TAG,
2090 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 continue;
2092 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002093
Chris Wrenf4d08112014-01-16 18:13:56 -05002094 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002095 if (user.equals(UserHandleCompat.myUserHandle())) {
2096 Launcher.addDumpLog(TAG,
2097 "constructing info for partially restored package",
2098 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002099 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002100 intent = getRestoredItemIntent(c, context, intent);
2101 } else {
2102 // Don't restore items for other profiles.
2103 itemsToRemove.add(id);
2104 continue;
2105 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002106 } else if (itemType ==
2107 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002108 info = getShortcutInfo(manager, intent, user, context, c,
2109 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 } else {
2111 info = getShortcutInfo(c, context, iconTypeIndex,
2112 iconPackageIndex, iconResourceIndex, iconIndex,
2113 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002114
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002115 // App shortcuts that used to be automatically added to Launcher
2116 // didn't always have the correct intent flags set, so do that
2117 // here
2118 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002119 intent.getCategories() != null &&
2120 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002121 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 intent.addFlags(
2123 Intent.FLAG_ACTIVITY_NEW_TASK |
2124 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2125 }
Michael Jurka96879562012-03-22 05:54:33 -07002126 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002127
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002128 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002129 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002130 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 container = c.getInt(containerIndex);
2132 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002133 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002134 info.cellX = c.getInt(cellXIndex);
2135 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002136 info.spanX = 1;
2137 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002138 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002139 info.isDisabled = disabledState;
2140 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2141 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2142 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002143
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002145 if (!checkItemPlacement(occupied, info)) {
2146 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 break;
2148 }
2149
2150 switch (container) {
2151 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2152 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2153 sBgWorkspaceItems.add(info);
2154 break;
2155 default:
2156 // Item is in a user folder
2157 FolderInfo folderInfo =
2158 findOrMakeFolder(sBgFolders, container);
2159 folderInfo.add(info);
2160 break;
2161 }
2162 sBgItemsIdMap.put(info.id, info);
2163
2164 // now that we've loaded everthing re-save it with the
2165 // icon in case it disappears somehow.
2166 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002167 } else {
2168 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002169 }
2170 break;
2171
2172 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2173 id = c.getLong(idIndex);
2174 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2175
2176 folderInfo.title = c.getString(titleIndex);
2177 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002178 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002180 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002181 folderInfo.cellX = c.getInt(cellXIndex);
2182 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002183 folderInfo.spanX = 1;
2184 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002185
Daniel Sandler8802e962010-05-26 16:28:16 -04002186 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002187 if (!checkItemPlacement(occupied, folderInfo)) {
2188 itemsToRemove.add(id);
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
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002296 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2297 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002298 break;
2299 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002300
Sunny Goyal94485362014-09-18 16:13:58 -07002301 String providerName = appWidgetInfo.providerName.flattenToString();
2302 if (!providerName.equals(savedProvider) ||
2303 (appWidgetInfo.restoreStatus != restoreStatus)) {
2304 ContentValues values = new ContentValues();
2305 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2306 providerName);
2307 values.put(LauncherSettings.Favorites.RESTORED,
2308 appWidgetInfo.restoreStatus);
2309 String where = BaseColumns._ID + "= ?";
2310 String[] args = {Long.toString(id)};
2311 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002312 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002313 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2314 sBgAppWidgets.add(appWidgetInfo);
2315 }
Joe Onorato36115782010-06-17 13:28:48 -04002316 break;
2317 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002318 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002319 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002320 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002321 }
2322 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002323 if (c != null) {
2324 c.close();
2325 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002326 }
2327
Winson Chungba9c37f2013-08-30 14:11:37 -07002328 // Break early if we've stopped loading
2329 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002330 clearSBgDataStructures();
2331 return false;
2332 }
2333
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002334 if (itemsToRemove.size() > 0) {
2335 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002336 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 // Remove dead items
2338 for (long id : itemsToRemove) {
2339 if (DEBUG_LOADERS) {
2340 Log.d(TAG, "Removed id = " + id);
2341 }
2342 // Don't notify content observers
2343 try {
2344 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2345 null, null);
2346 } catch (RemoteException e) {
2347 Log.w(TAG, "Could not remove id = " + id);
2348 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002349 }
2350 }
2351
Chris Wrenf4d08112014-01-16 18:13:56 -05002352 if (restoredRows.size() > 0) {
2353 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002354 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002355 // Update restored items that no longer require special handling
2356 try {
2357 StringBuilder selectionBuilder = new StringBuilder();
2358 selectionBuilder.append(LauncherSettings.Favorites._ID);
2359 selectionBuilder.append(" IN (");
2360 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2361 selectionBuilder.append(")");
2362 ContentValues values = new ContentValues();
2363 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002364 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002365 values, selectionBuilder.toString(), null);
2366 } catch (RemoteException e) {
2367 Log.w(TAG, "Could not update restored rows");
2368 }
2369 }
2370
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002371 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2372 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002373 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002374 null, sWorker);
2375 }
2376
Winson Chungc763c4e2013-07-19 13:49:06 -07002377 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002378 long maxScreenId = 0;
2379 // If we're importing we use the old screen order.
2380 for (ItemInfo item: sBgItemsIdMap.values()) {
2381 long screenId = item.screenId;
2382 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2383 !sBgWorkspaceScreens.contains(screenId)) {
2384 sBgWorkspaceScreens.add(screenId);
2385 if (screenId > maxScreenId) {
2386 maxScreenId = screenId;
2387 }
2388 }
2389 }
2390 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002391 // Log to disk
2392 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2393 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2394 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002395
Michael Jurka414300a2013-08-27 15:42:35 +02002396 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002397 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002398
2399 // Update the max item id after we load an old db
2400 long maxItemId = 0;
2401 // If we're importing we use the old screen order.
2402 for (ItemInfo item: sBgItemsIdMap.values()) {
2403 maxItemId = Math.max(maxItemId, item.id);
2404 }
Michael Jurka414300a2013-08-27 15:42:35 +02002405 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002406 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002407 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2408 for (Integer i : orderedScreens.keySet()) {
2409 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002410 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002411 // Log to disk
2412 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2413 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002414
2415 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002416 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002417 for (ItemInfo item: sBgItemsIdMap.values()) {
2418 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002419 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2420 unusedScreens.contains(screenId)) {
2421 unusedScreens.remove(screenId);
2422 }
2423 }
2424
2425 // If there are any empty screens remove them, and update.
2426 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002427 // Log to disk
2428 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2429 TextUtils.join(", ", unusedScreens), true);
2430
Winson Chung933bae62013-08-29 11:42:30 -07002431 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002432 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2433 }
2434 }
2435
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002436 if (DEBUG_LOADERS) {
2437 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2438 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002439 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002440 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002441 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002442
Daniel Sandler566da102013-06-25 23:43:45 -04002443 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002444 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002445 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002446 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002447 line += " | ";
2448 }
Winson Chung892c74d2013-08-22 16:15:50 -07002449 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002450 ItemInfo[][] screen = occupied.get(screenId);
2451 if (x < screen.length && y < screen[x].length) {
2452 line += (screen[x][y] != null) ? "#" : ".";
2453 } else {
2454 line += "!";
2455 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 }
Joe Onorato36115782010-06-17 13:28:48 -04002457 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002458 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002459 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002460 }
Joe Onorato36115782010-06-17 13:28:48 -04002461 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002462 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002463 }
2464
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002465 /** Filters the set of items who are directly or indirectly (via another container) on the
2466 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002467 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 ArrayList<ItemInfo> allWorkspaceItems,
2469 ArrayList<ItemInfo> currentScreenItems,
2470 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002471 // Purge any null ItemInfos
2472 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2473 while (iter.hasNext()) {
2474 ItemInfo i = iter.next();
2475 if (i == null) {
2476 iter.remove();
2477 }
2478 }
2479
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 // Order the set of items by their containers first, this allows use to walk through the
2481 // list sequentially, build up a list of containers that are in the specified screen,
2482 // as well as all items in those containers.
2483 Set<Long> itemsOnScreen = new HashSet<Long>();
2484 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2485 @Override
2486 public int compare(ItemInfo lhs, ItemInfo rhs) {
2487 return (int) (lhs.container - rhs.container);
2488 }
2489 });
2490 for (ItemInfo info : allWorkspaceItems) {
2491 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002492 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002493 currentScreenItems.add(info);
2494 itemsOnScreen.add(info.id);
2495 } else {
2496 otherScreenItems.add(info);
2497 }
2498 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2499 currentScreenItems.add(info);
2500 itemsOnScreen.add(info.id);
2501 } else {
2502 if (itemsOnScreen.contains(info.container)) {
2503 currentScreenItems.add(info);
2504 itemsOnScreen.add(info.id);
2505 } else {
2506 otherScreenItems.add(info);
2507 }
2508 }
2509 }
2510 }
2511
2512 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002513 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002514 ArrayList<LauncherAppWidgetInfo> appWidgets,
2515 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2516 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002517
2518 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002519 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002521 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 currentScreenWidgets.add(widget);
2523 } else {
2524 otherScreenWidgets.add(widget);
2525 }
2526 }
2527 }
2528
2529 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002530 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002531 HashMap<Long, ItemInfo> itemsIdMap,
2532 HashMap<Long, FolderInfo> folders,
2533 HashMap<Long, FolderInfo> currentScreenFolders,
2534 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002535
2536 for (long id : folders.keySet()) {
2537 ItemInfo info = itemsIdMap.get(id);
2538 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002539 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002540 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002541 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542 currentScreenFolders.put(id, folder);
2543 } else {
2544 otherScreenFolders.put(id, folder);
2545 }
2546 }
2547 }
2548
2549 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2550 * right) */
2551 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002552 final LauncherAppState app = LauncherAppState.getInstance();
2553 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002554 // XXX: review this
2555 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002556 @Override
2557 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002558 int cellCountX = (int) grid.numColumns;
2559 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002560 int screenOffset = cellCountX * cellCountY;
2561 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002562 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002563 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002564 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002565 rhs.cellY * cellCountX + rhs.cellX);
2566 return (int) (lr - rr);
2567 }
2568 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002570
Adam Cohendcd297f2013-06-18 13:13:40 -07002571 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2572 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002573 final Runnable r = new Runnable() {
2574 @Override
2575 public void run() {
2576 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2577 if (callbacks != null) {
2578 callbacks.bindScreens(orderedScreens);
2579 }
2580 }
2581 };
2582 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2583 }
2584
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002585 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2586 final ArrayList<ItemInfo> workspaceItems,
2587 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2588 final HashMap<Long, FolderInfo> folders,
2589 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002590
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 final boolean postOnMainThread = (deferredBindRunnables != null);
2592
2593 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002594 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002595 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002596 final int start = i;
2597 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 final Runnable r = new Runnable() {
2599 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002600 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002601 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002602 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002603 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2604 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002605 }
2606 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002607 };
2608 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002609 synchronized (deferredBindRunnables) {
2610 deferredBindRunnables.add(r);
2611 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002612 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002613 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002614 }
Joe Onorato36115782010-06-17 13:28:48 -04002615 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616
2617 // Bind the folders
2618 if (!folders.isEmpty()) {
2619 final Runnable r = new Runnable() {
2620 public void run() {
2621 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2622 if (callbacks != null) {
2623 callbacks.bindFolders(folders);
2624 }
2625 }
2626 };
2627 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002628 synchronized (deferredBindRunnables) {
2629 deferredBindRunnables.add(r);
2630 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002631 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002632 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002633 }
2634 }
2635
2636 // Bind the widgets, one at a time
2637 N = appWidgets.size();
2638 for (int i = 0; i < N; i++) {
2639 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2640 final Runnable r = new Runnable() {
2641 public void run() {
2642 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2643 if (callbacks != null) {
2644 callbacks.bindAppWidget(widget);
2645 }
2646 }
2647 };
2648 if (postOnMainThread) {
2649 deferredBindRunnables.add(r);
2650 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002651 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 }
2653 }
2654 }
2655
2656 /**
2657 * Binds all loaded data to actual views on the main thread.
2658 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002659 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002660 final long t = SystemClock.uptimeMillis();
2661 Runnable r;
2662
2663 // Don't use these two variables in any of the callback runnables.
2664 // Otherwise we hold a reference to them.
2665 final Callbacks oldCallbacks = mCallbacks.get();
2666 if (oldCallbacks == null) {
2667 // This launcher has exited and nobody bothered to tell us. Just bail.
2668 Log.w(TAG, "LoaderTask running with no launcher");
2669 return;
2670 }
2671
Winson Chung9b9fb962013-11-15 15:39:34 -08002672 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002673 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2674 ArrayList<LauncherAppWidgetInfo> appWidgets =
2675 new ArrayList<LauncherAppWidgetInfo>();
2676 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2677 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002678 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002679 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002680 workspaceItems.addAll(sBgWorkspaceItems);
2681 appWidgets.addAll(sBgAppWidgets);
2682 folders.putAll(sBgFolders);
2683 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002684 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002685 }
2686
Derek Prothro7aff3992013-12-10 14:00:37 -05002687 final boolean isLoadingSynchronously =
2688 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002689 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002690 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002691 if (currScreen >= orderedScreenIds.size()) {
2692 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002693 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002694 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002695 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002696 final long currentScreenId = currentScreen < 0
2697 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002698
2699 // Load all the items that are on the current page first (and in the process, unbind
2700 // all the existing workspace items before we call startBinding() below.
2701 unbindWorkspaceItemsOnMainThread();
2702
2703 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002704 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2705 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2706 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2707 new ArrayList<LauncherAppWidgetInfo>();
2708 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2709 new ArrayList<LauncherAppWidgetInfo>();
2710 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2711 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2712
Winson Chung9b9fb962013-11-15 15:39:34 -08002713 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002714 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002715 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002716 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002717 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002718 otherFolders);
2719 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2720 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2721
2722 // Tell the workspace that we're about to start binding items
2723 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002724 public void run() {
2725 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2726 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002727 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002728 }
2729 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002730 };
Winson Chung81b52252012-08-27 15:34:29 -07002731 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002732
Adam Cohendcd297f2013-06-18 13:13:40 -07002733 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2734
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002735 // Load items on the current page
2736 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2737 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002738 if (isLoadingSynchronously) {
2739 r = new Runnable() {
2740 public void run() {
2741 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002742 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002743 callbacks.onPageBoundSynchronously(currentScreen);
2744 }
2745 }
2746 };
Winson Chung81b52252012-08-27 15:34:29 -07002747 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002748 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002749
Winson Chung4a2afa32012-07-19 14:53:05 -07002750 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2751 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002752 synchronized (mDeferredBindRunnables) {
2753 mDeferredBindRunnables.clear();
2754 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002755 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002756 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002757
2758 // Tell the workspace that we're done binding items
2759 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002760 public void run() {
2761 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2762 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002763 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002764 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002765
Winson Chung98e030b2012-05-07 16:01:11 -07002766 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002767 if (DEBUG_LOADERS) {
2768 Log.d(TAG, "bound workspace in "
2769 + (SystemClock.uptimeMillis()-t) + "ms");
2770 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002771
2772 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002773 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002774 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002775 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002776 synchronized (mDeferredBindRunnables) {
2777 mDeferredBindRunnables.add(r);
2778 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002779 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002780 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002781 }
Joe Onorato36115782010-06-17 13:28:48 -04002782 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002783
Joe Onorato36115782010-06-17 13:28:48 -04002784 private void loadAndBindAllApps() {
2785 if (DEBUG_LOADERS) {
2786 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2787 }
2788 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002789 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002790 synchronized (LoaderTask.this) {
2791 if (mStopped) {
2792 return;
2793 }
2794 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002795 }
Joe Onorato36115782010-06-17 13:28:48 -04002796 } else {
2797 onlyBindAllApps();
2798 }
2799 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002800
Joe Onorato36115782010-06-17 13:28:48 -04002801 private void onlyBindAllApps() {
2802 final Callbacks oldCallbacks = mCallbacks.get();
2803 if (oldCallbacks == null) {
2804 // This launcher has exited and nobody bothered to tell us. Just bail.
2805 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2806 return;
2807 }
2808
2809 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002810 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002811 final ArrayList<AppInfo> list
2812 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002813 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002814 public void run() {
2815 final long t = SystemClock.uptimeMillis();
2816 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2817 if (callbacks != null) {
2818 callbacks.bindAllApplications(list);
2819 }
2820 if (DEBUG_LOADERS) {
2821 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2822 + (SystemClock.uptimeMillis()-t) + "ms");
2823 }
2824 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002825 };
2826 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002827 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002828 r.run();
2829 } else {
2830 mHandler.post(r);
2831 }
Joe Onorato36115782010-06-17 13:28:48 -04002832 }
2833
Winson Chung64359a52013-07-08 17:17:08 -07002834 private void loadAllApps() {
2835 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002836
Joe Onorato36115782010-06-17 13:28:48 -04002837 final Callbacks oldCallbacks = mCallbacks.get();
2838 if (oldCallbacks == null) {
2839 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002840 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002841 return;
2842 }
2843
2844 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2845 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2846
Kenny Guyed131872014-04-30 03:02:21 +01002847 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2848
Winson Chung64359a52013-07-08 17:17:08 -07002849 // Clear the list of apps
2850 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002851 for (UserHandleCompat user : profiles) {
2852 // Query for the set of apps
2853 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2854 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2855 if (DEBUG_LOADERS) {
2856 Log.d(TAG, "getActivityList took "
2857 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2858 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2859 }
2860 // Fail if we don't have any apps
2861 if (apps == null || apps.isEmpty()) {
2862 return;
2863 }
2864 // Sort the applications by name
2865 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2866 Collections.sort(apps,
2867 new LauncherModel.ShortcutNameComparator(mLabelCache));
2868 if (DEBUG_LOADERS) {
2869 Log.d(TAG, "sort took "
2870 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2871 }
Joe Onorato36115782010-06-17 13:28:48 -04002872
Kenny Guyed131872014-04-30 03:02:21 +01002873 // Create the ApplicationInfos
2874 for (int i = 0; i < apps.size(); i++) {
2875 LauncherActivityInfoCompat app = apps.get(i);
2876 // This builds the icon bitmaps.
2877 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2878 }
Winson Chung64359a52013-07-08 17:17:08 -07002879 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002880 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002881 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2882 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002883
2884 // Post callback on main thread
2885 mHandler.post(new Runnable() {
2886 public void run() {
2887 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002888 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002889 if (callbacks != null) {
2890 callbacks.bindAllApplications(added);
2891 if (DEBUG_LOADERS) {
2892 Log.d(TAG, "bound " + added.size() + " apps in "
2893 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2894 }
2895 } else {
2896 Log.i(TAG, "not binding apps: no Launcher activity");
2897 }
2898 }
2899 });
2900
Joe Onorato36115782010-06-17 13:28:48 -04002901 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002902 Log.d(TAG, "Icons processed in "
2903 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002904 }
2905 }
2906
2907 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002908 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002909 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2910 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2911 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2912 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2913 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2914 }
Joe Onorato36115782010-06-17 13:28:48 -04002915 }
2916 }
2917
2918 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002919 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002920 }
2921
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002922 private class AppsAvailabilityCheck extends BroadcastReceiver {
2923
2924 @Override
2925 public void onReceive(Context context, Intent intent) {
2926 synchronized (sBgLock) {
2927 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2928 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002929 final PackageManager manager = context.getPackageManager();
2930 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2931 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002932 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2933 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002934 packagesRemoved.clear();
2935 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 for (String pkg : entry.getValue()) {
2937 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002938 boolean packageOnSdcard = launcherApps.isAppEnabled(
2939 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2940 if (packageOnSdcard) {
2941 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2942 packagesUnavailable.add(pkg);
2943 } else {
2944 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2945 packagesRemoved.add(pkg);
2946 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002947 }
2948 }
2949 if (!packagesRemoved.isEmpty()) {
2950 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2951 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2952 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002953 if (!packagesUnavailable.isEmpty()) {
2954 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2955 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2956 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002957 }
Sunny Goyal34942622014-08-29 17:20:55 -07002958 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002959 }
2960 }
2961 }
2962
Joe Onorato36115782010-06-17 13:28:48 -04002963 private class PackageUpdatedTask implements Runnable {
2964 int mOp;
2965 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002966 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002967
2968 public static final int OP_NONE = 0;
2969 public static final int OP_ADD = 1;
2970 public static final int OP_UPDATE = 2;
2971 public static final int OP_REMOVE = 3; // uninstlled
2972 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2973
2974
Kenny Guyed131872014-04-30 03:02:21 +01002975 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002976 mOp = op;
2977 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002978 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002979 }
2980
2981 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002982 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002983
2984 final String[] packages = mPackages;
2985 final int N = packages.length;
2986 switch (mOp) {
2987 case OP_ADD:
2988 for (int i=0; i<N; i++) {
2989 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002990 mIconCache.remove(packages[i], mUser);
2991 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002992 }
2993 break;
2994 case OP_UPDATE:
2995 for (int i=0; i<N; i++) {
2996 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002997 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002998 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002999 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003000 }
3001 break;
3002 case OP_REMOVE:
3003 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003004 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003005 for (int i=0; i<N; i++) {
3006 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003007 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003008 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003009 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003010 }
3011 break;
3012 }
3013
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003014 ArrayList<AppInfo> added = null;
3015 ArrayList<AppInfo> modified = null;
3016 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003017
Adam Cohen487f7dd2012-06-28 18:12:10 -07003018 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003019 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003020 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003021 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003022 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003023 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003024 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003025 }
Winson Chung5d55f332012-07-16 20:45:03 -07003026 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003027 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003028 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003029 }
3030
Joe Onorato36115782010-06-17 13:28:48 -04003031 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
3032 if (callbacks == null) {
3033 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3034 return;
3035 }
3036
3037 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003038 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003039 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003040 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003041 addAndBindAddedWorkspaceApps(context, addedInfos);
3042 } else {
3043 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003044 }
Joe Onorato36115782010-06-17 13:28:48 -04003045 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003046
Joe Onorato36115782010-06-17 13:28:48 -04003047 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003048 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07003049
3050 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003051 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07003052 ArrayList<ItemInfo> infos =
Kenny Guyed131872014-04-30 03:02:21 +01003053 getItemInfoForComponentName(a.componentName, mUser);
Winson Chung64359a52013-07-08 17:17:08 -07003054 for (ItemInfo i : infos) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003055 if (i instanceof ShortcutInfo && isShortcutAppTarget((ShortcutInfo) i)) {
Winson Chung64359a52013-07-08 17:17:08 -07003056 ShortcutInfo info = (ShortcutInfo) i;
3057 info.title = a.title.toString();
Kenny Guyc2bd8102014-06-30 12:30:31 +01003058 info.contentDescription = a.contentDescription;
Winson Chung64359a52013-07-08 17:17:08 -07003059 updateItemInDatabase(context, info);
3060 }
3061 }
3062 }
3063
Joe Onorato36115782010-06-17 13:28:48 -04003064 mHandler.post(new Runnable() {
3065 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003066 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3067 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003068 callbacks.bindAppsUpdated(modifiedFinal);
3069 }
3070 }
3071 });
3072 }
Winson Chung83892cc2013-05-01 16:53:33 -07003073
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003074 // Update shortcuts which use an iconResource
3075 if (mOp == OP_ADD || mOp == OP_UPDATE) {
3076 final ArrayList<ShortcutInfo> iconsChanged = new ArrayList<ShortcutInfo>();
3077 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyal1a745e82014-10-02 15:58:31 -07003078 // We need to iterate over the items here, so that we can avoid new Bitmap
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003079 // creation on the UI thread.
3080 synchronized (sBgLock) {
3081 for (ItemInfo info : sBgWorkspaceItems) {
3082 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3083 ShortcutInfo si = (ShortcutInfo) info;
3084 if ((si.iconResource != null)
3085 && packageSet.contains(si.getTargetComponent().getPackageName())){
3086 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3087 si.iconResource.resourceName, mIconCache, context);
3088 if (icon != null) {
3089 si.setIcon(icon);
3090 si.usingFallbackIcon = false;
3091 iconsChanged.add(si);
3092 updateItemInDatabase(context, si);
3093 }
3094 }
3095 }
3096 }
3097 }
3098
3099 if (!iconsChanged.isEmpty()) {
3100 mHandler.post(new Runnable() {
3101 public void run() {
3102 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3103 if (callbacks == cb && cb != null) {
3104 callbacks.bindShortcutsUpdated(iconsChanged);
3105 }
3106 }
3107 });
3108 }
3109 }
3110
Winson Chungdf95eb12013-10-16 14:57:07 -07003111 final ArrayList<String> removedPackageNames =
3112 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003113 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003114 // Mark all packages in the broadcast to be removed
3115 removedPackageNames.addAll(Arrays.asList(packages));
3116 } else if (mOp == OP_UPDATE) {
3117 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003118 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003119 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003120 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003121 }
3122 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003123 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003124
Winson Chungdf95eb12013-10-16 14:57:07 -07003125 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003126 final int removeReason;
3127 if (mOp == OP_UNAVAILABLE) {
3128 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3129 } else {
3130 // Remove all the components associated with this package
3131 for (String pn : removedPackageNames) {
3132 deletePackageFromDatabase(context, pn, mUser);
3133 }
3134 // Remove all the specific components
3135 for (AppInfo a : removedApps) {
3136 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3137 deleteItemsFromDatabase(context, infos);
3138 }
3139 removeReason = 0;
3140 }
3141
Winson Chungdf95eb12013-10-16 14:57:07 -07003142 // Remove any queued items from the install queue
3143 String spKey = LauncherAppState.getSharedPreferencesKey();
3144 SharedPreferences sp =
3145 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
3146 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
3147 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003148 mHandler.post(new Runnable() {
3149 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003150 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3151 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003152 callbacks.bindComponentsRemoved(
3153 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003154 }
3155 }
3156 });
Joe Onoratobe386092009-11-17 17:32:16 -08003157 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003158
Michael Jurkac402cd92013-05-20 15:49:32 +02003159 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003160 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003161 mHandler.post(new Runnable() {
3162 @Override
3163 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07003164 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3165 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003166 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003167 }
3168 }
3169 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003170
3171 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003172 mHandler.post(new Runnable() {
3173 public void run() {
3174 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
3175 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003176 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003177 }
3178 }
3179 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003180 }
3181 }
3182
Michael Jurkac402cd92013-05-20 15:49:32 +02003183 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3184 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3185 PackageManager packageManager = context.getPackageManager();
3186 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003187 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3188
Michael Jurkac402cd92013-05-20 15:49:32 +02003189 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3190 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003191 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003192 return widgetsAndShortcuts;
3193 }
3194
Kenny Guyed131872014-04-30 03:02:21 +01003195 private static boolean isPackageDisabled(Context context, String packageName,
3196 UserHandleCompat user) {
3197 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3198 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003199 }
Adam Cohen556f6132014-01-15 15:18:08 -08003200
Kenny Guyed131872014-04-30 03:02:21 +01003201 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3202 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003203 if (cn == null) {
3204 return false;
3205 }
Kenny Guyed131872014-04-30 03:02:21 +01003206 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3207 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003208 return false;
3209 }
Kenny Guyed131872014-04-30 03:02:21 +01003210 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003211 }
3212
Adam Cohena28b78e2014-05-20 17:03:04 -07003213 public static boolean isValidPackage(Context context, String packageName,
3214 UserHandleCompat user) {
3215 if (packageName == null) {
3216 return false;
3217 }
3218 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3219 return launcherApps.isPackageEnabledForProfile(packageName, user);
3220 }
3221
Joe Onorato9c1289c2009-08-17 11:03:03 -04003222 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003223 * Make an ShortcutInfo object for a restored application or shortcut item that points
3224 * to a package that is not yet installed on the system.
3225 */
Sunny Goyal34942622014-08-29 17:20:55 -07003226 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3227 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003228 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003229 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003230 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3231
3232 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3233 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3234 if (!TextUtils.isEmpty(title)) {
3235 info.title = title;
3236 }
3237 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3238 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3239 if (TextUtils.isEmpty(info.title)) {
3240 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3241 }
3242 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3243 } else {
3244 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3245 }
3246
Kenny Guyc2bd8102014-06-30 12:30:31 +01003247 info.contentDescription = mUserManager.getBadgedLabelForUser(
3248 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003249 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003250 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003251 return info;
3252 }
3253
3254 /**
3255 * Make an Intent object for a restored application or shortcut item that points
3256 * to the market page for the item.
3257 */
3258 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3259 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003260 return getMarketIntent(componentName.getPackageName());
3261 }
3262
3263 static Intent getMarketIntent(String packageName) {
3264 return new Intent(Intent.ACTION_VIEW)
3265 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003266 .scheme("market")
3267 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003268 .appendQueryParameter("id", packageName)
3269 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003270 }
3271
3272 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003273 * This is called from the code that adds shortcuts from the intent receiver. This
3274 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003275 */
Kenny Guyed131872014-04-30 03:02:21 +01003276 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3277 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003278 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003279 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003280
Joe Onorato56d82912010-03-07 14:32:10 -05003281 /**
3282 * Make an ShortcutInfo object for a shortcut that is an application.
3283 *
3284 * If c is not null, then it will be used to fill in missing data like the title and icon.
3285 */
Kenny Guyed131872014-04-30 03:02:21 +01003286 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3287 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003288 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003289 if (user == null) {
3290 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003291 return null;
3292 }
3293
Kenny Guyed131872014-04-30 03:02:21 +01003294 ComponentName componentName = intent.getComponent();
3295 if (componentName == null) {
3296 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3297 return null;
3298 }
3299
3300 Intent newIntent = new Intent(intent.getAction(), null);
3301 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3302 newIntent.setComponent(componentName);
3303 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003304 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003305 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3306 return null;
3307 }
3308
3309 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003310
Joe Onorato56d82912010-03-07 14:32:10 -05003311 // the resource -- This may implicitly give us back the fallback icon,
3312 // but don't worry about that. All we're doing with usingFallbackIcon is
3313 // to avoid saving lots of copies of that in the database, and most apps
3314 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003315 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003316
Joe Onorato56d82912010-03-07 14:32:10 -05003317 // the db
3318 if (icon == null) {
3319 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003320 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003321 }
3322 }
3323 // the fallback icon
3324 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003325 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003326 info.usingFallbackIcon = true;
3327 }
3328 info.setIcon(icon);
3329
Kenny Guyed131872014-04-30 03:02:21 +01003330 // From the cache.
3331 if (labelCache != null) {
3332 info.title = labelCache.get(componentName);
3333 }
3334
Joe Onorato56d82912010-03-07 14:32:10 -05003335 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003336 if (info.title == null && lai != null) {
3337 info.title = lai.getLabel();
3338 if (labelCache != null) {
3339 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003340 }
Joe Onorato56d82912010-03-07 14:32:10 -05003341 }
3342 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003343 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003344 if (c != null) {
3345 info.title = c.getString(titleIndex);
3346 }
3347 }
3348 // fall back to the class name of the activity
3349 if (info.title == null) {
3350 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003351 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003352 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003353 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003354 info.contentDescription = mUserManager.getBadgedLabelForUser(
3355 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003356 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003357 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003358
Winson Chung64359a52013-07-08 17:17:08 -07003359 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3360 ItemInfoFilter f) {
3361 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3362 for (ItemInfo i : infos) {
3363 if (i instanceof ShortcutInfo) {
3364 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003365 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003366 if (cn != null && f.filterItem(null, info, cn)) {
3367 filtered.add(info);
3368 }
3369 } else if (i instanceof FolderInfo) {
3370 FolderInfo info = (FolderInfo) i;
3371 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003372 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003373 if (cn != null && f.filterItem(info, s, cn)) {
3374 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003375 }
3376 }
Winson Chung64359a52013-07-08 17:17:08 -07003377 } else if (i instanceof LauncherAppWidgetInfo) {
3378 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3379 ComponentName cn = info.providerName;
3380 if (cn != null && f.filterItem(null, info, cn)) {
3381 filtered.add(info);
3382 }
Winson Chung8a435102012-08-30 17:16:53 -07003383 }
3384 }
Winson Chung64359a52013-07-08 17:17:08 -07003385 return new ArrayList<ItemInfo>(filtered);
3386 }
3387
Kenny Guyed131872014-04-30 03:02:21 +01003388 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3389 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003390 ItemInfoFilter filter = new ItemInfoFilter() {
3391 @Override
3392 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003393 if (info.user == null) {
3394 return cn.equals(cname);
3395 } else {
3396 return cn.equals(cname) && info.user.equals(user);
3397 }
Winson Chung64359a52013-07-08 17:17:08 -07003398 }
3399 };
3400 return filterItemInfos(sBgItemsIdMap.values(), filter);
3401 }
3402
Sunny Goyal1a745e82014-10-02 15:58:31 -07003403 /**
3404 * @return true if the ShortcutInfo points to an app shortcut target, i.e. it has been added by
3405 * dragging from AllApps list.
3406 */
3407 public static boolean isShortcutAppTarget(ShortcutInfo info) {
3408 // We need to check for ACTION_MAIN otherwise getComponent() might
3409 // return null for some shortcuts (for instance, for shortcuts to
3410 // web pages.)
3411 Intent intent = info.promisedIntent != null ? info.promisedIntent : info.intent;
3412 ComponentName name = intent.getComponent();
3413 return info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3414 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null;
Winson Chung8a435102012-08-30 17:16:53 -07003415 }
3416
3417 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003418 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003419 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003420 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003421 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3422 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003423
Joe Onorato56d82912010-03-07 14:32:10 -05003424 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003425 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003426 // Non-app shortcuts are only supported for current user.
3427 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003428 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003429
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003430 // TODO: If there's an explicit component and we can't install that, delete it.
3431
Joe Onorato56d82912010-03-07 14:32:10 -05003432 info.title = c.getString(titleIndex);
3433
Joe Onorato9c1289c2009-08-17 11:03:03 -04003434 int iconType = c.getInt(iconTypeIndex);
3435 switch (iconType) {
3436 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3437 String packageName = c.getString(iconPackageIndex);
3438 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003439 info.customIcon = false;
3440 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003441 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003442 // the db
3443 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003444 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003445 }
3446 // the fallback icon
3447 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003448 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003449 info.usingFallbackIcon = true;
3450 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003451 break;
3452 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003453 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003454 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003455 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003456 info.customIcon = false;
3457 info.usingFallbackIcon = true;
3458 } else {
3459 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003460 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003461 break;
3462 default:
Kenny Guyed131872014-04-30 03:02:21 +01003463 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003464 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003465 info.customIcon = false;
3466 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003467 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003468 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003469 return info;
3470 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003471
Michael Jurka931dc972011-08-05 15:08:15 -07003472 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003473 @SuppressWarnings("all") // suppress dead code warning
3474 final boolean debug = false;
3475 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003476 Log.d(TAG, "getIconFromCursor app="
3477 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3478 }
3479 byte[] data = c.getBlob(iconIndex);
3480 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003481 return Utilities.createIconBitmap(
3482 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003483 } catch (Exception e) {
3484 return null;
3485 }
3486 }
3487
Winson Chunga9abd0e2010-10-27 17:18:37 -07003488 /**
Winson Chung55cef262010-10-28 14:14:18 -07003489 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3490 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003491 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003492 ComponentName component) {
3493 List<AppWidgetProviderInfo> widgets =
3494 AppWidgetManager.getInstance(context).getInstalledProviders();
3495 for (AppWidgetProviderInfo info : widgets) {
3496 if (info.provider.equals(component)) {
3497 return info;
3498 }
3499 }
3500 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003501 }
3502
Sunny Goyal2350bc92014-10-14 16:42:54 -07003503 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003504 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3505 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3506 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3507
Adam Cohend9198822011-11-22 16:42:47 -08003508 if (intent == null) {
3509 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3510 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3511 return null;
3512 }
3513
Joe Onorato0589f0f2010-02-08 13:44:00 -08003514 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003515 boolean customIcon = false;
3516 ShortcutIconResource iconResource = null;
3517
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003518 if (bitmap instanceof Bitmap) {
3519 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003520 customIcon = true;
3521 } else {
3522 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003523 if (extra instanceof ShortcutIconResource) {
3524 iconResource = (ShortcutIconResource) extra;
3525 icon = Utilities.createIconBitmap(iconResource.packageName,
3526 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003527 }
3528 }
3529
Michael Jurkac9d95c52011-08-29 14:03:34 -07003530 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003531
Kenny Guyed131872014-04-30 03:02:21 +01003532 // Only support intents for current user for now. Intents sent from other
3533 // users wouldn't get here without intent forwarding anyway.
3534 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003535 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003536 icon = mIconCache.getDefaultIcon(info.user);
3537 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003538 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003539 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003540
Joe Onorato0589f0f2010-02-08 13:44:00 -08003541 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003542 info.contentDescription = mUserManager.getBadgedLabelForUser(
3543 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003544 info.intent = intent;
3545 info.customIcon = customIcon;
3546 info.iconResource = iconResource;
3547
3548 return info;
3549 }
3550
Winson Chungaac01e12011-08-17 10:37:13 -07003551 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3552 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003553 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003554 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003555 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003556 }
Joe Onorato56d82912010-03-07 14:32:10 -05003557 // If this icon doesn't have a custom icon, check to see
3558 // what's stored in the DB, and if it doesn't match what
3559 // we're going to show, store what we are going to show back
3560 // into the DB. We do this so when we're loading, if the
3561 // package manager can't find an icon (for example because
3562 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003563 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003564 cache.put(info, c.getBlob(iconIndex));
3565 return true;
3566 }
3567 return false;
3568 }
3569 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3570 boolean needSave = false;
3571 try {
3572 if (data != null) {
3573 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3574 Bitmap loaded = info.getIcon(mIconCache);
3575 needSave = !saved.sameAs(loaded);
3576 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003577 needSave = true;
3578 }
Winson Chungaac01e12011-08-17 10:37:13 -07003579 } catch (Exception e) {
3580 needSave = true;
3581 }
3582 if (needSave) {
3583 Log.d(TAG, "going to save icon bitmap for info=" + info);
3584 // This is slower than is ideal, but this only happens once
3585 // or when the app is updated with a new icon.
3586 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003587 }
3588 }
3589
Joe Onorato9c1289c2009-08-17 11:03:03 -04003590 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003591 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003592 * or make a new one.
3593 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003594 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003595 // See if a placeholder was created for us already
3596 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003597 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003598 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003599 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003600 folders.put(id, folderInfo);
3601 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003602 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003603 }
3604
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003605 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003606 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003607 return new Comparator<AppInfo>() {
3608 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003609 if (a.user.equals(b.user)) {
3610 int result = collator.compare(a.title.toString().trim(),
3611 b.title.toString().trim());
3612 if (result == 0) {
3613 result = a.componentName.compareTo(b.componentName);
3614 }
3615 return result;
3616 } else {
3617 // TODO Need to figure out rules for sorting
3618 // profiles, this puts work second.
3619 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003620 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003621 }
Winson Chung11904872012-09-17 16:58:46 -07003622 };
3623 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003624 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3625 = new Comparator<AppInfo>() {
3626 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003627 if (a.firstInstallTime < b.firstInstallTime) return 1;
3628 if (a.firstInstallTime > b.firstInstallTime) return -1;
3629 return 0;
3630 }
3631 };
Winson Chung5308f242011-08-18 12:12:41 -07003632 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3633 if (info.activityInfo != null) {
3634 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3635 } else {
3636 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3637 }
3638 }
Kenny Guyed131872014-04-30 03:02:21 +01003639 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003640 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003641 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003642 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003643 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003644 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003645 }
Kenny Guyed131872014-04-30 03:02:21 +01003646 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003647 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003648 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003649 }
Kenny Guyed131872014-04-30 03:02:21 +01003650 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003651 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003652 ComponentName keyA = a.getComponentName();
3653 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003654 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003655 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003656 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003657 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003658
Winson Chung5308f242011-08-18 12:12:41 -07003659 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003660 }
Winson Chung5308f242011-08-18 12:12:41 -07003661 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003662 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003663 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003664 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003665
Winson Chung5308f242011-08-18 12:12:41 -07003666 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003667 }
Winson Chung11904872012-09-17 16:58:46 -07003668 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003669 }
3670 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003671 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003672 private final AppWidgetManagerCompat mManager;
3673 private final PackageManager mPackageManager;
3674 private final HashMap<Object, String> mLabelCache;
3675 private final Collator mCollator;
3676
3677 WidgetAndShortcutNameComparator(Context context) {
3678 mManager = AppWidgetManagerCompat.getInstance(context);
3679 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003680 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003681 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003682 }
3683 public final int compare(Object a, Object b) {
3684 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003685 if (mLabelCache.containsKey(a)) {
3686 labelA = mLabelCache.get(a);
3687 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003688 labelA = (a instanceof AppWidgetProviderInfo)
3689 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3690 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003691 mLabelCache.put(a, labelA);
3692 }
3693 if (mLabelCache.containsKey(b)) {
3694 labelB = mLabelCache.get(b);
3695 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003696 labelB = (b instanceof AppWidgetProviderInfo)
3697 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3698 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003699 mLabelCache.put(b, labelB);
3700 }
Winson Chung11904872012-09-17 16:58:46 -07003701 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003702 }
3703 };
Joe Onoratobe386092009-11-17 17:32:16 -08003704
Sunny Goyal651077b2014-06-30 14:15:31 -07003705 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3706 return (provider != null) && (provider.provider != null)
3707 && (provider.provider.getPackageName() != null);
3708 }
3709
Joe Onoratobe386092009-11-17 17:32:16 -08003710 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003711 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003712 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3713 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3714 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3715 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003716 if (mLoaderTask != null) {
3717 mLoaderTask.dumpState();
3718 } else {
3719 Log.d(TAG, "mLoaderTask=null");
3720 }
Joe Onoratobe386092009-11-17 17:32:16 -08003721 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003722}