blob: 954887dc31c7359ae2a2e04e834d668d6a99d05b [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;
Sunny Goyale0f58d72014-11-10 18:05:31 -080033import android.content.pm.LauncherApps.Callback;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040035import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070037import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.content.res.Resources;
39import android.database.Cursor;
40import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
42import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080043import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040044import android.os.Handler;
45import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080046import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080047import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070048import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040049import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040050import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080051import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070052import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070053import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.LauncherActivityInfoCompat;
57import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070058import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070059import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010060import com.android.launcher3.compat.UserHandleCompat;
61import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080062
Michael Jurkac2f801e2011-07-12 14:19:46 -070063import java.lang.ref.WeakReference;
64import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070065import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070066import java.text.Collator;
67import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070068import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070069import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070070import java.util.Collections;
71import java.util.Comparator;
72import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070073import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070074import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070075import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070076import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070078import java.util.TreeMap;
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;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080090 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040091
Joe Onorato9c1289c2009-08-17 11:03:03 -040092 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070093
Daniel Sandler8707e0f2013-08-15 15:54:18 -070094 // true = use a "More Apps" folder for non-workspace apps on upgrade
95 // false = strew non-workspace apps across the workspace on upgrade
96 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050097 public static final int LOADER_FLAG_NONE = 0;
98 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
99 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
100
Joe Onorato36115782010-06-17 13:28:48 -0400101 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500102 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800103
Winson Chungee055712013-07-30 14:46:24 -0700104 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800105 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400106
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400107 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400108 private final Object mLock = new Object();
109 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400110 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700111 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200112 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
Sunny Goyale0f58d72014-11-10 18:05:31 -0800114 /**
115 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
116 */
117 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
118
Winson Chung81b52252012-08-27 15:34:29 -0700119 // Specific runnable types that are run on the main thread deferred handler, this allows us to
120 // clear all queued binding runnables when the Launcher activity is destroyed.
121 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
122 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
123
Jason Monkbbe1e242014-05-16 17:37:34 -0400124 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700125
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700126 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
127 static {
128 sWorkerThread.start();
129 }
130 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
131
Joe Onoratocc67f472010-06-08 10:54:30 -0700132 // We start off with everything not loaded. After that, we assume that
133 // our monitoring of the package manager provides all updates and we never
134 // need to do a requery. These are only ever touched from the loader thread.
135 private boolean mWorkspaceLoaded;
136 private boolean mAllAppsLoaded;
137
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700138 // When we are loading pages synchronously, we can't just post the binding of items on the side
139 // pages as this delays the rotation process. Instead, we wait for a callback from the first
140 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
141 // a normal load, we also clear this set of Runnables.
142 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
143
Joe Onorato9c1289c2009-08-17 11:03:03 -0400144 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700146 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700147 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800148
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700149 // The lock that must be acquired before referencing any static bg data structures. Unlike
150 // other locks, this one can generally be held long-term because we never expect any of these
151 // static data structures to be referenced outside of the worker thread except on the first
152 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700153 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700157 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
160 // created by LauncherModel that are directly on the home screen (however, no widgets or
161 // shortcuts within folders).
162 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700163
Adam Cohen487f7dd2012-06-28 18:12:10 -0700164 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
165 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700166 new ArrayList<LauncherAppWidgetInfo>();
167
Adam Cohen487f7dd2012-06-28 18:12:10 -0700168 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
169 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700170
Adam Cohen487f7dd2012-06-28 18:12:10 -0700171 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
172 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700173
174 // sBgWorkspaceScreens is the ordered set of workspace screens.
175 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
176
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700177 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700178 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
179 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700180
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 // </ only access in worker thread >
182
183 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
Reena Lee99a73f32011-10-24 17:27:37 -0700185 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700186
Kenny Guyed131872014-04-30 03:02:21 +0100187 private final LauncherAppsCompat mLauncherApps;
188 private final UserManagerCompat mUserManager;
189
Joe Onorato9c1289c2009-08-17 11:03:03 -0400190 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700191 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400192 public int getCurrentWorkspaceScreen();
193 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700194 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
195 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700196 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700197 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500198 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700199 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400200 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200201 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700202 public void bindAppsAdded(ArrayList<Long> newScreens,
203 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700204 ArrayList<ItemInfo> addAnimated,
205 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200206 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700207 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
208 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
209 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700210 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700211 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700212 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700213 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200214 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100215 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700216 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700217 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700218 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400219 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220
Winson Chung64359a52013-07-08 17:17:08 -0700221 public interface ItemInfoFilter {
222 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
223 }
224
Bjorn Bringert1307f632013-10-03 22:31:03 +0100225 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800226 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400227
Winson Chungee055712013-07-30 14:46:24 -0700228 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700229 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400230 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
231 // resource string.
232 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
233 ProviderInfo providerInfo =
234 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
235 ProviderInfo redirectProvider =
236 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700237
238 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400239 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700240
241 if (mOldContentProviderExists) {
242 Log.d(TAG, "Old launcher provider exists.");
243 } else {
244 Log.d(TAG, "Old launcher provider does not exist.");
245 }
246
Daniel Sandlere4f98912013-06-25 15:13:26 -0400247 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100248 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800249 mIconCache = iconCache;
250
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400251 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700252 Configuration config = res.getConfiguration();
253 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100254 mLauncherApps = LauncherAppsCompat.getInstance(context);
255 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800256 }
257
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700258 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
259 * posted on the main thread handler. */
260 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700261 runOnMainThread(r, 0);
262 }
263 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700264 if (sWorkerThread.getThreadId() == Process.myTid()) {
265 // If we are on the worker thread, post onto the main handler
266 mHandler.post(r);
267 } else {
268 r.run();
269 }
270 }
271
272 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
273 * posted on the worker thread handler. */
274 private static void runOnWorkerThread(Runnable r) {
275 if (sWorkerThread.getThreadId() == Process.myTid()) {
276 r.run();
277 } else {
278 // If we are not on the worker thread, then post to the worker handler
279 sWorker.post(r);
280 }
281 }
282
Winson Chunge43a1e72014-01-15 10:33:02 -0800283 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
284 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800285 }
286
Winson Chungc9168342013-06-26 14:54:55 -0700287 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
288 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700289 LauncherAppState app = LauncherAppState.getInstance();
290 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
291 final int xCount = (int) grid.numColumns;
292 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700293 boolean[][] occupied = new boolean[xCount][yCount];
294
295 int cellX, cellY, spanX, spanY;
296 for (int i = 0; i < items.size(); ++i) {
297 final ItemInfo item = items.get(i);
298 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
299 if (item.screenId == screen) {
300 cellX = item.cellX;
301 cellY = item.cellY;
302 spanX = item.spanX;
303 spanY = item.spanY;
304 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
305 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
306 occupied[x][y] = true;
307 }
308 }
309 }
310 }
311 }
312
313 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
314 }
315 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700316 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700317 int firstScreenIndex,
318 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700319 // Lock on the app so that we don't try and get the items while apps are being added
320 LauncherAppState app = LauncherAppState.getInstance();
321 LauncherModel model = app.getModel();
322 boolean found = false;
323 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700324 if (sWorkerThread.getThreadId() != Process.myTid()) {
325 // Flush the LauncherModel worker thread, so that if we just did another
326 // processInstallShortcut, we give it time for its shortcut to get added to the
327 // database (getItemsInLocalCoordinates reads the database)
328 model.flushWorkerThread();
329 }
Winson Chungc9168342013-06-26 14:54:55 -0700330 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700331
332 // Try adding to the workspace screens incrementally, starting at the default or center
333 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700334 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
335 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700336 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700337 int[] tmpCoordinates = new int[2];
338 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700339 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700340 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700341 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700342 }
343 }
344 }
Winson Chungc9168342013-06-26 14:54:55 -0700345 return null;
346 }
347
Sunny Goyale755d462014-07-22 13:48:29 -0700348 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500349 // Process the updated package state
350 Runnable r = new Runnable() {
351 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800352 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500353 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700354 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500355 }
356 }
357 };
358 mHandler.post(r);
359 }
360
Sunny Goyala22666f2014-09-18 13:25:15 -0700361 public void updatePackageBadge(final String packageName) {
362 // Process the updated package badge
363 Runnable r = new Runnable() {
364 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800365 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700366 if (callbacks != null) {
367 callbacks.updatePackageBadge(packageName);
368 }
369 }
370 };
371 mHandler.post(r);
372 }
373
Adam Cohen76a47a12014-02-05 11:47:43 -0800374 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800375 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800376
377 if (allAppsApps == null) {
378 throw new RuntimeException("allAppsApps must not be null");
379 }
380 if (allAppsApps.isEmpty()) {
381 return;
382 }
383
384 // Process the newly added applications and add them to the database first
385 Runnable r = new Runnable() {
386 public void run() {
387 runOnMainThread(new Runnable() {
388 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800389 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800390 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500391 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800392 }
393 }
394 });
395 }
396 };
397 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700398 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800399
400 public void addAndBindAddedWorkspaceApps(final Context context,
401 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800402 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800403
404 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800405 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
406 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800407 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700408 return;
Winson Chung997a9232013-07-24 15:33:46 -0700409 }
Winson Chung64359a52013-07-08 17:17:08 -0700410 // Process the newly added applications and add them to the database first
411 Runnable r = new Runnable() {
412 public void run() {
413 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
414 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
415
Winson Chung76828c82013-08-19 15:43:29 -0700416 // Get the list of workspace screens. We need to append to this list and
417 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
418 // called.
419 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
420 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
421 for (Integer i : orderedScreens.keySet()) {
422 long screenId = orderedScreens.get(i);
423 workspaceScreens.add(screenId);
424 }
425
Winson Chung64359a52013-07-08 17:17:08 -0700426 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700427 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700428 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700429 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700430 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700431 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700432
433 // Short-circuit this logic if the icon exists somewhere on the workspace
Sunny Goyale0f58d72014-11-10 18:05:31 -0800434 if (shortcutExists(context, name, launchIntent, a.user)) {
Winson Chung64359a52013-07-08 17:17:08 -0700435 continue;
436 }
437
Winson Chung87412982013-10-03 18:34:14 -0700438 // Add this icon to the db, creating a new page if necessary. If there
439 // is only the empty page then we just add items to the first page.
440 // Otherwise, we add them to the next pages.
441 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700442 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700443 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700444 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200445 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700446
447 // If we can't find a valid position, then just add a new screen.
448 // This takes time so we need to re-queue the add until the new
449 // page is added. Create as many screens as necessary to satisfy
450 // the startSearchPageIndex.
451 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700452 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700453 while (numPagesToAdd > 0) {
454 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700455 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700456 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700457 addedWorkspaceScreensFinal.add(screenId);
458 numPagesToAdd--;
459 }
Winson Chung76828c82013-08-19 15:43:29 -0700460
Winson Chung64359a52013-07-08 17:17:08 -0700461 // Find the coordinate again
462 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700463 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700464 }
465 if (coords == null) {
466 throw new RuntimeException("Coordinates should not be null");
467 }
468
Winson Chung997a9232013-07-24 15:33:46 -0700469 ShortcutInfo shortcutInfo;
470 if (a instanceof ShortcutInfo) {
471 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200472 } else if (a instanceof AppInfo) {
473 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700474 } else {
475 throw new RuntimeException("Unexpected info type");
476 }
Winson Chung94d67682013-09-25 16:29:40 -0700477
Winson Chung64359a52013-07-08 17:17:08 -0700478 // Add the shortcut to the db
479 addItemToDatabase(context, shortcutInfo,
480 LauncherSettings.Favorites.CONTAINER_DESKTOP,
481 coords.first, coords.second[0], coords.second[1], false);
482 // Save the ShortcutInfo for binding in the workspace
483 addedShortcutsFinal.add(shortcutInfo);
484 }
485 }
486
Winson Chung76828c82013-08-19 15:43:29 -0700487 // Update the workspace screens
488 updateWorkspaceScreenOrder(context, workspaceScreens);
489
Adam Cohen76a47a12014-02-05 11:47:43 -0800490 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700491 runOnMainThread(new Runnable() {
492 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800493 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700494 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700495 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
496 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700497 if (!addedShortcutsFinal.isEmpty()) {
498 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
499 long lastScreenId = info.screenId;
500 for (ItemInfo i : addedShortcutsFinal) {
501 if (i.screenId == lastScreenId) {
502 addAnimated.add(i);
503 } else {
504 addNotAnimated.add(i);
505 }
Winson Chung997a9232013-07-24 15:33:46 -0700506 }
507 }
Winson Chungd64d1762013-08-20 14:37:16 -0700508 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800509 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700510 }
Winson Chung64359a52013-07-08 17:17:08 -0700511 }
Winson Chung997a9232013-07-24 15:33:46 -0700512 });
513 }
Winson Chung64359a52013-07-08 17:17:08 -0700514 }
515 };
516 runOnWorkerThread(r);
517 }
518
Winson Chung81b52252012-08-27 15:34:29 -0700519 public void unbindItemInfosAndClearQueuedBindRunnables() {
520 if (sWorkerThread.getThreadId() == Process.myTid()) {
521 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
522 "main thread");
523 }
524
525 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400526 synchronized (mDeferredBindRunnables) {
527 mDeferredBindRunnables.clear();
528 }
Winson Chung81b52252012-08-27 15:34:29 -0700529 // Remove any queued bind runnables
530 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
531 // Unbind all the workspace items
532 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700533 }
534
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700535 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700536 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700537 // Ensure that we don't use the same workspace items data structure on the main thread
538 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700539 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
540 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700541 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700542 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
543 tmpAppWidgets.addAll(sBgAppWidgets);
544 }
545 Runnable r = new Runnable() {
546 @Override
547 public void run() {
548 for (ItemInfo item : tmpWorkspaceItems) {
549 item.unbind();
550 }
551 for (ItemInfo item : tmpAppWidgets) {
552 item.unbind();
553 }
554 }
555 };
556 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700557 }
558
Joe Onorato9c1289c2009-08-17 11:03:03 -0400559 /**
560 * Adds an item to the DB if it was not created previously, or move it to a new
561 * <container, screen, cellX, cellY>
562 */
563 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700564 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400565 if (item.container == ItemInfo.NO_ID) {
566 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700567 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400568 } else {
569 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800571 }
572 }
573
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700574 static void checkItemInfoLocked(
575 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
576 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
577 if (modelItem != null && item != modelItem) {
578 // check all the data is consistent
579 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
580 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
581 ShortcutInfo shortcut = (ShortcutInfo) item;
582 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
583 modelShortcut.intent.filterEquals(shortcut.intent) &&
584 modelShortcut.id == shortcut.id &&
585 modelShortcut.itemType == shortcut.itemType &&
586 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700587 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700588 modelShortcut.cellX == shortcut.cellX &&
589 modelShortcut.cellY == shortcut.cellY &&
590 modelShortcut.spanX == shortcut.spanX &&
591 modelShortcut.spanY == shortcut.spanY &&
592 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
593 (modelShortcut.dropPos != null &&
594 shortcut.dropPos != null &&
595 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
596 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
597 // For all intents and purposes, this is the same object
598 return;
599 }
600 }
601
602 // the modelItem needs to match up perfectly with item if our model is
603 // to be consistent with the database-- for now, just require
604 // modelItem == item or the equality check above
605 String msg = "item: " + ((item != null) ? item.toString() : "null") +
606 "modelItem: " +
607 ((modelItem != null) ? modelItem.toString() : "null") +
608 "Error: ItemInfo passed to checkItemInfo doesn't match original";
609 RuntimeException e = new RuntimeException(msg);
610 if (stackTrace != null) {
611 e.setStackTrace(stackTrace);
612 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800613 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700614 }
615 }
616
Michael Jurka816474f2012-06-25 14:49:02 -0700617 static void checkItemInfo(final ItemInfo item) {
618 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
619 final long itemId = item.id;
620 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700621 public void run() {
622 synchronized (sBgLock) {
623 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700624 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700625 }
626 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700627 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700628 }
629
Michael Jurkac9d95c52011-08-29 14:03:34 -0700630 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
631 final ItemInfo item, final String callingFunction) {
632 final long itemId = item.id;
633 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
634 final ContentResolver cr = context.getContentResolver();
635
Adam Cohen487f7dd2012-06-28 18:12:10 -0700636 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700637 Runnable r = new Runnable() {
638 public void run() {
639 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700640 updateItemArrays(item, itemId, stackTrace);
641 }
642 };
643 runOnWorkerThread(r);
644 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700645
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700646 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
647 final ArrayList<ItemInfo> items, final String callingFunction) {
648 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700649
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700650 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
651 Runnable r = new Runnable() {
652 public void run() {
653 ArrayList<ContentProviderOperation> ops =
654 new ArrayList<ContentProviderOperation>();
655 int count = items.size();
656 for (int i = 0; i < count; i++) {
657 ItemInfo item = items.get(i);
658 final long itemId = item.id;
659 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
660 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700661
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700662 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
663 updateItemArrays(item, itemId, stackTrace);
664
665 }
666 try {
667 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
668 } catch (Exception e) {
669 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700670 }
671 }
672 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700673 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700674 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700675
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700676 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
677 // Lock on mBgLock *after* the db operation
678 synchronized (sBgLock) {
679 checkItemInfoLocked(itemId, item, stackTrace);
680
681 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
682 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
683 // Item is in a folder, make sure this folder exists
684 if (!sBgFolders.containsKey(item.container)) {
685 // An items container is being set to a that of an item which is not in
686 // the list of Folders.
687 String msg = "item: " + item + " container being set to: " +
688 item.container + ", not in the list of folders";
689 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700690 }
691 }
692
693 // Items are added/removed from the corresponding FolderInfo elsewhere, such
694 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
695 // that are on the desktop, as appropriate
696 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800697 if (modelItem != null &&
698 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
699 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700700 switch (modelItem.itemType) {
701 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
702 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
703 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
704 if (!sBgWorkspaceItems.contains(modelItem)) {
705 sBgWorkspaceItems.add(modelItem);
706 }
707 break;
708 default:
709 break;
710 }
711 } else {
712 sBgWorkspaceItems.remove(modelItem);
713 }
714 }
715 }
716
Michael Jurkac7700af2013-05-14 20:17:58 +0200717 public void flushWorkerThread() {
718 mFlushingWorkerThread = true;
719 Runnable waiter = new Runnable() {
720 public void run() {
721 synchronized (this) {
722 notifyAll();
723 mFlushingWorkerThread = false;
724 }
725 }
726 };
727
728 synchronized(waiter) {
729 runOnWorkerThread(waiter);
730 if (mLoaderTask != null) {
731 synchronized(mLoaderTask) {
732 mLoaderTask.notify();
733 }
734 }
735 boolean success = false;
736 while (!success) {
737 try {
738 waiter.wait();
739 success = true;
740 } catch (InterruptedException e) {
741 }
742 }
743 }
744 }
745
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800746 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400747 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700748 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700749 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700750 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400751 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400752 item.cellX = cellX;
753 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700754
Winson Chung3d503fb2011-07-13 17:25:49 -0700755 // We store hotseat items in canonical form which is this orientation invariant position
756 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700757 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700758 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700759 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700760 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700761 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700762 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400763
764 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400765 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700766 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
767 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700768 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400769
Michael Jurkac9d95c52011-08-29 14:03:34 -0700770 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700771 }
772
773 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700774 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
775 * cellX, cellY have already been updated on the ItemInfos.
776 */
777 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
778 final long container, final int screen) {
779
780 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
781 int count = items.size();
782
783 for (int i = 0; i < count; i++) {
784 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700785 item.container = container;
786
787 // We store hotseat items in canonical form which is this orientation invariant position
788 // in the hotseat
789 if (context instanceof Launcher && screen < 0 &&
790 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700791 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700792 item.cellY);
793 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700794 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700795 }
796
797 final ContentValues values = new ContentValues();
798 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
799 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
800 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700802
803 contentValues.add(values);
804 }
805 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
806 }
807
808 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700809 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800810 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700811 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700812 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700813 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800814 item.cellX = cellX;
815 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700816 item.spanX = spanX;
817 item.spanY = spanY;
818
819 // We store hotseat items in canonical form which is this orientation invariant position
820 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700821 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700822 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700823 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700824 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700825 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700826 }
Adam Cohend4844c32011-02-18 19:25:06 -0800827
Adam Cohend4844c32011-02-18 19:25:06 -0800828 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800829 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700830 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
831 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
832 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
833 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700834 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800835
Michael Jurka816474f2012-06-25 14:49:02 -0700836 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700837 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700838
839 /**
840 * Update an item to the database in a specified container.
841 */
842 static void updateItemInDatabase(Context context, final ItemInfo item) {
843 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100844 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700845 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
846 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800847 }
848
849 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400850 * Returns true if the shortcuts already exists in the database.
851 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800852 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800853 static boolean shortcutExists(Context context, String title, Intent intent,
854 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400855 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700856 final Intent intentWithPkg, intentWithoutPkg;
857
858 if (intent.getComponent() != null) {
859 // If component is not null, an intent with null package will produce
860 // the same result and should also be a match.
861 if (intent.getPackage() != null) {
862 intentWithPkg = intent;
863 intentWithoutPkg = new Intent(intent).setPackage(null);
864 } else {
865 intentWithPkg = new Intent(intent).setPackage(
866 intent.getComponent().getPackageName());
867 intentWithoutPkg = intent;
868 }
869 } else {
870 intentWithPkg = intent;
871 intentWithoutPkg = intent;
872 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800873 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
874 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400875 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800876 new String[] { "title", "intent", "profileId" },
877 "title=? and (intent=? or intent=?) and profileId=?",
878 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
879 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400880 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800881 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400882 } finally {
883 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800884 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700885 }
886
Joe Onorato9c1289c2009-08-17 11:03:03 -0400887 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700888 * Returns an ItemInfo array containing all the items in the LauncherModel.
889 * The ItemInfo.id is not set through this function.
890 */
891 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
892 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
893 final ContentResolver cr = context.getContentResolver();
894 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
895 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100896 LauncherSettings.Favorites.SCREEN,
897 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
898 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
899 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700900
901 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
902 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
903 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
904 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
905 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
906 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
907 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100908 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
909 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700910 try {
911 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700912 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700913 item.cellX = c.getInt(cellXIndex);
914 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700915 item.spanX = Math.max(1, c.getInt(spanXIndex));
916 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700917 item.container = c.getInt(containerIndex);
918 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700919 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100920 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100921 item.user = userManager.getUserForSerialNumber(serialNumber);
922 // Skip if user has been deleted.
923 if (item.user != null) {
924 items.add(item);
925 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700926 }
927 } catch (Exception e) {
928 items.clear();
929 } finally {
930 c.close();
931 }
932
933 return items;
934 }
935
936 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400937 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
938 */
939 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
940 final ContentResolver cr = context.getContentResolver();
941 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
942 "_id=? and (itemType=? or itemType=?)",
943 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700944 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700945
Joe Onorato9c1289c2009-08-17 11:03:03 -0400946 try {
947 if (c.moveToFirst()) {
948 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
949 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
950 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
951 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
952 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
953 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800954
Joe Onorato9c1289c2009-08-17 11:03:03 -0400955 FolderInfo folderInfo = null;
956 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700957 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
958 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400959 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700960 }
961
Joe Onorato9c1289c2009-08-17 11:03:03 -0400962 folderInfo.title = c.getString(titleIndex);
963 folderInfo.id = id;
964 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700965 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700966 folderInfo.cellX = c.getInt(cellXIndex);
967 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968
969 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700970 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 } finally {
972 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700973 }
974
975 return null;
976 }
977
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978 /**
979 * Add an item to the database in a specified container. Sets the container, screen, cellX and
980 * cellY fields of the item. Also assigns an ID to the item.
981 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700982 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 item.cellX = cellX;
986 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700987 // We store hotseat items in canonical form which is this orientation invariant position
988 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700989 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700990 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700991 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700992 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700994 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995
996 final ContentValues values = new ContentValues();
997 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +0100998 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999
Michael Jurka414300a2013-08-27 15:42:35 +02001000 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001003
Jason Monk8e19cf22014-03-20 15:06:57 -04001004 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001005 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 public void run() {
1007 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1008 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001010 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001011 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001012 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001013 sBgItemsIdMap.put(item.id, item);
1014 switch (item.itemType) {
1015 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1016 sBgFolders.put(item.id, (FolderInfo) item);
1017 // Fall through
1018 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1019 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1020 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1021 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1022 sBgWorkspaceItems.add(item);
1023 } else {
1024 if (!sBgFolders.containsKey(item.container)) {
1025 // Adding an item to a folder that doesn't exist.
1026 String msg = "adding item: " + item + " to a folder that " +
1027 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001028 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001029 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001030 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001031 break;
1032 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1033 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1034 break;
1035 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036 }
1037 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001038 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001040 }
1041
Joe Onorato9c1289c2009-08-17 11:03:03 -04001042 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001043 * Creates a new unique child id, for a given cell span across all layouts.
1044 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001045 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001046 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001047 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001048 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001049 }
1050
Sunny Goyal34942622014-08-29 17:20:55 -07001051 private static ArrayList<ItemInfo> getItemsByPackageName(
1052 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001053 ItemInfoFilter filter = new ItemInfoFilter() {
1054 @Override
1055 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1056 return cn.getPackageName().equals(pn) && info.user.equals(user);
1057 }
1058 };
Sunny Goyal34942622014-08-29 17:20:55 -07001059 return filterItemInfos(sBgItemsIdMap.values(), filter);
1060 }
1061
1062 /**
1063 * Removes all the items from the database corresponding to the specified package.
1064 */
1065 static void deletePackageFromDatabase(Context context, final String pn,
1066 final UserHandleCompat user) {
1067 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001068 }
1069
1070 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001071 * Removes the specified item from the database
1072 * @param context
1073 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001074 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001075 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001076 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1077 items.add(item);
1078 deleteItemsFromDatabase(context, items);
1079 }
1080
1081 /**
1082 * Removes the specified items from the database
1083 * @param context
1084 * @param item
1085 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001086 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001087 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001088
Michael Jurka83df1882011-08-31 20:59:26 -07001089 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001091 for (ItemInfo item : items) {
1092 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1093 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001094
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001095 // Lock on mBgLock *after* the db operation
1096 synchronized (sBgLock) {
1097 switch (item.itemType) {
1098 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1099 sBgFolders.remove(item.id);
1100 for (ItemInfo info: sBgItemsIdMap.values()) {
1101 if (info.container == item.id) {
1102 // We are deleting a folder which still contains items that
1103 // think they are contained by that folder.
1104 String msg = "deleting a folder (" + item + ") which still " +
1105 "contains items (" + info + ")";
1106 Log.e(TAG, msg);
1107 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001108 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001109 sBgWorkspaceItems.remove(item);
1110 break;
1111 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1112 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1113 sBgWorkspaceItems.remove(item);
1114 break;
1115 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1116 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1117 break;
1118 }
1119 sBgItemsIdMap.remove(item.id);
1120 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001122 }
1123 }
Michael Jurka83df1882011-08-31 20:59:26 -07001124 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001125 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001126 }
1127
1128 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001129 * Update the order of the workspace screens in the database. The array list contains
1130 * a list of screen ids in the order that they should appear.
1131 */
Winson Chungc9168342013-06-26 14:54:55 -07001132 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001133 // Log to disk
1134 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1135 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1136
Winson Chung64359a52013-07-08 17:17:08 -07001137 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001138 final ContentResolver cr = context.getContentResolver();
1139 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1140
1141 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001142 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001143 while (iter.hasNext()) {
1144 long id = iter.next();
1145 if (id < 0) {
1146 iter.remove();
1147 }
1148 }
1149
1150 Runnable r = new Runnable() {
1151 @Override
1152 public void run() {
Yura085c8532014-02-11 15:15:29 +00001153 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001155 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001156 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001157 for (int i = 0; i < count; i++) {
1158 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001159 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1161 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001162 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 }
Yura085c8532014-02-11 15:15:29 +00001164
1165 try {
1166 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1167 } catch (Exception ex) {
1168 throw new RuntimeException(ex);
1169 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001170
Winson Chungba9c37f2013-08-30 14:11:37 -07001171 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001172 sBgWorkspaceScreens.clear();
1173 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001174 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001175 }
1176 };
1177 runOnWorkerThread(r);
1178 }
1179
1180 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001181 * Remove the contents of the specified folder from the database
1182 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001183 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001184 final ContentResolver cr = context.getContentResolver();
1185
Michael Jurkac9d95c52011-08-29 14:03:34 -07001186 Runnable r = new Runnable() {
1187 public void run() {
1188 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001189 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001190 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001191 sBgItemsIdMap.remove(info.id);
1192 sBgFolders.remove(info.id);
1193 sBgDbIconCache.remove(info);
1194 sBgWorkspaceItems.remove(info);
1195 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001196
Michael Jurkac9d95c52011-08-29 14:03:34 -07001197 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1198 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001199 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001200 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 for (ItemInfo childInfo : info.contents) {
1202 sBgItemsIdMap.remove(childInfo.id);
1203 sBgDbIconCache.remove(childInfo);
1204 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001205 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001206 }
1207 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001209 }
1210
1211 /**
1212 * Set this as the current Launcher activity object for the loader.
1213 */
1214 public void initialize(Callbacks callbacks) {
1215 synchronized (mLock) {
1216 mCallbacks = new WeakReference<Callbacks>(callbacks);
1217 }
1218 }
1219
Kenny Guyed131872014-04-30 03:02:21 +01001220 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001221 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001222 int op = PackageUpdatedTask.OP_UPDATE;
1223 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1224 user));
1225 }
1226
1227 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001228 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001229 int op = PackageUpdatedTask.OP_REMOVE;
1230 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1231 user));
1232 }
1233
1234 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001235 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001236 int op = PackageUpdatedTask.OP_ADD;
1237 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1238 user));
1239 }
1240
1241 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001242 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001243 boolean replacing) {
1244 if (!replacing) {
1245 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1246 user));
1247 if (mAppsCanBeOnRemoveableStorage) {
1248 // Only rebind if we support removable storage. It catches the
1249 // case where
1250 // apps on the external sd card need to be reloaded
1251 startLoaderFromBackground();
1252 }
1253 } else {
1254 // If we are replacing then just update the packages in the list
1255 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1256 packageNames, user));
1257 }
1258 }
1259
1260 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001261 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001262 boolean replacing) {
1263 if (!replacing) {
1264 enqueuePackageUpdated(new PackageUpdatedTask(
1265 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1266 user));
1267 }
1268
1269 }
1270
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001271 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001272 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1273 * ACTION_PACKAGE_CHANGED.
1274 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001275 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001276 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001277 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001278
Joe Onorato36115782010-06-17 13:28:48 -04001279 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001280 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001281 // If we have changed locale we need to clear out the labels in all apps/workspace.
1282 forceReload();
1283 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1284 // Check if configuration change was an mcc/mnc change which would affect app resources
1285 // and we would need to clear out the labels in all apps/workspace. Same handling as
1286 // above for ACTION_LOCALE_CHANGED
1287 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001288 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001289 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001290 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001291 forceReload();
1292 }
1293 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001294 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001295 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1296 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001297 Callbacks callbacks = getCallback();
1298 if (callbacks != null) {
1299 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001300 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001301 }
1302 }
1303
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001304 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001305 resetLoadedState(true, true);
1306
Reena Lee93f824a2011-09-23 17:20:28 -07001307 // Do this here because if the launcher activity is running it will be restarted.
1308 // If it's not running startLoaderFromBackground will merely tell it that it needs
1309 // to reload.
1310 startLoaderFromBackground();
1311 }
1312
Winson Chungf0c6ae02012-03-21 16:10:31 -07001313 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1314 synchronized (mLock) {
1315 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1316 // mWorkspaceLoaded to true later
1317 stopLoaderLocked();
1318 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1319 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1320 }
1321 }
1322
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001323 /**
1324 * When the launcher is in the background, it's possible for it to miss paired
1325 * configuration changes. So whenever we trigger the loader from the background
1326 * tell the launcher that it needs to re-run the loader when it comes back instead
1327 * of doing it now.
1328 */
1329 public void startLoaderFromBackground() {
1330 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001331 Callbacks callbacks = getCallback();
1332 if (callbacks != null) {
1333 // Only actually run the loader if they're not paused.
1334 if (!callbacks.setLoadOnResume()) {
1335 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001336 }
1337 }
1338 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001339 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001340 }
Joe Onorato36115782010-06-17 13:28:48 -04001341 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001342
Reena Lee93f824a2011-09-23 17:20:28 -07001343 // If there is already a loader task running, tell it to stop.
1344 // returns true if isLaunching() was true on the old task
1345 private boolean stopLoaderLocked() {
1346 boolean isLaunching = false;
1347 LoaderTask oldTask = mLoaderTask;
1348 if (oldTask != null) {
1349 if (oldTask.isLaunching()) {
1350 isLaunching = true;
1351 }
1352 oldTask.stopLocked();
1353 }
1354 return isLaunching;
1355 }
1356
Adam Cohen1a85c582014-09-30 09:48:49 -07001357 public boolean isCurrentCallbacks(Callbacks callbacks) {
1358 return (mCallbacks != null && mCallbacks.get() == callbacks);
1359 }
1360
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001361 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001362 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1363 }
1364
1365 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001366 synchronized (mLock) {
1367 if (DEBUG_LOADERS) {
1368 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1369 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001370
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001371 // Clear any deferred bind-runnables from the synchronized load process
1372 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001373 synchronized (mDeferredBindRunnables) {
1374 mDeferredBindRunnables.clear();
1375 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001376
Joe Onorato36115782010-06-17 13:28:48 -04001377 // Don't bother to start the thread if we know it's not going to do anything
1378 if (mCallbacks != null && mCallbacks.get() != null) {
1379 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001380 // also, don't downgrade isLaunching if we're already running
1381 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001382 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001383 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1384 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001385 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1386 } else {
1387 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1388 sWorker.post(mLoaderTask);
1389 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001390 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001391 }
1392 }
1393
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001394 void bindRemainingSynchronousPages() {
1395 // Post the remaining side pages to be loaded
1396 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001397 Runnable[] deferredBindRunnables = null;
1398 synchronized (mDeferredBindRunnables) {
1399 deferredBindRunnables = mDeferredBindRunnables.toArray(
1400 new Runnable[mDeferredBindRunnables.size()]);
1401 mDeferredBindRunnables.clear();
1402 }
1403 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001404 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001405 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001406 }
1407 }
1408
Joe Onorato36115782010-06-17 13:28:48 -04001409 public void stopLoader() {
1410 synchronized (mLock) {
1411 if (mLoaderTask != null) {
1412 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001413 }
1414 }
Joe Onorato36115782010-06-17 13:28:48 -04001415 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001416
Winson Chung76828c82013-08-19 15:43:29 -07001417 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1418 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1419 final ContentResolver contentResolver = context.getContentResolver();
1420 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1421 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1422 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1423
1424 try {
1425 final int idIndex = sc.getColumnIndexOrThrow(
1426 LauncherSettings.WorkspaceScreens._ID);
1427 final int rankIndex = sc.getColumnIndexOrThrow(
1428 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1429 while (sc.moveToNext()) {
1430 try {
1431 long screenId = sc.getLong(idIndex);
1432 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001433 orderedScreens.put(rank, screenId);
1434 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001435 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001436 }
1437 }
1438 } finally {
1439 sc.close();
1440 }
Winson Chunga90303b2013-11-15 13:05:06 -08001441
1442 // Log to disk
1443 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1444 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1445 for (Integer i : orderedScreens.keySet()) {
1446 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1447 }
1448 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1449 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001450 return orderedScreens;
1451 }
1452
Michael Jurkac57b7a82011-08-09 22:02:20 -07001453 public boolean isAllAppsLoaded() {
1454 return mAllAppsLoaded;
1455 }
1456
Winson Chung36a62fe2012-05-06 18:04:42 -07001457 boolean isLoadingWorkspace() {
1458 synchronized (mLock) {
1459 if (mLoaderTask != null) {
1460 return mLoaderTask.isLoadingWorkspace();
1461 }
1462 }
1463 return false;
1464 }
1465
Joe Onorato36115782010-06-17 13:28:48 -04001466 /**
1467 * Runnable for the thread that loads the contents of the launcher:
1468 * - workspace icons
1469 * - widgets
1470 * - all apps icons
1471 */
1472 private class LoaderTask implements Runnable {
1473 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001474 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001475 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001476 private boolean mStopped;
1477 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001479
Winson Chungc3eecff2011-07-11 17:44:15 -07001480 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001481
Dan Sandlerd5024042014-01-09 15:01:33 -05001482 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001483 mContext = context;
1484 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001485 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001486 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001487 }
1488
Joe Onorato36115782010-06-17 13:28:48 -04001489 boolean isLaunching() {
1490 return mIsLaunching;
1491 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001492
Winson Chung36a62fe2012-05-06 18:04:42 -07001493 boolean isLoadingWorkspace() {
1494 return mIsLoadingAndBindingWorkspace;
1495 }
1496
Winson Chungc763c4e2013-07-19 13:49:06 -07001497 /** Returns whether this is an upgrade path */
1498 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001499 mIsLoadingAndBindingWorkspace = true;
1500
Joe Onorato36115782010-06-17 13:28:48 -04001501 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001502 if (DEBUG_LOADERS) {
1503 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001504 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001505
Winson Chungc763c4e2013-07-19 13:49:06 -07001506 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001507 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001508 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001509 synchronized (LoaderTask.this) {
1510 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001511 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001512 }
1513 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001514 }
1515 }
1516
Joe Onorato36115782010-06-17 13:28:48 -04001517 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001518 bindWorkspace(-1, isUpgradePath);
1519 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001520 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001521
Joe Onorato36115782010-06-17 13:28:48 -04001522 private void waitForIdle() {
1523 // Wait until the either we're stopped or the other threads are done.
1524 // This way we don't start loading all apps until the workspace has settled
1525 // down.
1526 synchronized (LoaderTask.this) {
1527 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001528
Joe Onorato36115782010-06-17 13:28:48 -04001529 mHandler.postIdle(new Runnable() {
1530 public void run() {
1531 synchronized (LoaderTask.this) {
1532 mLoadAndBindStepFinished = true;
1533 if (DEBUG_LOADERS) {
1534 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001535 }
Joe Onorato36115782010-06-17 13:28:48 -04001536 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001537 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001538 }
Joe Onorato36115782010-06-17 13:28:48 -04001539 });
1540
Michael Jurkac7700af2013-05-14 20:17:58 +02001541 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001542 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001543 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1544 // wait no longer than 1sec at a time
1545 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001546 } catch (InterruptedException ex) {
1547 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001548 }
1549 }
Joe Onorato36115782010-06-17 13:28:48 -04001550 if (DEBUG_LOADERS) {
1551 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001552 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001553 + "ms for previous step to finish binding");
1554 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001555 }
Joe Onorato36115782010-06-17 13:28:48 -04001556 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001557
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001558 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001559 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001560 // Ensure that we have a valid page index to load synchronously
1561 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1562 "valid page index");
1563 }
1564 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1565 // Ensure that we don't try and bind a specified page when the pages have not been
1566 // loaded already (we should load everything asynchronously in that case)
1567 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1568 }
1569 synchronized (mLock) {
1570 if (mIsLoaderTaskRunning) {
1571 // Ensure that we are never running the background loading at this point since
1572 // we also touch the background collections
1573 throw new RuntimeException("Error! Background loading is already running");
1574 }
1575 }
1576
1577 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1578 // data structures, we can't allow any other thread to touch that data, but because
1579 // this call is synchronous, we can get away with not locking).
1580
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001581 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001582 // operations from the previous activity. We need to ensure that all queued operations
1583 // are executed before any synchronous binding work is done.
1584 mHandler.flush();
1585
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 // Divide the set of loaded items into those that we are binding synchronously, and
1587 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001588 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1590 // arise from that.
1591 onlyBindAllApps();
1592 }
1593
Joe Onorato36115782010-06-17 13:28:48 -04001594 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001595 boolean isUpgrade = false;
1596
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001597 synchronized (mLock) {
1598 mIsLoaderTaskRunning = true;
1599 }
Joe Onorato36115782010-06-17 13:28:48 -04001600 // Optimize for end-user experience: if the Launcher is up and // running with the
1601 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1602 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001603 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001604 // Elevate priority when Home launches for the first time to avoid
1605 // starving at boot time. Staring at a blank home is not cool.
1606 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001607 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1608 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001609 android.os.Process.setThreadPriority(mIsLaunching
1610 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1611 }
Winson Chung64359a52013-07-08 17:17:08 -07001612 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001613 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001614
Joe Onorato36115782010-06-17 13:28:48 -04001615 if (mStopped) {
1616 break keep_running;
1617 }
1618
1619 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1620 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001621 synchronized (mLock) {
1622 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001623 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001624 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1625 }
1626 }
Joe Onorato36115782010-06-17 13:28:48 -04001627 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001628
1629 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001630 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1631 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001632
1633 // Restore the default thread priority after we are done loading items
1634 synchronized (mLock) {
1635 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1636 }
Joe Onorato36115782010-06-17 13:28:48 -04001637 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001638
Winson Chungaac01e12011-08-17 10:37:13 -07001639 // Update the saved icons if necessary
1640 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001641 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001642 for (Object key : sBgDbIconCache.keySet()) {
1643 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1644 }
1645 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001646 }
Winson Chungaac01e12011-08-17 10:37:13 -07001647
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001648 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001649 // Ensure that all the applications that are in the system are
1650 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001651 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001652 verifyApplications();
1653 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001654 }
1655
Joe Onorato36115782010-06-17 13:28:48 -04001656 // Clear out this reference, otherwise we end up holding it until all of the
1657 // callback runnables are done.
1658 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001659
Joe Onorato36115782010-06-17 13:28:48 -04001660 synchronized (mLock) {
1661 // If we are still the last one to be scheduled, remove ourselves.
1662 if (mLoaderTask == this) {
1663 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001664 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001665 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001666 }
Joe Onorato36115782010-06-17 13:28:48 -04001667 }
1668
1669 public void stopLocked() {
1670 synchronized (LoaderTask.this) {
1671 mStopped = true;
1672 this.notify();
1673 }
1674 }
1675
1676 /**
1677 * Gets the callbacks object. If we've been stopped, or if the launcher object
1678 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1679 * object that was around when the deferred message was scheduled, and if there's
1680 * a new Callbacks object around then also return null. This will save us from
1681 * calling onto it with data that will be ignored.
1682 */
1683 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1684 synchronized (mLock) {
1685 if (mStopped) {
1686 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001687 }
Joe Onorato36115782010-06-17 13:28:48 -04001688
1689 if (mCallbacks == null) {
1690 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001691 }
Joe Onorato36115782010-06-17 13:28:48 -04001692
1693 final Callbacks callbacks = mCallbacks.get();
1694 if (callbacks != oldCallbacks) {
1695 return null;
1696 }
1697 if (callbacks == null) {
1698 Log.w(TAG, "no mCallbacks");
1699 return null;
1700 }
1701
1702 return callbacks;
1703 }
1704 }
1705
Winson Chungc763c4e2013-07-19 13:49:06 -07001706 private void verifyApplications() {
1707 final Context context = mApp.getContext();
1708
1709 // Cross reference all the applications in our apps list with items in the workspace
1710 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001711 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001712 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001713 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001714 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001715 if (tmpInfos.isEmpty()) {
1716 // We are missing an application icon, so add this to the workspace
1717 added.add(app);
1718 // This is a rare event, so lets log it
1719 Log.e(TAG, "Missing Application on load: " + app);
1720 }
1721 }
1722 }
1723 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001724 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001725 }
1726 }
1727
Joe Onorato36115782010-06-17 13:28:48 -04001728 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001729 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001730 LauncherAppState app = LauncherAppState.getInstance();
1731 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001732 final int countX = (int) grid.numColumns;
1733 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001734
Adam Cohendcd297f2013-06-18 13:13:40 -07001735 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001736 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001737 // Return early if we detect that an item is under the hotseat button
1738 if (mCallbacks == null ||
1739 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001740 Log.e(TAG, "Error loading shortcut into hotseat " + item
1741 + " into position (" + item.screenId + ":" + item.cellX + ","
1742 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001743 return false;
1744 }
1745
Dan Sandler295ae182013-12-10 16:05:47 -05001746 final ItemInfo[][] hotseatItems =
1747 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1748
Adam Cohenae4409d2013-11-26 10:34:59 -08001749 if (item.screenId >= grid.numHotseatIcons) {
1750 Log.e(TAG, "Error loading shortcut " + item
1751 + " into hotseat position " + item.screenId
1752 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1753 + ")");
1754 return false;
1755 }
1756
Dan Sandler295ae182013-12-10 16:05:47 -05001757 if (hotseatItems != null) {
1758 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001759 Log.e(TAG, "Error loading shortcut into hotseat " + item
1760 + " into position (" + item.screenId + ":" + item.cellX + ","
1761 + item.cellY + ") occupied by "
1762 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1763 [(int) item.screenId][0]);
1764 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001765 } else {
1766 hotseatItems[(int) item.screenId][0] = item;
1767 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001768 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001769 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001770 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001771 items[(int) item.screenId][0] = item;
1772 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001773 return true;
1774 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001775 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1776 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001777 return true;
1778 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001779
Adam Cohendcd297f2013-06-18 13:13:40 -07001780 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001781 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001782 occupied.put(item.screenId, items);
1783 }
1784
Dan Sandler295ae182013-12-10 16:05:47 -05001785 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001786 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1787 item.cellX < 0 || item.cellY < 0 ||
1788 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1789 Log.e(TAG, "Error loading shortcut " + item
1790 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1791 + item.cellX + "," + item.cellY
1792 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1793 return false;
1794 }
1795
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001796 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001797 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1798 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001799 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001800 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001801 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001802 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001803 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001804 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001805 return false;
1806 }
1807 }
1808 }
1809 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1810 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001811 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001812 }
1813 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001814
Joe Onorato36115782010-06-17 13:28:48 -04001815 return true;
1816 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001817
Winson Chungba9c37f2013-08-30 14:11:37 -07001818 /** Clears all the sBg data structures */
1819 private void clearSBgDataStructures() {
1820 synchronized (sBgLock) {
1821 sBgWorkspaceItems.clear();
1822 sBgAppWidgets.clear();
1823 sBgFolders.clear();
1824 sBgItemsIdMap.clear();
1825 sBgDbIconCache.clear();
1826 sBgWorkspaceScreens.clear();
1827 }
1828 }
1829
Dan Sandlerd5024042014-01-09 15:01:33 -05001830 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001831 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001832 // Log to disk
1833 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1834
Joe Onorato36115782010-06-17 13:28:48 -04001835 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001836
Joe Onorato36115782010-06-17 13:28:48 -04001837 final Context context = mContext;
1838 final ContentResolver contentResolver = context.getContentResolver();
1839 final PackageManager manager = context.getPackageManager();
1840 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1841 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001842 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1843 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001844 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001845
Winson Chung892c74d2013-08-22 16:15:50 -07001846 LauncherAppState app = LauncherAppState.getInstance();
1847 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1848 int countX = (int) grid.numColumns;
1849 int countY = (int) grid.numRows;
1850
Dan Sandlerd5024042014-01-09 15:01:33 -05001851 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1852 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1853 LauncherAppState.getLauncherProvider().deleteDatabase();
1854 }
1855
1856 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1857 // append the user's Launcher2 shortcuts
1858 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1859 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1860 } else {
1861 // Make sure the default workspace is loaded
1862 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001863 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001864 }
Adam Cohene25af792013-06-06 23:08:25 -07001865
Adam Cohen71483f42014-05-15 14:04:01 -07001866 // This code path is for our old migration code and should no longer be exercised
1867 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001868
Winson Chung9f9f00b2013-11-15 13:27:00 -08001869 // Log to disk
1870 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001871
Winson Chung2abf94d2012-07-18 18:16:38 -07001872 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001873 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001874 final HashSet<String> installingPkgs = PackageInstallerCompat
1875 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001876
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001877 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001878 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001879 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001880 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001881 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001882
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 // +1 for the hotseat (it can be larger than the workspace)
1884 // Load workspace in reverse order to ensure that latest items are loaded first (and
1885 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001886 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001887
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001888 try {
1889 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1890 final int intentIndex = c.getColumnIndexOrThrow
1891 (LauncherSettings.Favorites.INTENT);
1892 final int titleIndex = c.getColumnIndexOrThrow
1893 (LauncherSettings.Favorites.TITLE);
1894 final int iconTypeIndex = c.getColumnIndexOrThrow(
1895 LauncherSettings.Favorites.ICON_TYPE);
1896 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1897 final int iconPackageIndex = c.getColumnIndexOrThrow(
1898 LauncherSettings.Favorites.ICON_PACKAGE);
1899 final int iconResourceIndex = c.getColumnIndexOrThrow(
1900 LauncherSettings.Favorites.ICON_RESOURCE);
1901 final int containerIndex = c.getColumnIndexOrThrow(
1902 LauncherSettings.Favorites.CONTAINER);
1903 final int itemTypeIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.ITEM_TYPE);
1905 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001907 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1908 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001909 final int screenIndex = c.getColumnIndexOrThrow(
1910 LauncherSettings.Favorites.SCREEN);
1911 final int cellXIndex = c.getColumnIndexOrThrow
1912 (LauncherSettings.Favorites.CELLX);
1913 final int cellYIndex = c.getColumnIndexOrThrow
1914 (LauncherSettings.Favorites.CELLY);
1915 final int spanXIndex = c.getColumnIndexOrThrow
1916 (LauncherSettings.Favorites.SPANX);
1917 final int spanYIndex = c.getColumnIndexOrThrow(
1918 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001919 final int restoredIndex = c.getColumnIndexOrThrow(
1920 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001921 final int profileIdIndex = c.getColumnIndexOrThrow(
1922 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001923 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1924 //final int displayModeIndex = c.getColumnIndexOrThrow(
1925 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001926
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001927 ShortcutInfo info;
1928 String intentDescription;
1929 LauncherAppWidgetInfo appWidgetInfo;
1930 int container;
1931 long id;
1932 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001933 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001934
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001935 while (!mStopped && c.moveToNext()) {
1936 try {
1937 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001938 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001939 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001940
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 switch (itemType) {
1942 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1943 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001944 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001945 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001946 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001947 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001948 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001949 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001950 if (user == null) {
1951 // User has been deleted remove the item.
1952 itemsToRemove.add(id);
1953 continue;
1954 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001955 try {
1956 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001957 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001958 if (cn != null && cn.getPackageName() != null) {
1959 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1960 cn.getPackageName(), user);
1961 boolean validComponent = validPkg &&
1962 launcherApps.isActivityEnabledForProfile(cn, user);
1963
1964 if (validComponent) {
1965 if (restored) {
1966 // no special handling necessary for this item
1967 restoredRows.add(id);
1968 restored = false;
1969 }
1970 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001971 intent = null;
1972 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1973 // We allow auto install apps to have their intent
1974 // updated after an install.
1975 intent = manager.getLaunchIntentForPackage(
1976 cn.getPackageName());
1977 if (intent != null) {
1978 ContentValues values = new ContentValues();
1979 values.put(LauncherSettings.Favorites.INTENT,
1980 intent.toUri(0));
1981 String where = BaseColumns._ID + "= ?";
1982 String[] args = {Long.toString(id)};
1983 contentResolver.update(contentUri, values, where, args);
1984 }
1985 }
1986
1987 if (intent == null) {
1988 // The app is installed but the component is no
1989 // longer available.
1990 Launcher.addDumpLog(TAG,
1991 "Invalid component removed: " + cn, true);
1992 itemsToRemove.add(id);
1993 continue;
1994 } else {
1995 // no special handling necessary for this item
1996 restoredRows.add(id);
1997 restored = false;
1998 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001999 } else if (restored) {
2000 // Package is not yet available but might be
2001 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002002 Launcher.addDumpLog(TAG,
2003 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002004
2005 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2006 // Restore has started once.
2007 } else if (installingPkgs.contains(cn.getPackageName())) {
2008 // App restore has started. Update the flag
2009 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2010 ContentValues values = new ContentValues();
2011 values.put(LauncherSettings.Favorites.RESTORED,
2012 promiseType);
2013 String where = BaseColumns._ID + "= ?";
2014 String[] args = {Long.toString(id)};
2015 contentResolver.update(contentUri, values, where, args);
2016
2017 } else if (REMOVE_UNRESTORED_ICONS) {
2018 Launcher.addDumpLog(TAG,
2019 "Unrestored package removed: " + cn, true);
2020 itemsToRemove.add(id);
2021 continue;
2022 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002023 } else if (launcherApps.isAppEnabled(
2024 manager, cn.getPackageName(),
2025 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2026 // Package is present but not available.
2027 allowMissingTarget = true;
2028 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2029 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002030 // SdCard is not ready yet. Package might get available,
2031 // once it is ready.
2032 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2033 + " (check again later)", true);
2034 HashSet<String> pkgs = sPendingPackages.get(user);
2035 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002036 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002037 sPendingPackages.put(user, pkgs);
2038 }
2039 pkgs.add(cn.getPackageName());
2040 allowMissingTarget = true;
2041 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002042
2043 } else {
2044 // Do not wait for external media load anymore.
2045 // Log the invalid package, and remove it
2046 Launcher.addDumpLog(TAG,
2047 "Invalid package removed: " + cn, true);
2048 itemsToRemove.add(id);
2049 continue;
Winson Chungee055712013-07-30 14:46:24 -07002050 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002051 } else if (cn == null) {
2052 // For shortcuts with no component, keep them as they are
2053 restoredRows.add(id);
2054 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002055 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002056 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002057 Launcher.addDumpLog(TAG,
2058 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002059 continue;
2060 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002061
Chris Wrenf4d08112014-01-16 18:13:56 -05002062 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002063 if (user.equals(UserHandleCompat.myUserHandle())) {
2064 Launcher.addDumpLog(TAG,
2065 "constructing info for partially restored package",
2066 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002067 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002068 intent = getRestoredItemIntent(c, context, intent);
2069 } else {
2070 // Don't restore items for other profiles.
2071 itemsToRemove.add(id);
2072 continue;
2073 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002074 } else if (itemType ==
2075 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002076 info = getShortcutInfo(manager, intent, user, context, c,
2077 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002078 } else {
2079 info = getShortcutInfo(c, context, iconTypeIndex,
2080 iconPackageIndex, iconResourceIndex, iconIndex,
2081 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002082
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 // App shortcuts that used to be automatically added to Launcher
2084 // didn't always have the correct intent flags set, so do that
2085 // here
2086 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002087 intent.getCategories() != null &&
2088 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002089 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002090 intent.addFlags(
2091 Intent.FLAG_ACTIVITY_NEW_TASK |
2092 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2093 }
Michael Jurka96879562012-03-22 05:54:33 -07002094 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002095
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002096 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002097 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 container = c.getInt(containerIndex);
2100 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002101 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002102 info.cellX = c.getInt(cellXIndex);
2103 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002104 info.spanX = 1;
2105 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002106 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002107 info.isDisabled = disabledState;
2108 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2109 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2110 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002111
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002113 if (!checkItemPlacement(occupied, info)) {
2114 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002115 break;
2116 }
2117
2118 switch (container) {
2119 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2120 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2121 sBgWorkspaceItems.add(info);
2122 break;
2123 default:
2124 // Item is in a user folder
2125 FolderInfo folderInfo =
2126 findOrMakeFolder(sBgFolders, container);
2127 folderInfo.add(info);
2128 break;
2129 }
2130 sBgItemsIdMap.put(info.id, info);
2131
2132 // now that we've loaded everthing re-save it with the
2133 // icon in case it disappears somehow.
2134 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002135 } else {
2136 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 }
2138 break;
2139
2140 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2141 id = c.getLong(idIndex);
2142 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2143
2144 folderInfo.title = c.getString(titleIndex);
2145 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002146 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002148 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 folderInfo.cellX = c.getInt(cellXIndex);
2150 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002151 folderInfo.spanX = 1;
2152 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002153
Daniel Sandler8802e962010-05-26 16:28:16 -04002154 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002155 if (!checkItemPlacement(occupied, folderInfo)) {
2156 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002157 break;
2158 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002159
Joe Onorato9c1289c2009-08-17 11:03:03 -04002160 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002161 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2162 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2163 sBgWorkspaceItems.add(folderInfo);
2164 break;
Joe Onorato36115782010-06-17 13:28:48 -04002165 }
Joe Onorato17a89222011-02-08 17:26:11 -08002166
Chris Wrenf4d08112014-01-16 18:13:56 -05002167 if (restored) {
2168 // no special handling required for restored folders
2169 restoredRows.add(id);
2170 }
2171
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002172 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2173 sBgFolders.put(folderInfo.id, folderInfo);
2174 break;
2175
2176 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2177 // Read all Launcher-specific widget details
2178 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002179 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002180 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002181 final ComponentName component =
2182 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002183
Sunny Goyal651077b2014-06-30 14:15:31 -07002184 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002185 final boolean isIdValid = (restoreStatus &
2186 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002187
Sunny Goyalff572272014-07-23 13:58:07 -07002188 final boolean wasProviderReady = (restoreStatus &
2189 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002190
Sunny Goyalff572272014-07-23 13:58:07 -07002191 final AppWidgetProviderInfo provider = isIdValid
2192 ? widgets.getAppWidgetInfo(appWidgetId)
2193 : findAppWidgetProviderInfoWithComponent(context, component);
2194
2195 final boolean isProviderReady = isValidProvider(provider);
2196 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002197 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002198 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002199 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002200 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002201 itemsToRemove.add(id);
2202 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002203 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002204 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2205 provider.provider);
2206 int[] minSpan =
2207 Launcher.getMinSpanForWidget(context, provider);
2208 appWidgetInfo.minSpanX = minSpan[0];
2209 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002210
2211 int status = restoreStatus;
2212 if (!wasProviderReady) {
2213 // If provider was not previously ready, update the
2214 // status and UI flag.
2215
2216 // Id would be valid only if the widget restore broadcast was received.
2217 if (isIdValid) {
2218 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2219 } else {
2220 status &= ~LauncherAppWidgetInfo
2221 .FLAG_PROVIDER_NOT_READY;
2222 }
2223 }
2224 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002225 } else {
2226 Log.v(TAG, "Widget restore pending id=" + id
2227 + " appWidgetId=" + appWidgetId
2228 + " status =" + restoreStatus);
2229 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002230 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002231 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002232
2233 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2234 // Restore has started once.
2235 } else if (installingPkgs.contains(component.getPackageName())) {
2236 // App restore has started. Update the flag
2237 appWidgetInfo.restoreStatus |=
2238 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002239 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002240 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002241 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002242 itemsToRemove.add(id);
2243 continue;
2244 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002245 }
Sunny Goyalff572272014-07-23 13:58:07 -07002246
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002248 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002249 appWidgetInfo.cellX = c.getInt(cellXIndex);
2250 appWidgetInfo.cellY = c.getInt(cellYIndex);
2251 appWidgetInfo.spanX = c.getInt(spanXIndex);
2252 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002253
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002254 container = c.getInt(containerIndex);
2255 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2256 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2257 Log.e(TAG, "Widget found where container != " +
2258 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2259 continue;
2260 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002261
Adam Cohene25af792013-06-06 23:08:25 -07002262 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002264 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2265 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002266 break;
2267 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002268
Sunny Goyal94485362014-09-18 16:13:58 -07002269 String providerName = appWidgetInfo.providerName.flattenToString();
2270 if (!providerName.equals(savedProvider) ||
2271 (appWidgetInfo.restoreStatus != restoreStatus)) {
2272 ContentValues values = new ContentValues();
2273 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2274 providerName);
2275 values.put(LauncherSettings.Favorites.RESTORED,
2276 appWidgetInfo.restoreStatus);
2277 String where = BaseColumns._ID + "= ?";
2278 String[] args = {Long.toString(id)};
2279 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002280 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2282 sBgAppWidgets.add(appWidgetInfo);
2283 }
Joe Onorato36115782010-06-17 13:28:48 -04002284 break;
2285 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002286 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002287 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002288 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 }
2290 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002291 if (c != null) {
2292 c.close();
2293 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002294 }
2295
Winson Chungba9c37f2013-08-30 14:11:37 -07002296 // Break early if we've stopped loading
2297 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002298 clearSBgDataStructures();
2299 return false;
2300 }
2301
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002302 if (itemsToRemove.size() > 0) {
2303 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002304 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002305 // Remove dead items
2306 for (long id : itemsToRemove) {
2307 if (DEBUG_LOADERS) {
2308 Log.d(TAG, "Removed id = " + id);
2309 }
2310 // Don't notify content observers
2311 try {
2312 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2313 null, null);
2314 } catch (RemoteException e) {
2315 Log.w(TAG, "Could not remove id = " + id);
2316 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002317 }
2318 }
2319
Chris Wrenf4d08112014-01-16 18:13:56 -05002320 if (restoredRows.size() > 0) {
2321 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002322 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002323 // Update restored items that no longer require special handling
2324 try {
2325 StringBuilder selectionBuilder = new StringBuilder();
2326 selectionBuilder.append(LauncherSettings.Favorites._ID);
2327 selectionBuilder.append(" IN (");
2328 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2329 selectionBuilder.append(")");
2330 ContentValues values = new ContentValues();
2331 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002332 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002333 values, selectionBuilder.toString(), null);
2334 } catch (RemoteException e) {
2335 Log.w(TAG, "Could not update restored rows");
2336 }
2337 }
2338
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002339 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2340 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002341 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002342 null, sWorker);
2343 }
2344
Winson Chungc763c4e2013-07-19 13:49:06 -07002345 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002346 long maxScreenId = 0;
2347 // If we're importing we use the old screen order.
2348 for (ItemInfo item: sBgItemsIdMap.values()) {
2349 long screenId = item.screenId;
2350 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2351 !sBgWorkspaceScreens.contains(screenId)) {
2352 sBgWorkspaceScreens.add(screenId);
2353 if (screenId > maxScreenId) {
2354 maxScreenId = screenId;
2355 }
2356 }
2357 }
2358 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002359 // Log to disk
2360 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2361 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2362 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002363
Michael Jurka414300a2013-08-27 15:42:35 +02002364 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002365 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002366
2367 // Update the max item id after we load an old db
2368 long maxItemId = 0;
2369 // If we're importing we use the old screen order.
2370 for (ItemInfo item: sBgItemsIdMap.values()) {
2371 maxItemId = Math.max(maxItemId, item.id);
2372 }
Michael Jurka414300a2013-08-27 15:42:35 +02002373 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002374 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002375 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2376 for (Integer i : orderedScreens.keySet()) {
2377 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002378 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002379 // Log to disk
2380 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2381 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002382
2383 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002384 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002385 for (ItemInfo item: sBgItemsIdMap.values()) {
2386 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002387 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2388 unusedScreens.contains(screenId)) {
2389 unusedScreens.remove(screenId);
2390 }
2391 }
2392
2393 // If there are any empty screens remove them, and update.
2394 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002395 // Log to disk
2396 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2397 TextUtils.join(", ", unusedScreens), true);
2398
Winson Chung933bae62013-08-29 11:42:30 -07002399 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002400 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2401 }
2402 }
2403
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002404 if (DEBUG_LOADERS) {
2405 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2406 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002407 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002408 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002409 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002410
Daniel Sandler566da102013-06-25 23:43:45 -04002411 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002412 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002413 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002414 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002415 line += " | ";
2416 }
Winson Chung892c74d2013-08-22 16:15:50 -07002417 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002418 ItemInfo[][] screen = occupied.get(screenId);
2419 if (x < screen.length && y < screen[x].length) {
2420 line += (screen[x][y] != null) ? "#" : ".";
2421 } else {
2422 line += "!";
2423 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002424 }
Joe Onorato36115782010-06-17 13:28:48 -04002425 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002426 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002427 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002428 }
Joe Onorato36115782010-06-17 13:28:48 -04002429 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002430 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002431 }
2432
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002433 /** Filters the set of items who are directly or indirectly (via another container) on the
2434 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002435 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002436 ArrayList<ItemInfo> allWorkspaceItems,
2437 ArrayList<ItemInfo> currentScreenItems,
2438 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002439 // Purge any null ItemInfos
2440 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2441 while (iter.hasNext()) {
2442 ItemInfo i = iter.next();
2443 if (i == null) {
2444 iter.remove();
2445 }
2446 }
2447
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002448 // Order the set of items by their containers first, this allows use to walk through the
2449 // list sequentially, build up a list of containers that are in the specified screen,
2450 // as well as all items in those containers.
2451 Set<Long> itemsOnScreen = new HashSet<Long>();
2452 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2453 @Override
2454 public int compare(ItemInfo lhs, ItemInfo rhs) {
2455 return (int) (lhs.container - rhs.container);
2456 }
2457 });
2458 for (ItemInfo info : allWorkspaceItems) {
2459 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002460 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461 currentScreenItems.add(info);
2462 itemsOnScreen.add(info.id);
2463 } else {
2464 otherScreenItems.add(info);
2465 }
2466 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2467 currentScreenItems.add(info);
2468 itemsOnScreen.add(info.id);
2469 } else {
2470 if (itemsOnScreen.contains(info.container)) {
2471 currentScreenItems.add(info);
2472 itemsOnScreen.add(info.id);
2473 } else {
2474 otherScreenItems.add(info);
2475 }
2476 }
2477 }
2478 }
2479
2480 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002481 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002482 ArrayList<LauncherAppWidgetInfo> appWidgets,
2483 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2484 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002485
2486 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002487 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002488 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002489 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002490 currentScreenWidgets.add(widget);
2491 } else {
2492 otherScreenWidgets.add(widget);
2493 }
2494 }
2495 }
2496
2497 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002498 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002499 HashMap<Long, ItemInfo> itemsIdMap,
2500 HashMap<Long, FolderInfo> folders,
2501 HashMap<Long, FolderInfo> currentScreenFolders,
2502 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002503
2504 for (long id : folders.keySet()) {
2505 ItemInfo info = itemsIdMap.get(id);
2506 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002507 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002509 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002510 currentScreenFolders.put(id, folder);
2511 } else {
2512 otherScreenFolders.put(id, folder);
2513 }
2514 }
2515 }
2516
2517 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2518 * right) */
2519 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002520 final LauncherAppState app = LauncherAppState.getInstance();
2521 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 // XXX: review this
2523 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002524 @Override
2525 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002526 int cellCountX = (int) grid.numColumns;
2527 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002528 int screenOffset = cellCountX * cellCountY;
2529 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002530 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002531 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002532 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002533 rhs.cellY * cellCountX + rhs.cellX);
2534 return (int) (lr - rr);
2535 }
2536 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002537 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002538
Adam Cohendcd297f2013-06-18 13:13:40 -07002539 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2540 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002541 final Runnable r = new Runnable() {
2542 @Override
2543 public void run() {
2544 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2545 if (callbacks != null) {
2546 callbacks.bindScreens(orderedScreens);
2547 }
2548 }
2549 };
2550 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2551 }
2552
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2554 final ArrayList<ItemInfo> workspaceItems,
2555 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2556 final HashMap<Long, FolderInfo> folders,
2557 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002558
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002559 final boolean postOnMainThread = (deferredBindRunnables != null);
2560
2561 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002562 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002563 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002564 final int start = i;
2565 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002566 final Runnable r = new Runnable() {
2567 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002568 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002569 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002570 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002571 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2572 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002573 }
2574 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002575 };
2576 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002577 synchronized (deferredBindRunnables) {
2578 deferredBindRunnables.add(r);
2579 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002580 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002581 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002582 }
Joe Onorato36115782010-06-17 13:28:48 -04002583 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584
2585 // Bind the folders
2586 if (!folders.isEmpty()) {
2587 final Runnable r = new Runnable() {
2588 public void run() {
2589 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2590 if (callbacks != null) {
2591 callbacks.bindFolders(folders);
2592 }
2593 }
2594 };
2595 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002596 synchronized (deferredBindRunnables) {
2597 deferredBindRunnables.add(r);
2598 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002599 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002600 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 }
2602 }
2603
2604 // Bind the widgets, one at a time
2605 N = appWidgets.size();
2606 for (int i = 0; i < N; i++) {
2607 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2608 final Runnable r = new Runnable() {
2609 public void run() {
2610 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2611 if (callbacks != null) {
2612 callbacks.bindAppWidget(widget);
2613 }
2614 }
2615 };
2616 if (postOnMainThread) {
2617 deferredBindRunnables.add(r);
2618 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002619 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002620 }
2621 }
2622 }
2623
2624 /**
2625 * Binds all loaded data to actual views on the main thread.
2626 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002627 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002628 final long t = SystemClock.uptimeMillis();
2629 Runnable r;
2630
2631 // Don't use these two variables in any of the callback runnables.
2632 // Otherwise we hold a reference to them.
2633 final Callbacks oldCallbacks = mCallbacks.get();
2634 if (oldCallbacks == null) {
2635 // This launcher has exited and nobody bothered to tell us. Just bail.
2636 Log.w(TAG, "LoaderTask running with no launcher");
2637 return;
2638 }
2639
Winson Chung9b9fb962013-11-15 15:39:34 -08002640 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002641 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2642 ArrayList<LauncherAppWidgetInfo> appWidgets =
2643 new ArrayList<LauncherAppWidgetInfo>();
2644 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2645 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002646 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002647 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002648 workspaceItems.addAll(sBgWorkspaceItems);
2649 appWidgets.addAll(sBgAppWidgets);
2650 folders.putAll(sBgFolders);
2651 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002652 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 }
2654
Derek Prothro7aff3992013-12-10 14:00:37 -05002655 final boolean isLoadingSynchronously =
2656 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002657 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002658 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002659 if (currScreen >= orderedScreenIds.size()) {
2660 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002661 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002662 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002663 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002664 final long currentScreenId = currentScreen < 0
2665 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002666
2667 // Load all the items that are on the current page first (and in the process, unbind
2668 // all the existing workspace items before we call startBinding() below.
2669 unbindWorkspaceItemsOnMainThread();
2670
2671 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2673 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2674 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2675 new ArrayList<LauncherAppWidgetInfo>();
2676 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2677 new ArrayList<LauncherAppWidgetInfo>();
2678 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2679 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2680
Winson Chung9b9fb962013-11-15 15:39:34 -08002681 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002682 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002683 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002685 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002686 otherFolders);
2687 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2688 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2689
2690 // Tell the workspace that we're about to start binding items
2691 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002692 public void run() {
2693 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2694 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002695 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002696 }
2697 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002698 };
Winson Chung81b52252012-08-27 15:34:29 -07002699 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002700
Adam Cohendcd297f2013-06-18 13:13:40 -07002701 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2702
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002703 // Load items on the current page
2704 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2705 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002706 if (isLoadingSynchronously) {
2707 r = new Runnable() {
2708 public void run() {
2709 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002710 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002711 callbacks.onPageBoundSynchronously(currentScreen);
2712 }
2713 }
2714 };
Winson Chung81b52252012-08-27 15:34:29 -07002715 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002716 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002717
Winson Chung4a2afa32012-07-19 14:53:05 -07002718 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2719 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002720 synchronized (mDeferredBindRunnables) {
2721 mDeferredBindRunnables.clear();
2722 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002723 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002724 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002725
2726 // Tell the workspace that we're done binding items
2727 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002728 public void run() {
2729 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2730 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002731 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002732 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002733
Winson Chung98e030b2012-05-07 16:01:11 -07002734 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002735 if (DEBUG_LOADERS) {
2736 Log.d(TAG, "bound workspace in "
2737 + (SystemClock.uptimeMillis()-t) + "ms");
2738 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002739
2740 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002741 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002742 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002743 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002744 synchronized (mDeferredBindRunnables) {
2745 mDeferredBindRunnables.add(r);
2746 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002747 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002748 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002749 }
Joe Onorato36115782010-06-17 13:28:48 -04002750 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002751
Joe Onorato36115782010-06-17 13:28:48 -04002752 private void loadAndBindAllApps() {
2753 if (DEBUG_LOADERS) {
2754 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2755 }
2756 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002757 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002758 synchronized (LoaderTask.this) {
2759 if (mStopped) {
2760 return;
2761 }
2762 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002763 }
Joe Onorato36115782010-06-17 13:28:48 -04002764 } else {
2765 onlyBindAllApps();
2766 }
2767 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002768
Joe Onorato36115782010-06-17 13:28:48 -04002769 private void onlyBindAllApps() {
2770 final Callbacks oldCallbacks = mCallbacks.get();
2771 if (oldCallbacks == null) {
2772 // This launcher has exited and nobody bothered to tell us. Just bail.
2773 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2774 return;
2775 }
2776
2777 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002778 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002779 final ArrayList<AppInfo> list
2780 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002781 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002782 public void run() {
2783 final long t = SystemClock.uptimeMillis();
2784 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2785 if (callbacks != null) {
2786 callbacks.bindAllApplications(list);
2787 }
2788 if (DEBUG_LOADERS) {
2789 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2790 + (SystemClock.uptimeMillis()-t) + "ms");
2791 }
2792 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002793 };
2794 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002795 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002796 r.run();
2797 } else {
2798 mHandler.post(r);
2799 }
Joe Onorato36115782010-06-17 13:28:48 -04002800 }
2801
Winson Chung64359a52013-07-08 17:17:08 -07002802 private void loadAllApps() {
2803 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002804
Joe Onorato36115782010-06-17 13:28:48 -04002805 final Callbacks oldCallbacks = mCallbacks.get();
2806 if (oldCallbacks == null) {
2807 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002808 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002809 return;
2810 }
2811
2812 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2813 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2814
Kenny Guyed131872014-04-30 03:02:21 +01002815 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2816
Winson Chung64359a52013-07-08 17:17:08 -07002817 // Clear the list of apps
2818 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002819 SharedPreferences prefs = mContext.getSharedPreferences(
2820 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002821 for (UserHandleCompat user : profiles) {
2822 // Query for the set of apps
2823 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2824 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2825 if (DEBUG_LOADERS) {
2826 Log.d(TAG, "getActivityList took "
2827 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2828 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2829 }
2830 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002831 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002832 if (apps == null || apps.isEmpty()) {
2833 return;
2834 }
2835 // Sort the applications by name
2836 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2837 Collections.sort(apps,
2838 new LauncherModel.ShortcutNameComparator(mLabelCache));
2839 if (DEBUG_LOADERS) {
2840 Log.d(TAG, "sort took "
2841 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2842 }
Joe Onorato36115782010-06-17 13:28:48 -04002843
Kenny Guyed131872014-04-30 03:02:21 +01002844 // Create the ApplicationInfos
2845 for (int i = 0; i < apps.size(); i++) {
2846 LauncherActivityInfoCompat app = apps.get(i);
2847 // This builds the icon bitmaps.
2848 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2849 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002850
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002851 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002852 // Add shortcuts for packages which were installed while launcher was dead.
2853 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2854 + mUserManager.getSerialNumberForUser(user);
2855 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2856 HashSet<String> newPackageSet = new HashSet<String>();
2857
2858 for (LauncherActivityInfoCompat info : apps) {
2859 String packageName = info.getComponentName().getPackageName();
2860 if (!packagesAdded.contains(packageName)
2861 && !newPackageSet.contains(packageName)) {
2862 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2863 }
2864 newPackageSet.add(packageName);
2865 }
2866
2867 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2868 }
Winson Chung64359a52013-07-08 17:17:08 -07002869 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002870 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002871 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2872 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002873
2874 // Post callback on main thread
2875 mHandler.post(new Runnable() {
2876 public void run() {
2877 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002878 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002879 if (callbacks != null) {
2880 callbacks.bindAllApplications(added);
2881 if (DEBUG_LOADERS) {
2882 Log.d(TAG, "bound " + added.size() + " apps in "
2883 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2884 }
2885 } else {
2886 Log.i(TAG, "not binding apps: no Launcher activity");
2887 }
2888 }
2889 });
2890
Joe Onorato36115782010-06-17 13:28:48 -04002891 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002892 Log.d(TAG, "Icons processed in "
2893 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002894 }
2895 }
2896
2897 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002898 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002899 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2900 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2901 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2902 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2903 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2904 }
Joe Onorato36115782010-06-17 13:28:48 -04002905 }
2906 }
2907
2908 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002909 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002910 }
2911
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002912 private class AppsAvailabilityCheck extends BroadcastReceiver {
2913
2914 @Override
2915 public void onReceive(Context context, Intent intent) {
2916 synchronized (sBgLock) {
2917 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2918 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002919 final PackageManager manager = context.getPackageManager();
2920 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2921 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002922 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2923 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002924 packagesRemoved.clear();
2925 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002926 for (String pkg : entry.getValue()) {
2927 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002928 boolean packageOnSdcard = launcherApps.isAppEnabled(
2929 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2930 if (packageOnSdcard) {
2931 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2932 packagesUnavailable.add(pkg);
2933 } else {
2934 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2935 packagesRemoved.add(pkg);
2936 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002937 }
2938 }
2939 if (!packagesRemoved.isEmpty()) {
2940 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2941 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2942 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002943 if (!packagesUnavailable.isEmpty()) {
2944 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2945 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2946 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002947 }
Sunny Goyal34942622014-08-29 17:20:55 -07002948 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002949 }
2950 }
2951 }
2952
Joe Onorato36115782010-06-17 13:28:48 -04002953 private class PackageUpdatedTask implements Runnable {
2954 int mOp;
2955 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002956 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002957
2958 public static final int OP_NONE = 0;
2959 public static final int OP_ADD = 1;
2960 public static final int OP_UPDATE = 2;
2961 public static final int OP_REMOVE = 3; // uninstlled
2962 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2963
2964
Kenny Guyed131872014-04-30 03:02:21 +01002965 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002966 mOp = op;
2967 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002968 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002969 }
2970
2971 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002972 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002973
2974 final String[] packages = mPackages;
2975 final int N = packages.length;
2976 switch (mOp) {
2977 case OP_ADD:
2978 for (int i=0; i<N; i++) {
2979 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002980 mIconCache.remove(packages[i], mUser);
2981 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002982 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002983
2984 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002985 if (ADD_MANAGED_PROFILE_SHORTCUTS
2986 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002987 SharedPreferences prefs = context.getSharedPreferences(
2988 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2989 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2990 + mUserManager.getSerialNumberForUser(mUser);
2991 Set<String> shortcutSet = new HashSet<String>(
2992 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2993
2994 for (int i=0; i<N; i++) {
2995 if (!shortcutSet.contains(packages[i])) {
2996 shortcutSet.add(packages[i]);
2997 List<LauncherActivityInfoCompat> activities =
2998 mLauncherApps.getActivityList(packages[i], mUser);
2999 if (activities != null && !activities.isEmpty()) {
3000 InstallShortcutReceiver.queueInstallShortcut(
3001 activities.get(0), context);
3002 }
3003 }
3004 }
3005
3006 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3007 }
Joe Onorato36115782010-06-17 13:28:48 -04003008 break;
3009 case OP_UPDATE:
3010 for (int i=0; i<N; i++) {
3011 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003012 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003013 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003014 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003015 }
3016 break;
3017 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003018 // Remove the packageName for the set of auto-installed shortcuts. This
3019 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003020 if (ADD_MANAGED_PROFILE_SHORTCUTS
3021 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003022 SharedPreferences prefs = context.getSharedPreferences(
3023 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3024 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3025 + mUserManager.getSerialNumberForUser(mUser);
3026 HashSet<String> shortcutSet = new HashSet<String>(
3027 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3028 shortcutSet.removeAll(Arrays.asList(mPackages));
3029 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3030 }
3031 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003032 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003033 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003034 for (int i=0; i<N; i++) {
3035 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003036 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003037 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003038 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003039 }
3040 break;
3041 }
3042
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003043 ArrayList<AppInfo> added = null;
3044 ArrayList<AppInfo> modified = null;
3045 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003046
Adam Cohen487f7dd2012-06-28 18:12:10 -07003047 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003048 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003049 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003050 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003051 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003052 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003053 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003054 }
Winson Chung5d55f332012-07-16 20:45:03 -07003055 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003056 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003057 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003058 }
3059
Sunny Goyale0f58d72014-11-10 18:05:31 -08003060 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003061 if (callbacks == null) {
3062 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3063 return;
3064 }
3065
Sunny Goyal4390ace2014-10-13 11:33:11 -07003066 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3067 new HashMap<ComponentName, AppInfo>();
3068
Joe Onorato36115782010-06-17 13:28:48 -04003069 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003070 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003071 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003072 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003073 addAndBindAddedWorkspaceApps(context, addedInfos);
3074 } else {
3075 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003076 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003077 for (AppInfo ai : added) {
3078 addedOrUpdatedApps.put(ai.componentName, ai);
3079 }
Joe Onorato36115782010-06-17 13:28:48 -04003080 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003081
Joe Onorato36115782010-06-17 13:28:48 -04003082 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003083 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003084 for (AppInfo ai : modified) {
3085 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003086 }
3087
Joe Onorato36115782010-06-17 13:28:48 -04003088 mHandler.post(new Runnable() {
3089 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003090 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003091 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003092 callbacks.bindAppsUpdated(modifiedFinal);
3093 }
3094 }
3095 });
3096 }
Winson Chung83892cc2013-05-01 16:53:33 -07003097
Sunny Goyal4390ace2014-10-13 11:33:11 -07003098 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003099 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003100 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3101 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3102 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3103
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003104 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003105 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003106 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003107 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3108 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003109 boolean infoUpdated = false;
3110 boolean shortcutUpdated = false;
3111
3112 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003113 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003114 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003115 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3116 si.iconResource.resourceName, mIconCache, context);
3117 if (icon != null) {
3118 si.setIcon(icon);
3119 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003120 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003121 }
3122 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003123
3124 ComponentName cn = si.getTargetComponent();
3125 if (cn != null && packageSet.contains(cn.getPackageName())) {
3126 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3127
3128 if (si.isPromise()) {
3129 mIconCache.deletePreloadedIcon(cn, mUser);
3130 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3131 // Auto install icon
3132 PackageManager pm = context.getPackageManager();
3133 ResolveInfo matched = pm.resolveActivity(
3134 new Intent(Intent.ACTION_MAIN)
3135 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3136 PackageManager.MATCH_DEFAULT_ONLY);
3137 if (matched == null) {
3138 // Try to find the best match activity.
3139 Intent intent = pm.getLaunchIntentForPackage(
3140 cn.getPackageName());
3141 if (intent != null) {
3142 cn = intent.getComponent();
3143 appInfo = addedOrUpdatedApps.get(cn);
3144 }
3145
3146 if ((intent == null) || (appInfo == null)) {
3147 removedShortcuts.add(si);
3148 continue;
3149 }
3150 si.promisedIntent = intent;
3151 }
3152 }
3153
3154 // Restore the shortcut.
3155 si.intent = si.promisedIntent;
3156 si.promisedIntent = null;
3157 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3158 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3159 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3160
3161 infoUpdated = true;
3162 si.updateIcon(mIconCache);
3163 }
3164
3165 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3166 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3167 si.updateIcon(mIconCache);
3168 si.title = appInfo.title.toString();
3169 si.contentDescription = appInfo.contentDescription;
3170 infoUpdated = true;
3171 }
3172
3173 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3174 // Since package was just updated, the target must be available now.
3175 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3176 shortcutUpdated = true;
3177 }
3178 }
3179
3180 if (infoUpdated || shortcutUpdated) {
3181 updatedShortcuts.add(si);
3182 }
3183 if (infoUpdated) {
3184 updateItemInDatabase(context, si);
3185 }
3186 } else if (info instanceof LauncherAppWidgetInfo) {
3187 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3188 if (mUser.equals(widgetInfo.user)
3189 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3190 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3191 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3192 widgets.add(widgetInfo);
3193 updateItemInDatabase(context, widgetInfo);
3194 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003195 }
3196 }
3197 }
3198
Sunny Goyal4390ace2014-10-13 11:33:11 -07003199 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3200 mHandler.post(new Runnable() {
3201
3202 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003203 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003204 if (callbacks == cb && cb != null) {
3205 callbacks.bindShortcutsChanged(
3206 updatedShortcuts, removedShortcuts, mUser);
3207 }
3208 }
3209 });
3210 if (!removedShortcuts.isEmpty()) {
3211 deleteItemsFromDatabase(context, removedShortcuts);
3212 }
3213 }
3214 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003215 mHandler.post(new Runnable() {
3216 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003217 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003218 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003219 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003220 }
3221 }
3222 });
3223 }
3224 }
3225
Winson Chungdf95eb12013-10-16 14:57:07 -07003226 final ArrayList<String> removedPackageNames =
3227 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003228 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003229 // Mark all packages in the broadcast to be removed
3230 removedPackageNames.addAll(Arrays.asList(packages));
3231 } else if (mOp == OP_UPDATE) {
3232 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003233 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003234 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003235 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003236 }
3237 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003238 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003239
Winson Chungdf95eb12013-10-16 14:57:07 -07003240 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003241 final int removeReason;
3242 if (mOp == OP_UNAVAILABLE) {
3243 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3244 } else {
3245 // Remove all the components associated with this package
3246 for (String pn : removedPackageNames) {
3247 deletePackageFromDatabase(context, pn, mUser);
3248 }
3249 // Remove all the specific components
3250 for (AppInfo a : removedApps) {
3251 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3252 deleteItemsFromDatabase(context, infos);
3253 }
3254 removeReason = 0;
3255 }
3256
Winson Chungdf95eb12013-10-16 14:57:07 -07003257 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003258 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003259 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003260 mHandler.post(new Runnable() {
3261 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003262 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003263 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003264 callbacks.bindComponentsRemoved(
3265 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003266 }
3267 }
3268 });
Joe Onoratobe386092009-11-17 17:32:16 -08003269 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003270
Michael Jurkac402cd92013-05-20 15:49:32 +02003271 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003272 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003273 mHandler.post(new Runnable() {
3274 @Override
3275 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003276 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003277 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003278 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003279 }
3280 }
3281 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003282
3283 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003284 mHandler.post(new Runnable() {
3285 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003286 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003287 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003288 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003289 }
3290 }
3291 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003292 }
3293 }
3294
Michael Jurkac402cd92013-05-20 15:49:32 +02003295 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3296 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3297 PackageManager packageManager = context.getPackageManager();
3298 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003299 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3300
Michael Jurkac402cd92013-05-20 15:49:32 +02003301 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3302 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003303 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003304 return widgetsAndShortcuts;
3305 }
3306
Kenny Guyed131872014-04-30 03:02:21 +01003307 private static boolean isPackageDisabled(Context context, String packageName,
3308 UserHandleCompat user) {
3309 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3310 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003311 }
Adam Cohen556f6132014-01-15 15:18:08 -08003312
Kenny Guyed131872014-04-30 03:02:21 +01003313 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3314 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003315 if (cn == null) {
3316 return false;
3317 }
Kenny Guyed131872014-04-30 03:02:21 +01003318 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3319 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003320 return false;
3321 }
Kenny Guyed131872014-04-30 03:02:21 +01003322 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003323 }
3324
Adam Cohena28b78e2014-05-20 17:03:04 -07003325 public static boolean isValidPackage(Context context, String packageName,
3326 UserHandleCompat user) {
3327 if (packageName == null) {
3328 return false;
3329 }
3330 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3331 return launcherApps.isPackageEnabledForProfile(packageName, user);
3332 }
3333
Joe Onorato9c1289c2009-08-17 11:03:03 -04003334 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003335 * Make an ShortcutInfo object for a restored application or shortcut item that points
3336 * to a package that is not yet installed on the system.
3337 */
Sunny Goyal34942622014-08-29 17:20:55 -07003338 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3339 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003340 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003341 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003342 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3343
3344 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3345 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3346 if (!TextUtils.isEmpty(title)) {
3347 info.title = title;
3348 }
3349 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3350 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3351 if (TextUtils.isEmpty(info.title)) {
3352 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3353 }
3354 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3355 } else {
3356 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3357 }
3358
Kenny Guyc2bd8102014-06-30 12:30:31 +01003359 info.contentDescription = mUserManager.getBadgedLabelForUser(
3360 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003361 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003362 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003363 return info;
3364 }
3365
3366 /**
3367 * Make an Intent object for a restored application or shortcut item that points
3368 * to the market page for the item.
3369 */
3370 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3371 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003372 return getMarketIntent(componentName.getPackageName());
3373 }
3374
3375 static Intent getMarketIntent(String packageName) {
3376 return new Intent(Intent.ACTION_VIEW)
3377 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003378 .scheme("market")
3379 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003380 .appendQueryParameter("id", packageName)
3381 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003382 }
3383
3384 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003385 * This is called from the code that adds shortcuts from the intent receiver. This
3386 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003387 */
Kenny Guyed131872014-04-30 03:02:21 +01003388 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3389 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003390 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003391 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003392
Joe Onorato56d82912010-03-07 14:32:10 -05003393 /**
3394 * Make an ShortcutInfo object for a shortcut that is an application.
3395 *
3396 * If c is not null, then it will be used to fill in missing data like the title and icon.
3397 */
Kenny Guyed131872014-04-30 03:02:21 +01003398 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3399 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003400 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003401 if (user == null) {
3402 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003403 return null;
3404 }
3405
Kenny Guyed131872014-04-30 03:02:21 +01003406 ComponentName componentName = intent.getComponent();
3407 if (componentName == null) {
3408 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3409 return null;
3410 }
3411
3412 Intent newIntent = new Intent(intent.getAction(), null);
3413 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3414 newIntent.setComponent(componentName);
3415 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003416 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003417 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3418 return null;
3419 }
3420
3421 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003422
Joe Onorato56d82912010-03-07 14:32:10 -05003423 // the resource -- This may implicitly give us back the fallback icon,
3424 // but don't worry about that. All we're doing with usingFallbackIcon is
3425 // to avoid saving lots of copies of that in the database, and most apps
3426 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003427 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003428
Joe Onorato56d82912010-03-07 14:32:10 -05003429 // the db
3430 if (icon == null) {
3431 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003432 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003433 }
3434 }
3435 // the fallback icon
3436 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003437 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003438 info.usingFallbackIcon = true;
3439 }
3440 info.setIcon(icon);
3441
Kenny Guyed131872014-04-30 03:02:21 +01003442 // From the cache.
3443 if (labelCache != null) {
3444 info.title = labelCache.get(componentName);
3445 }
3446
Joe Onorato56d82912010-03-07 14:32:10 -05003447 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003448 if (info.title == null && lai != null) {
3449 info.title = lai.getLabel();
3450 if (labelCache != null) {
3451 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003452 }
Joe Onorato56d82912010-03-07 14:32:10 -05003453 }
3454 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003455 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003456 if (c != null) {
3457 info.title = c.getString(titleIndex);
3458 }
3459 }
3460 // fall back to the class name of the activity
3461 if (info.title == null) {
3462 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003463 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003464 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003465 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003466 info.contentDescription = mUserManager.getBadgedLabelForUser(
3467 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003468 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003469 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003470
Winson Chung64359a52013-07-08 17:17:08 -07003471 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3472 ItemInfoFilter f) {
3473 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3474 for (ItemInfo i : infos) {
3475 if (i instanceof ShortcutInfo) {
3476 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003477 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003478 if (cn != null && f.filterItem(null, info, cn)) {
3479 filtered.add(info);
3480 }
3481 } else if (i instanceof FolderInfo) {
3482 FolderInfo info = (FolderInfo) i;
3483 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003484 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003485 if (cn != null && f.filterItem(info, s, cn)) {
3486 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003487 }
3488 }
Winson Chung64359a52013-07-08 17:17:08 -07003489 } else if (i instanceof LauncherAppWidgetInfo) {
3490 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3491 ComponentName cn = info.providerName;
3492 if (cn != null && f.filterItem(null, info, cn)) {
3493 filtered.add(info);
3494 }
Winson Chung8a435102012-08-30 17:16:53 -07003495 }
3496 }
Winson Chung64359a52013-07-08 17:17:08 -07003497 return new ArrayList<ItemInfo>(filtered);
3498 }
3499
Kenny Guyed131872014-04-30 03:02:21 +01003500 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3501 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003502 ItemInfoFilter filter = new ItemInfoFilter() {
3503 @Override
3504 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003505 if (info.user == null) {
3506 return cn.equals(cname);
3507 } else {
3508 return cn.equals(cname) && info.user.equals(user);
3509 }
Winson Chung64359a52013-07-08 17:17:08 -07003510 }
3511 };
3512 return filterItemInfos(sBgItemsIdMap.values(), filter);
3513 }
3514
Sunny Goyal1a745e82014-10-02 15:58:31 -07003515 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003516 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003517 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003518 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003519 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3520 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003521
Joe Onorato56d82912010-03-07 14:32:10 -05003522 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003523 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003524 // Non-app shortcuts are only supported for current user.
3525 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003526 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003527
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003528 // TODO: If there's an explicit component and we can't install that, delete it.
3529
Joe Onorato56d82912010-03-07 14:32:10 -05003530 info.title = c.getString(titleIndex);
3531
Joe Onorato9c1289c2009-08-17 11:03:03 -04003532 int iconType = c.getInt(iconTypeIndex);
3533 switch (iconType) {
3534 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3535 String packageName = c.getString(iconPackageIndex);
3536 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003537 info.customIcon = false;
3538 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003539 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003540 // the db
3541 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003542 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003543 }
3544 // the fallback icon
3545 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003546 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003547 info.usingFallbackIcon = true;
3548 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003549 break;
3550 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003551 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003552 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003553 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003554 info.customIcon = false;
3555 info.usingFallbackIcon = true;
3556 } else {
3557 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003558 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003559 break;
3560 default:
Kenny Guyed131872014-04-30 03:02:21 +01003561 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003562 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003563 info.customIcon = false;
3564 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003565 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003566 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003567 return info;
3568 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003569
Michael Jurka931dc972011-08-05 15:08:15 -07003570 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003571 @SuppressWarnings("all") // suppress dead code warning
3572 final boolean debug = false;
3573 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003574 Log.d(TAG, "getIconFromCursor app="
3575 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3576 }
3577 byte[] data = c.getBlob(iconIndex);
3578 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003579 return Utilities.createIconBitmap(
3580 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003581 } catch (Exception e) {
3582 return null;
3583 }
3584 }
3585
Winson Chunga9abd0e2010-10-27 17:18:37 -07003586 /**
Winson Chung55cef262010-10-28 14:14:18 -07003587 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3588 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003589 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003590 ComponentName component) {
3591 List<AppWidgetProviderInfo> widgets =
3592 AppWidgetManager.getInstance(context).getInstalledProviders();
3593 for (AppWidgetProviderInfo info : widgets) {
3594 if (info.provider.equals(component)) {
3595 return info;
3596 }
3597 }
3598 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003599 }
3600
Sunny Goyal2350bc92014-10-14 16:42:54 -07003601 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003602 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3603 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3604 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3605
Adam Cohend9198822011-11-22 16:42:47 -08003606 if (intent == null) {
3607 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3608 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3609 return null;
3610 }
3611
Joe Onorato0589f0f2010-02-08 13:44:00 -08003612 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003613 boolean customIcon = false;
3614 ShortcutIconResource iconResource = null;
3615
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003616 if (bitmap instanceof Bitmap) {
3617 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003618 customIcon = true;
3619 } else {
3620 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003621 if (extra instanceof ShortcutIconResource) {
3622 iconResource = (ShortcutIconResource) extra;
3623 icon = Utilities.createIconBitmap(iconResource.packageName,
3624 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003625 }
3626 }
3627
Michael Jurkac9d95c52011-08-29 14:03:34 -07003628 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003629
Kenny Guyed131872014-04-30 03:02:21 +01003630 // Only support intents for current user for now. Intents sent from other
3631 // users wouldn't get here without intent forwarding anyway.
3632 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003633 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003634 icon = mIconCache.getDefaultIcon(info.user);
3635 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003636 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003637 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003638
Joe Onorato0589f0f2010-02-08 13:44:00 -08003639 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003640 info.contentDescription = mUserManager.getBadgedLabelForUser(
3641 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003642 info.intent = intent;
3643 info.customIcon = customIcon;
3644 info.iconResource = iconResource;
3645
3646 return info;
3647 }
3648
Winson Chungaac01e12011-08-17 10:37:13 -07003649 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3650 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003651 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003652 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003653 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003654 }
Joe Onorato56d82912010-03-07 14:32:10 -05003655 // If this icon doesn't have a custom icon, check to see
3656 // what's stored in the DB, and if it doesn't match what
3657 // we're going to show, store what we are going to show back
3658 // into the DB. We do this so when we're loading, if the
3659 // package manager can't find an icon (for example because
3660 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003661 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003662 cache.put(info, c.getBlob(iconIndex));
3663 return true;
3664 }
3665 return false;
3666 }
3667 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3668 boolean needSave = false;
3669 try {
3670 if (data != null) {
3671 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3672 Bitmap loaded = info.getIcon(mIconCache);
3673 needSave = !saved.sameAs(loaded);
3674 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003675 needSave = true;
3676 }
Winson Chungaac01e12011-08-17 10:37:13 -07003677 } catch (Exception e) {
3678 needSave = true;
3679 }
3680 if (needSave) {
3681 Log.d(TAG, "going to save icon bitmap for info=" + info);
3682 // This is slower than is ideal, but this only happens once
3683 // or when the app is updated with a new icon.
3684 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003685 }
3686 }
3687
Joe Onorato9c1289c2009-08-17 11:03:03 -04003688 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003689 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003690 * or make a new one.
3691 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003692 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003693 // See if a placeholder was created for us already
3694 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003695 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003696 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003697 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003698 folders.put(id, folderInfo);
3699 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003700 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003701 }
3702
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003703 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003704 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003705 return new Comparator<AppInfo>() {
3706 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003707 if (a.user.equals(b.user)) {
3708 int result = collator.compare(a.title.toString().trim(),
3709 b.title.toString().trim());
3710 if (result == 0) {
3711 result = a.componentName.compareTo(b.componentName);
3712 }
3713 return result;
3714 } else {
3715 // TODO Need to figure out rules for sorting
3716 // profiles, this puts work second.
3717 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003718 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003719 }
Winson Chung11904872012-09-17 16:58:46 -07003720 };
3721 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003722 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3723 = new Comparator<AppInfo>() {
3724 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003725 if (a.firstInstallTime < b.firstInstallTime) return 1;
3726 if (a.firstInstallTime > b.firstInstallTime) return -1;
3727 return 0;
3728 }
3729 };
Winson Chung5308f242011-08-18 12:12:41 -07003730 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3731 if (info.activityInfo != null) {
3732 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3733 } else {
3734 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3735 }
3736 }
Kenny Guyed131872014-04-30 03:02:21 +01003737 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003738 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003739 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003740 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003741 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003742 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003743 }
Kenny Guyed131872014-04-30 03:02:21 +01003744 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003745 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003746 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003747 }
Kenny Guyed131872014-04-30 03:02:21 +01003748 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003749 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003750 ComponentName keyA = a.getComponentName();
3751 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003752 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003753 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003754 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003755 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003756
Winson Chung5308f242011-08-18 12:12:41 -07003757 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003758 }
Winson Chung5308f242011-08-18 12:12:41 -07003759 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003760 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003761 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003762 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003763
Winson Chung5308f242011-08-18 12:12:41 -07003764 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003765 }
Winson Chung11904872012-09-17 16:58:46 -07003766 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003767 }
3768 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003769 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003770 private final AppWidgetManagerCompat mManager;
3771 private final PackageManager mPackageManager;
3772 private final HashMap<Object, String> mLabelCache;
3773 private final Collator mCollator;
3774
3775 WidgetAndShortcutNameComparator(Context context) {
3776 mManager = AppWidgetManagerCompat.getInstance(context);
3777 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003778 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003779 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003780 }
3781 public final int compare(Object a, Object b) {
3782 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003783 if (mLabelCache.containsKey(a)) {
3784 labelA = mLabelCache.get(a);
3785 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003786 labelA = (a instanceof AppWidgetProviderInfo)
3787 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3788 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003789 mLabelCache.put(a, labelA);
3790 }
3791 if (mLabelCache.containsKey(b)) {
3792 labelB = mLabelCache.get(b);
3793 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003794 labelB = (b instanceof AppWidgetProviderInfo)
3795 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3796 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003797 mLabelCache.put(b, labelB);
3798 }
Winson Chung11904872012-09-17 16:58:46 -07003799 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003800 }
3801 };
Joe Onoratobe386092009-11-17 17:32:16 -08003802
Sunny Goyal651077b2014-06-30 14:15:31 -07003803 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3804 return (provider != null) && (provider.provider != null)
3805 && (provider.provider.getPackageName() != null);
3806 }
3807
Joe Onoratobe386092009-11-17 17:32:16 -08003808 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003809 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003810 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3811 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3812 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3813 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003814 if (mLoaderTask != null) {
3815 mLoaderTask.dumpState();
3816 } else {
3817 Log.d(TAG, "mLoaderTask=null");
3818 }
Joe Onoratobe386092009-11-17 17:32:16 -08003819 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003820
3821 public Callbacks getCallback() {
3822 return mCallbacks != null ? mCallbacks.get() : null;
3823 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003824}