blob: 11440c0fc43432aab03459f857fab90fd0e5ebab [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;
Chris Wrenb358f812014-04-16 13:37:00 -040090
Joe Onorato9c1289c2009-08-17 11:03:03 -040091 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070092
Daniel Sandler8707e0f2013-08-15 15:54:18 -070093 // true = use a "More Apps" folder for non-workspace apps on upgrade
94 // false = strew non-workspace apps across the workspace on upgrade
95 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050096 public static final int LOADER_FLAG_NONE = 0;
97 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
98 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
99
Joe Onorato36115782010-06-17 13:28:48 -0400100 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500101 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800102
Winson Chungee055712013-07-30 14:46:24 -0700103 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800104 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400105
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400106 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400107 private final Object mLock = new Object();
108 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400109 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700110 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200111 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Sunny Goyale0f58d72014-11-10 18:05:31 -0800113 /**
114 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
115 */
116 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
117
Winson Chung81b52252012-08-27 15:34:29 -0700118 // Specific runnable types that are run on the main thread deferred handler, this allows us to
119 // clear all queued binding runnables when the Launcher activity is destroyed.
120 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
121 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
122
Jason Monkbbe1e242014-05-16 17:37:34 -0400123 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700124
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700125 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
126 static {
127 sWorkerThread.start();
128 }
129 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
130
Joe Onoratocc67f472010-06-08 10:54:30 -0700131 // We start off with everything not loaded. After that, we assume that
132 // our monitoring of the package manager provides all updates and we never
133 // need to do a requery. These are only ever touched from the loader thread.
134 private boolean mWorkspaceLoaded;
135 private boolean mAllAppsLoaded;
136
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700137 // When we are loading pages synchronously, we can't just post the binding of items on the side
138 // pages as this delays the rotation process. Instead, we wait for a callback from the first
139 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
140 // a normal load, we also clear this set of Runnables.
141 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
142
Joe Onorato9c1289c2009-08-17 11:03:03 -0400143 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800144
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700146 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800147
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148 // The lock that must be acquired before referencing any static bg data structures. Unlike
149 // other locks, this one can generally be held long-term because we never expect any of these
150 // static data structures to be referenced outside of the worker thread except on the first
151 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700152 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700153
Adam Cohen487f7dd2012-06-28 18:12:10 -0700154 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700156 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
159 // created by LauncherModel that are directly on the home screen (however, no widgets or
160 // shortcuts within folders).
161 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
164 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 new ArrayList<LauncherAppWidgetInfo>();
166
Adam Cohen487f7dd2012-06-28 18:12:10 -0700167 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
168 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700169
Adam Cohen487f7dd2012-06-28 18:12:10 -0700170 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
171 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700172
173 // sBgWorkspaceScreens is the ordered set of workspace screens.
174 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
175
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700176 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700177 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
178 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700179
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700180 // </ only access in worker thread >
181
182 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183
Reena Lee99a73f32011-10-24 17:27:37 -0700184 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700185
Kenny Guyed131872014-04-30 03:02:21 +0100186 private final LauncherAppsCompat mLauncherApps;
187 private final UserManagerCompat mUserManager;
188
Joe Onorato9c1289c2009-08-17 11:03:03 -0400189 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700190 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400191 public int getCurrentWorkspaceScreen();
192 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700193 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
194 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700195 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700196 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500197 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700198 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400199 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200200 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700201 public void bindAppsAdded(ArrayList<Long> newScreens,
202 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700203 ArrayList<ItemInfo> addAnimated,
204 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200205 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700206 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
207 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
208 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700209 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700210 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700211 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700212 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200213 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100214 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700215 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700216 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700217 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400218 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800219
Winson Chung64359a52013-07-08 17:17:08 -0700220 public interface ItemInfoFilter {
221 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
222 }
223
Bjorn Bringert1307f632013-10-03 22:31:03 +0100224 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800225 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400226
Winson Chungee055712013-07-30 14:46:24 -0700227 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700228 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400229 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
230 // resource string.
231 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
232 ProviderInfo providerInfo =
233 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
234 ProviderInfo redirectProvider =
235 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700236
237 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400238 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700239
240 if (mOldContentProviderExists) {
241 Log.d(TAG, "Old launcher provider exists.");
242 } else {
243 Log.d(TAG, "Old launcher provider does not exist.");
244 }
245
Daniel Sandlere4f98912013-06-25 15:13:26 -0400246 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100247 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800248 mIconCache = iconCache;
249
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400250 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700251 Configuration config = res.getConfiguration();
252 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100253 mLauncherApps = LauncherAppsCompat.getInstance(context);
254 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800255 }
256
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700257 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
258 * posted on the main thread handler. */
259 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700260 runOnMainThread(r, 0);
261 }
262 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700263 if (sWorkerThread.getThreadId() == Process.myTid()) {
264 // If we are on the worker thread, post onto the main handler
265 mHandler.post(r);
266 } else {
267 r.run();
268 }
269 }
270
271 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
272 * posted on the worker thread handler. */
273 private static void runOnWorkerThread(Runnable r) {
274 if (sWorkerThread.getThreadId() == Process.myTid()) {
275 r.run();
276 } else {
277 // If we are not on the worker thread, then post to the worker handler
278 sWorker.post(r);
279 }
280 }
281
Winson Chunge43a1e72014-01-15 10:33:02 -0800282 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
283 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800284 }
285
Winson Chungc9168342013-06-26 14:54:55 -0700286 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
287 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700288 LauncherAppState app = LauncherAppState.getInstance();
289 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
290 final int xCount = (int) grid.numColumns;
291 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700292 boolean[][] occupied = new boolean[xCount][yCount];
293
294 int cellX, cellY, spanX, spanY;
295 for (int i = 0; i < items.size(); ++i) {
296 final ItemInfo item = items.get(i);
297 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
298 if (item.screenId == screen) {
299 cellX = item.cellX;
300 cellY = item.cellY;
301 spanX = item.spanX;
302 spanY = item.spanY;
303 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
304 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
305 occupied[x][y] = true;
306 }
307 }
308 }
309 }
310 }
311
312 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
313 }
314 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700315 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700316 int firstScreenIndex,
317 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700318 // Lock on the app so that we don't try and get the items while apps are being added
319 LauncherAppState app = LauncherAppState.getInstance();
320 LauncherModel model = app.getModel();
321 boolean found = false;
322 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700323 if (sWorkerThread.getThreadId() != Process.myTid()) {
324 // Flush the LauncherModel worker thread, so that if we just did another
325 // processInstallShortcut, we give it time for its shortcut to get added to the
326 // database (getItemsInLocalCoordinates reads the database)
327 model.flushWorkerThread();
328 }
Winson Chungc9168342013-06-26 14:54:55 -0700329 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700330
331 // Try adding to the workspace screens incrementally, starting at the default or center
332 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700333 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
334 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700335 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700336 int[] tmpCoordinates = new int[2];
337 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700338 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700339 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700340 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700341 }
342 }
343 }
Winson Chungc9168342013-06-26 14:54:55 -0700344 return null;
345 }
346
Sunny Goyale755d462014-07-22 13:48:29 -0700347 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500348 // Process the updated package state
349 Runnable r = new Runnable() {
350 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800351 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500352 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700353 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500354 }
355 }
356 };
357 mHandler.post(r);
358 }
359
Sunny Goyala22666f2014-09-18 13:25:15 -0700360 public void updatePackageBadge(final String packageName) {
361 // Process the updated package badge
362 Runnable r = new Runnable() {
363 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800364 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700365 if (callbacks != null) {
366 callbacks.updatePackageBadge(packageName);
367 }
368 }
369 };
370 mHandler.post(r);
371 }
372
Adam Cohen76a47a12014-02-05 11:47:43 -0800373 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800374 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800375
376 if (allAppsApps == null) {
377 throw new RuntimeException("allAppsApps must not be null");
378 }
379 if (allAppsApps.isEmpty()) {
380 return;
381 }
382
383 // Process the newly added applications and add them to the database first
384 Runnable r = new Runnable() {
385 public void run() {
386 runOnMainThread(new Runnable() {
387 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800388 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800389 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500390 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800391 }
392 }
393 });
394 }
395 };
396 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700397 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800398
399 public void addAndBindAddedWorkspaceApps(final Context context,
400 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800401 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800402
403 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800404 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
405 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800406 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700407 return;
Winson Chung997a9232013-07-24 15:33:46 -0700408 }
Winson Chung64359a52013-07-08 17:17:08 -0700409 // Process the newly added applications and add them to the database first
410 Runnable r = new Runnable() {
411 public void run() {
412 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
413 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
414
Winson Chung76828c82013-08-19 15:43:29 -0700415 // Get the list of workspace screens. We need to append to this list and
416 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
417 // called.
418 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
419 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
420 for (Integer i : orderedScreens.keySet()) {
421 long screenId = orderedScreens.get(i);
422 workspaceScreens.add(screenId);
423 }
424
Winson Chung64359a52013-07-08 17:17:08 -0700425 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700426 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700427 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700428 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700429 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700430 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700431
432 // Short-circuit this logic if the icon exists somewhere on the workspace
Sunny Goyale0f58d72014-11-10 18:05:31 -0800433 if (shortcutExists(context, name, launchIntent, a.user)) {
Winson Chung64359a52013-07-08 17:17:08 -0700434 continue;
435 }
436
Winson Chung87412982013-10-03 18:34:14 -0700437 // Add this icon to the db, creating a new page if necessary. If there
438 // is only the empty page then we just add items to the first page.
439 // Otherwise, we add them to the next pages.
440 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700441 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700442 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700443 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200444 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700445
446 // If we can't find a valid position, then just add a new screen.
447 // This takes time so we need to re-queue the add until the new
448 // page is added. Create as many screens as necessary to satisfy
449 // the startSearchPageIndex.
450 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700451 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700452 while (numPagesToAdd > 0) {
453 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700454 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700455 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 addedWorkspaceScreensFinal.add(screenId);
457 numPagesToAdd--;
458 }
Winson Chung76828c82013-08-19 15:43:29 -0700459
Winson Chung64359a52013-07-08 17:17:08 -0700460 // Find the coordinate again
461 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700462 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700463 }
464 if (coords == null) {
465 throw new RuntimeException("Coordinates should not be null");
466 }
467
Winson Chung997a9232013-07-24 15:33:46 -0700468 ShortcutInfo shortcutInfo;
469 if (a instanceof ShortcutInfo) {
470 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200471 } else if (a instanceof AppInfo) {
472 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700473 } else {
474 throw new RuntimeException("Unexpected info type");
475 }
Winson Chung94d67682013-09-25 16:29:40 -0700476
Winson Chung64359a52013-07-08 17:17:08 -0700477 // Add the shortcut to the db
478 addItemToDatabase(context, shortcutInfo,
479 LauncherSettings.Favorites.CONTAINER_DESKTOP,
480 coords.first, coords.second[0], coords.second[1], false);
481 // Save the ShortcutInfo for binding in the workspace
482 addedShortcutsFinal.add(shortcutInfo);
483 }
484 }
485
Winson Chung76828c82013-08-19 15:43:29 -0700486 // Update the workspace screens
487 updateWorkspaceScreenOrder(context, workspaceScreens);
488
Adam Cohen76a47a12014-02-05 11:47:43 -0800489 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700490 runOnMainThread(new Runnable() {
491 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800492 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700493 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700494 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
495 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700496 if (!addedShortcutsFinal.isEmpty()) {
497 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
498 long lastScreenId = info.screenId;
499 for (ItemInfo i : addedShortcutsFinal) {
500 if (i.screenId == lastScreenId) {
501 addAnimated.add(i);
502 } else {
503 addNotAnimated.add(i);
504 }
Winson Chung997a9232013-07-24 15:33:46 -0700505 }
506 }
Winson Chungd64d1762013-08-20 14:37:16 -0700507 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800508 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700509 }
Winson Chung64359a52013-07-08 17:17:08 -0700510 }
Winson Chung997a9232013-07-24 15:33:46 -0700511 });
512 }
Winson Chung64359a52013-07-08 17:17:08 -0700513 }
514 };
515 runOnWorkerThread(r);
516 }
517
Winson Chung81b52252012-08-27 15:34:29 -0700518 public void unbindItemInfosAndClearQueuedBindRunnables() {
519 if (sWorkerThread.getThreadId() == Process.myTid()) {
520 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
521 "main thread");
522 }
523
524 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400525 synchronized (mDeferredBindRunnables) {
526 mDeferredBindRunnables.clear();
527 }
Winson Chung81b52252012-08-27 15:34:29 -0700528 // Remove any queued bind runnables
529 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
530 // Unbind all the workspace items
531 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700532 }
533
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700534 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700535 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700536 // Ensure that we don't use the same workspace items data structure on the main thread
537 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700538 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
539 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700540 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700541 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
542 tmpAppWidgets.addAll(sBgAppWidgets);
543 }
544 Runnable r = new Runnable() {
545 @Override
546 public void run() {
547 for (ItemInfo item : tmpWorkspaceItems) {
548 item.unbind();
549 }
550 for (ItemInfo item : tmpAppWidgets) {
551 item.unbind();
552 }
553 }
554 };
555 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700556 }
557
Joe Onorato9c1289c2009-08-17 11:03:03 -0400558 /**
559 * Adds an item to the DB if it was not created previously, or move it to a new
560 * <container, screen, cellX, cellY>
561 */
562 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700563 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400564 if (item.container == ItemInfo.NO_ID) {
565 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700566 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400567 } else {
568 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700569 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800570 }
571 }
572
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700573 static void checkItemInfoLocked(
574 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
575 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
576 if (modelItem != null && item != modelItem) {
577 // check all the data is consistent
578 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
579 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
580 ShortcutInfo shortcut = (ShortcutInfo) item;
581 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
582 modelShortcut.intent.filterEquals(shortcut.intent) &&
583 modelShortcut.id == shortcut.id &&
584 modelShortcut.itemType == shortcut.itemType &&
585 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700586 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700587 modelShortcut.cellX == shortcut.cellX &&
588 modelShortcut.cellY == shortcut.cellY &&
589 modelShortcut.spanX == shortcut.spanX &&
590 modelShortcut.spanY == shortcut.spanY &&
591 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
592 (modelShortcut.dropPos != null &&
593 shortcut.dropPos != null &&
594 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
595 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
596 // For all intents and purposes, this is the same object
597 return;
598 }
599 }
600
601 // the modelItem needs to match up perfectly with item if our model is
602 // to be consistent with the database-- for now, just require
603 // modelItem == item or the equality check above
604 String msg = "item: " + ((item != null) ? item.toString() : "null") +
605 "modelItem: " +
606 ((modelItem != null) ? modelItem.toString() : "null") +
607 "Error: ItemInfo passed to checkItemInfo doesn't match original";
608 RuntimeException e = new RuntimeException(msg);
609 if (stackTrace != null) {
610 e.setStackTrace(stackTrace);
611 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800612 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700613 }
614 }
615
Michael Jurka816474f2012-06-25 14:49:02 -0700616 static void checkItemInfo(final ItemInfo item) {
617 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
618 final long itemId = item.id;
619 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700620 public void run() {
621 synchronized (sBgLock) {
622 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700623 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700624 }
625 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700626 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700627 }
628
Michael Jurkac9d95c52011-08-29 14:03:34 -0700629 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
630 final ItemInfo item, final String callingFunction) {
631 final long itemId = item.id;
632 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
633 final ContentResolver cr = context.getContentResolver();
634
Adam Cohen487f7dd2012-06-28 18:12:10 -0700635 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700636 Runnable r = new Runnable() {
637 public void run() {
638 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700639 updateItemArrays(item, itemId, stackTrace);
640 }
641 };
642 runOnWorkerThread(r);
643 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700644
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700645 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
646 final ArrayList<ItemInfo> items, final String callingFunction) {
647 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700648
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700649 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
650 Runnable r = new Runnable() {
651 public void run() {
652 ArrayList<ContentProviderOperation> ops =
653 new ArrayList<ContentProviderOperation>();
654 int count = items.size();
655 for (int i = 0; i < count; i++) {
656 ItemInfo item = items.get(i);
657 final long itemId = item.id;
658 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
659 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700660
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700661 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
662 updateItemArrays(item, itemId, stackTrace);
663
664 }
665 try {
666 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
667 } catch (Exception e) {
668 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700669 }
670 }
671 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700672 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700673 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700674
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700675 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
676 // Lock on mBgLock *after* the db operation
677 synchronized (sBgLock) {
678 checkItemInfoLocked(itemId, item, stackTrace);
679
680 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
681 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
682 // Item is in a folder, make sure this folder exists
683 if (!sBgFolders.containsKey(item.container)) {
684 // An items container is being set to a that of an item which is not in
685 // the list of Folders.
686 String msg = "item: " + item + " container being set to: " +
687 item.container + ", not in the list of folders";
688 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700689 }
690 }
691
692 // Items are added/removed from the corresponding FolderInfo elsewhere, such
693 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
694 // that are on the desktop, as appropriate
695 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800696 if (modelItem != null &&
697 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
698 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700699 switch (modelItem.itemType) {
700 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
701 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
702 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
703 if (!sBgWorkspaceItems.contains(modelItem)) {
704 sBgWorkspaceItems.add(modelItem);
705 }
706 break;
707 default:
708 break;
709 }
710 } else {
711 sBgWorkspaceItems.remove(modelItem);
712 }
713 }
714 }
715
Michael Jurkac7700af2013-05-14 20:17:58 +0200716 public void flushWorkerThread() {
717 mFlushingWorkerThread = true;
718 Runnable waiter = new Runnable() {
719 public void run() {
720 synchronized (this) {
721 notifyAll();
722 mFlushingWorkerThread = false;
723 }
724 }
725 };
726
727 synchronized(waiter) {
728 runOnWorkerThread(waiter);
729 if (mLoaderTask != null) {
730 synchronized(mLoaderTask) {
731 mLoaderTask.notify();
732 }
733 }
734 boolean success = false;
735 while (!success) {
736 try {
737 waiter.wait();
738 success = true;
739 } catch (InterruptedException e) {
740 }
741 }
742 }
743 }
744
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800745 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400746 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700747 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700748 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700749 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400750 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400751 item.cellX = cellX;
752 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700753
Winson Chung3d503fb2011-07-13 17:25:49 -0700754 // We store hotseat items in canonical form which is this orientation invariant position
755 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700756 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700757 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700758 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700759 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400762
763 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400764 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700765 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
766 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700767 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400768
Michael Jurkac9d95c52011-08-29 14:03:34 -0700769 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700770 }
771
772 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700773 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
774 * cellX, cellY have already been updated on the ItemInfos.
775 */
776 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
777 final long container, final int screen) {
778
779 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
780 int count = items.size();
781
782 for (int i = 0; i < count; i++) {
783 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700784 item.container = container;
785
786 // We store hotseat items in canonical form which is this orientation invariant position
787 // in the hotseat
788 if (context instanceof Launcher && screen < 0 &&
789 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700790 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700791 item.cellY);
792 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700793 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700794 }
795
796 final ContentValues values = new ContentValues();
797 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
798 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
799 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700800 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700801
802 contentValues.add(values);
803 }
804 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
805 }
806
807 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700808 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800809 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700810 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700811 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700812 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800813 item.cellX = cellX;
814 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700815 item.spanX = spanX;
816 item.spanY = spanY;
817
818 // We store hotseat items in canonical form which is this orientation invariant position
819 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700821 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700822 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700823 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700825 }
Adam Cohend4844c32011-02-18 19:25:06 -0800826
Adam Cohend4844c32011-02-18 19:25:06 -0800827 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800828 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
830 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
831 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
832 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700833 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800834
Michael Jurka816474f2012-06-25 14:49:02 -0700835 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700836 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700837
838 /**
839 * Update an item to the database in a specified container.
840 */
841 static void updateItemInDatabase(Context context, final ItemInfo item) {
842 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100843 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700844 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
845 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800846 }
847
848 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400849 * Returns true if the shortcuts already exists in the database.
850 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800851 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800852 static boolean shortcutExists(Context context, String title, Intent intent,
853 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400854 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700855 final Intent intentWithPkg, intentWithoutPkg;
856
857 if (intent.getComponent() != null) {
858 // If component is not null, an intent with null package will produce
859 // the same result and should also be a match.
860 if (intent.getPackage() != null) {
861 intentWithPkg = intent;
862 intentWithoutPkg = new Intent(intent).setPackage(null);
863 } else {
864 intentWithPkg = new Intent(intent).setPackage(
865 intent.getComponent().getPackageName());
866 intentWithoutPkg = intent;
867 }
868 } else {
869 intentWithPkg = intent;
870 intentWithoutPkg = intent;
871 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800872 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
873 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400874 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800875 new String[] { "title", "intent", "profileId" },
876 "title=? and (intent=? or intent=?) and profileId=?",
877 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
878 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400879 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800880 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400881 } finally {
882 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800883 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700884 }
885
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700887 * Returns an ItemInfo array containing all the items in the LauncherModel.
888 * The ItemInfo.id is not set through this function.
889 */
890 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
891 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
892 final ContentResolver cr = context.getContentResolver();
893 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
894 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100895 LauncherSettings.Favorites.SCREEN,
896 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
897 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
898 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700899
900 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
901 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
902 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
903 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
904 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
905 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
906 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100907 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
908 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700909 try {
910 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700911 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700912 item.cellX = c.getInt(cellXIndex);
913 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700914 item.spanX = Math.max(1, c.getInt(spanXIndex));
915 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 item.container = c.getInt(containerIndex);
917 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700918 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100919 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100920 item.user = userManager.getUserForSerialNumber(serialNumber);
921 // Skip if user has been deleted.
922 if (item.user != null) {
923 items.add(item);
924 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700925 }
926 } catch (Exception e) {
927 items.clear();
928 } finally {
929 c.close();
930 }
931
932 return items;
933 }
934
935 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400936 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
937 */
938 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
939 final ContentResolver cr = context.getContentResolver();
940 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
941 "_id=? and (itemType=? or itemType=?)",
942 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700943 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700944
Joe Onorato9c1289c2009-08-17 11:03:03 -0400945 try {
946 if (c.moveToFirst()) {
947 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
948 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
949 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
950 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
951 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
952 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800953
Joe Onorato9c1289c2009-08-17 11:03:03 -0400954 FolderInfo folderInfo = null;
955 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700956 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
957 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700959 }
960
Joe Onorato9c1289c2009-08-17 11:03:03 -0400961 folderInfo.title = c.getString(titleIndex);
962 folderInfo.id = id;
963 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700964 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700965 folderInfo.cellX = c.getInt(cellXIndex);
966 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967
968 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700969 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400970 } finally {
971 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700972 }
973
974 return null;
975 }
976
Joe Onorato9c1289c2009-08-17 11:03:03 -0400977 /**
978 * Add an item to the database in a specified container. Sets the container, screen, cellX and
979 * cellY fields of the item. Also assigns an ID to the item.
980 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700981 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700982 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 item.cellX = cellX;
985 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700986 // We store hotseat items in canonical form which is this orientation invariant position
987 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700989 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700990 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700991 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700992 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700993 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994
995 final ContentValues values = new ContentValues();
996 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +0100997 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998
Michael Jurka414300a2013-08-27 15:42:35 +0200999 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001000 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001002
Jason Monk8e19cf22014-03-20 15:06:57 -04001003 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001004 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001005 public void run() {
1006 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1007 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001009 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001010 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001011 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001012 sBgItemsIdMap.put(item.id, item);
1013 switch (item.itemType) {
1014 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1015 sBgFolders.put(item.id, (FolderInfo) item);
1016 // Fall through
1017 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1018 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1019 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1020 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1021 sBgWorkspaceItems.add(item);
1022 } else {
1023 if (!sBgFolders.containsKey(item.container)) {
1024 // Adding an item to a folder that doesn't exist.
1025 String msg = "adding item: " + item + " to a folder that " +
1026 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001027 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001028 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001029 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001030 break;
1031 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1032 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1033 break;
1034 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001035 }
1036 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001037 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001039 }
1040
Joe Onorato9c1289c2009-08-17 11:03:03 -04001041 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001042 * Creates a new unique child id, for a given cell span across all layouts.
1043 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001044 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001045 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001046 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001047 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001048 }
1049
Sunny Goyal34942622014-08-29 17:20:55 -07001050 private static ArrayList<ItemInfo> getItemsByPackageName(
1051 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001052 ItemInfoFilter filter = new ItemInfoFilter() {
1053 @Override
1054 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1055 return cn.getPackageName().equals(pn) && info.user.equals(user);
1056 }
1057 };
Sunny Goyal34942622014-08-29 17:20:55 -07001058 return filterItemInfos(sBgItemsIdMap.values(), filter);
1059 }
1060
1061 /**
1062 * Removes all the items from the database corresponding to the specified package.
1063 */
1064 static void deletePackageFromDatabase(Context context, final String pn,
1065 final UserHandleCompat user) {
1066 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001067 }
1068
1069 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001070 * Removes the specified item from the database
1071 * @param context
1072 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001073 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001074 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001075 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1076 items.add(item);
1077 deleteItemsFromDatabase(context, items);
1078 }
1079
1080 /**
1081 * Removes the specified items from the database
1082 * @param context
1083 * @param item
1084 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001085 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001087
Michael Jurka83df1882011-08-31 20:59:26 -07001088 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001089 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001090 for (ItemInfo item : items) {
1091 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1092 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001093
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001094 // Lock on mBgLock *after* the db operation
1095 synchronized (sBgLock) {
1096 switch (item.itemType) {
1097 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1098 sBgFolders.remove(item.id);
1099 for (ItemInfo info: sBgItemsIdMap.values()) {
1100 if (info.container == item.id) {
1101 // We are deleting a folder which still contains items that
1102 // think they are contained by that folder.
1103 String msg = "deleting a folder (" + item + ") which still " +
1104 "contains items (" + info + ")";
1105 Log.e(TAG, msg);
1106 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001107 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001108 sBgWorkspaceItems.remove(item);
1109 break;
1110 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1111 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1112 sBgWorkspaceItems.remove(item);
1113 break;
1114 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1115 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1116 break;
1117 }
1118 sBgItemsIdMap.remove(item.id);
1119 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001120 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001121 }
1122 }
Michael Jurka83df1882011-08-31 20:59:26 -07001123 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001124 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001125 }
1126
1127 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001128 * Update the order of the workspace screens in the database. The array list contains
1129 * a list of screen ids in the order that they should appear.
1130 */
Winson Chungc9168342013-06-26 14:54:55 -07001131 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001132 // Log to disk
1133 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1134 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1135
Winson Chung64359a52013-07-08 17:17:08 -07001136 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001137 final ContentResolver cr = context.getContentResolver();
1138 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1139
1140 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001141 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001142 while (iter.hasNext()) {
1143 long id = iter.next();
1144 if (id < 0) {
1145 iter.remove();
1146 }
1147 }
1148
1149 Runnable r = new Runnable() {
1150 @Override
1151 public void run() {
Yura085c8532014-02-11 15:15:29 +00001152 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001153 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001154 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001155 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001156 for (int i = 0; i < count; i++) {
1157 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001158 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001159 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1160 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001161 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001162 }
Yura085c8532014-02-11 15:15:29 +00001163
1164 try {
1165 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1166 } catch (Exception ex) {
1167 throw new RuntimeException(ex);
1168 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001169
Winson Chungba9c37f2013-08-30 14:11:37 -07001170 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001171 sBgWorkspaceScreens.clear();
1172 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001173 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001174 }
1175 };
1176 runOnWorkerThread(r);
1177 }
1178
1179 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001180 * Remove the contents of the specified folder from the database
1181 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001182 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001183 final ContentResolver cr = context.getContentResolver();
1184
Michael Jurkac9d95c52011-08-29 14:03:34 -07001185 Runnable r = new Runnable() {
1186 public void run() {
1187 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001188 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001189 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001190 sBgItemsIdMap.remove(info.id);
1191 sBgFolders.remove(info.id);
1192 sBgDbIconCache.remove(info);
1193 sBgWorkspaceItems.remove(info);
1194 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001195
Michael Jurkac9d95c52011-08-29 14:03:34 -07001196 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1197 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001198 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001199 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001200 for (ItemInfo childInfo : info.contents) {
1201 sBgItemsIdMap.remove(childInfo.id);
1202 sBgDbIconCache.remove(childInfo);
1203 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001204 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001205 }
1206 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001207 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001208 }
1209
1210 /**
1211 * Set this as the current Launcher activity object for the loader.
1212 */
1213 public void initialize(Callbacks callbacks) {
1214 synchronized (mLock) {
1215 mCallbacks = new WeakReference<Callbacks>(callbacks);
1216 }
1217 }
1218
Kenny Guyed131872014-04-30 03:02:21 +01001219 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001220 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001221 int op = PackageUpdatedTask.OP_UPDATE;
1222 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1223 user));
1224 }
1225
1226 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001227 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001228 int op = PackageUpdatedTask.OP_REMOVE;
1229 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1230 user));
1231 }
1232
1233 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001234 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001235 int op = PackageUpdatedTask.OP_ADD;
1236 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1237 user));
1238 }
1239
1240 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001241 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001242 boolean replacing) {
1243 if (!replacing) {
1244 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1245 user));
1246 if (mAppsCanBeOnRemoveableStorage) {
1247 // Only rebind if we support removable storage. It catches the
1248 // case where
1249 // apps on the external sd card need to be reloaded
1250 startLoaderFromBackground();
1251 }
1252 } else {
1253 // If we are replacing then just update the packages in the list
1254 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1255 packageNames, user));
1256 }
1257 }
1258
1259 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001260 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001261 boolean replacing) {
1262 if (!replacing) {
1263 enqueuePackageUpdated(new PackageUpdatedTask(
1264 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1265 user));
1266 }
1267
1268 }
1269
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001270 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001271 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1272 * ACTION_PACKAGE_CHANGED.
1273 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001274 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001275 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001276 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001277
Joe Onorato36115782010-06-17 13:28:48 -04001278 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001279 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001280 // If we have changed locale we need to clear out the labels in all apps/workspace.
1281 forceReload();
1282 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1283 // Check if configuration change was an mcc/mnc change which would affect app resources
1284 // and we would need to clear out the labels in all apps/workspace. Same handling as
1285 // above for ACTION_LOCALE_CHANGED
1286 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001287 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001288 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001289 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001290 forceReload();
1291 }
1292 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001293 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001294 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1295 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001296 Callbacks callbacks = getCallback();
1297 if (callbacks != null) {
1298 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001299 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001300 }
1301 }
1302
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001303 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001304 resetLoadedState(true, true);
1305
Reena Lee93f824a2011-09-23 17:20:28 -07001306 // Do this here because if the launcher activity is running it will be restarted.
1307 // If it's not running startLoaderFromBackground will merely tell it that it needs
1308 // to reload.
1309 startLoaderFromBackground();
1310 }
1311
Winson Chungf0c6ae02012-03-21 16:10:31 -07001312 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1313 synchronized (mLock) {
1314 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1315 // mWorkspaceLoaded to true later
1316 stopLoaderLocked();
1317 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1318 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1319 }
1320 }
1321
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001322 /**
1323 * When the launcher is in the background, it's possible for it to miss paired
1324 * configuration changes. So whenever we trigger the loader from the background
1325 * tell the launcher that it needs to re-run the loader when it comes back instead
1326 * of doing it now.
1327 */
1328 public void startLoaderFromBackground() {
1329 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001330 Callbacks callbacks = getCallback();
1331 if (callbacks != null) {
1332 // Only actually run the loader if they're not paused.
1333 if (!callbacks.setLoadOnResume()) {
1334 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001335 }
1336 }
1337 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001338 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001339 }
Joe Onorato36115782010-06-17 13:28:48 -04001340 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001341
Reena Lee93f824a2011-09-23 17:20:28 -07001342 // If there is already a loader task running, tell it to stop.
1343 // returns true if isLaunching() was true on the old task
1344 private boolean stopLoaderLocked() {
1345 boolean isLaunching = false;
1346 LoaderTask oldTask = mLoaderTask;
1347 if (oldTask != null) {
1348 if (oldTask.isLaunching()) {
1349 isLaunching = true;
1350 }
1351 oldTask.stopLocked();
1352 }
1353 return isLaunching;
1354 }
1355
Adam Cohen1a85c582014-09-30 09:48:49 -07001356 public boolean isCurrentCallbacks(Callbacks callbacks) {
1357 return (mCallbacks != null && mCallbacks.get() == callbacks);
1358 }
1359
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001360 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001361 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1362 }
1363
1364 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001365 synchronized (mLock) {
1366 if (DEBUG_LOADERS) {
1367 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1368 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001369
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 // Clear any deferred bind-runnables from the synchronized load process
1371 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001372 synchronized (mDeferredBindRunnables) {
1373 mDeferredBindRunnables.clear();
1374 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001375
Joe Onorato36115782010-06-17 13:28:48 -04001376 // Don't bother to start the thread if we know it's not going to do anything
1377 if (mCallbacks != null && mCallbacks.get() != null) {
1378 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001379 // also, don't downgrade isLaunching if we're already running
1380 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001381 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001382 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1383 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001384 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1385 } else {
1386 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1387 sWorker.post(mLoaderTask);
1388 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001389 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001390 }
1391 }
1392
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001393 void bindRemainingSynchronousPages() {
1394 // Post the remaining side pages to be loaded
1395 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001396 Runnable[] deferredBindRunnables = null;
1397 synchronized (mDeferredBindRunnables) {
1398 deferredBindRunnables = mDeferredBindRunnables.toArray(
1399 new Runnable[mDeferredBindRunnables.size()]);
1400 mDeferredBindRunnables.clear();
1401 }
1402 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001403 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001404 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001405 }
1406 }
1407
Joe Onorato36115782010-06-17 13:28:48 -04001408 public void stopLoader() {
1409 synchronized (mLock) {
1410 if (mLoaderTask != null) {
1411 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001412 }
1413 }
Joe Onorato36115782010-06-17 13:28:48 -04001414 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001415
Winson Chung76828c82013-08-19 15:43:29 -07001416 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1417 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1418 final ContentResolver contentResolver = context.getContentResolver();
1419 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1420 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1421 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1422
1423 try {
1424 final int idIndex = sc.getColumnIndexOrThrow(
1425 LauncherSettings.WorkspaceScreens._ID);
1426 final int rankIndex = sc.getColumnIndexOrThrow(
1427 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1428 while (sc.moveToNext()) {
1429 try {
1430 long screenId = sc.getLong(idIndex);
1431 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001432 orderedScreens.put(rank, screenId);
1433 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001434 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001435 }
1436 }
1437 } finally {
1438 sc.close();
1439 }
Winson Chunga90303b2013-11-15 13:05:06 -08001440
1441 // Log to disk
1442 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1443 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1444 for (Integer i : orderedScreens.keySet()) {
1445 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1446 }
1447 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1448 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001449 return orderedScreens;
1450 }
1451
Michael Jurkac57b7a82011-08-09 22:02:20 -07001452 public boolean isAllAppsLoaded() {
1453 return mAllAppsLoaded;
1454 }
1455
Winson Chung36a62fe2012-05-06 18:04:42 -07001456 boolean isLoadingWorkspace() {
1457 synchronized (mLock) {
1458 if (mLoaderTask != null) {
1459 return mLoaderTask.isLoadingWorkspace();
1460 }
1461 }
1462 return false;
1463 }
1464
Joe Onorato36115782010-06-17 13:28:48 -04001465 /**
1466 * Runnable for the thread that loads the contents of the launcher:
1467 * - workspace icons
1468 * - widgets
1469 * - all apps icons
1470 */
1471 private class LoaderTask implements Runnable {
1472 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001474 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001475 private boolean mStopped;
1476 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001477 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001478
Winson Chungc3eecff2011-07-11 17:44:15 -07001479 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001480
Dan Sandlerd5024042014-01-09 15:01:33 -05001481 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001482 mContext = context;
1483 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001484 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001485 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001486 }
1487
Joe Onorato36115782010-06-17 13:28:48 -04001488 boolean isLaunching() {
1489 return mIsLaunching;
1490 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001491
Winson Chung36a62fe2012-05-06 18:04:42 -07001492 boolean isLoadingWorkspace() {
1493 return mIsLoadingAndBindingWorkspace;
1494 }
1495
Winson Chungc763c4e2013-07-19 13:49:06 -07001496 /** Returns whether this is an upgrade path */
1497 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001498 mIsLoadingAndBindingWorkspace = true;
1499
Joe Onorato36115782010-06-17 13:28:48 -04001500 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001501 if (DEBUG_LOADERS) {
1502 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001503 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001504
Winson Chungc763c4e2013-07-19 13:49:06 -07001505 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001506 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001507 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001508 synchronized (LoaderTask.this) {
1509 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001510 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001511 }
1512 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001513 }
1514 }
1515
Joe Onorato36115782010-06-17 13:28:48 -04001516 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001517 bindWorkspace(-1, isUpgradePath);
1518 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001519 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001520
Joe Onorato36115782010-06-17 13:28:48 -04001521 private void waitForIdle() {
1522 // Wait until the either we're stopped or the other threads are done.
1523 // This way we don't start loading all apps until the workspace has settled
1524 // down.
1525 synchronized (LoaderTask.this) {
1526 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001527
Joe Onorato36115782010-06-17 13:28:48 -04001528 mHandler.postIdle(new Runnable() {
1529 public void run() {
1530 synchronized (LoaderTask.this) {
1531 mLoadAndBindStepFinished = true;
1532 if (DEBUG_LOADERS) {
1533 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001534 }
Joe Onorato36115782010-06-17 13:28:48 -04001535 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001536 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001537 }
Joe Onorato36115782010-06-17 13:28:48 -04001538 });
1539
Michael Jurkac7700af2013-05-14 20:17:58 +02001540 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001541 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001542 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1543 // wait no longer than 1sec at a time
1544 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001545 } catch (InterruptedException ex) {
1546 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001547 }
1548 }
Joe Onorato36115782010-06-17 13:28:48 -04001549 if (DEBUG_LOADERS) {
1550 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001551 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001552 + "ms for previous step to finish binding");
1553 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001554 }
Joe Onorato36115782010-06-17 13:28:48 -04001555 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001556
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001557 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001558 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001559 // Ensure that we have a valid page index to load synchronously
1560 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1561 "valid page index");
1562 }
1563 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1564 // Ensure that we don't try and bind a specified page when the pages have not been
1565 // loaded already (we should load everything asynchronously in that case)
1566 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1567 }
1568 synchronized (mLock) {
1569 if (mIsLoaderTaskRunning) {
1570 // Ensure that we are never running the background loading at this point since
1571 // we also touch the background collections
1572 throw new RuntimeException("Error! Background loading is already running");
1573 }
1574 }
1575
1576 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1577 // data structures, we can't allow any other thread to touch that data, but because
1578 // this call is synchronous, we can get away with not locking).
1579
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001580 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001581 // operations from the previous activity. We need to ensure that all queued operations
1582 // are executed before any synchronous binding work is done.
1583 mHandler.flush();
1584
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 // Divide the set of loaded items into those that we are binding synchronously, and
1586 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001587 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001588 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1589 // arise from that.
1590 onlyBindAllApps();
1591 }
1592
Joe Onorato36115782010-06-17 13:28:48 -04001593 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001594 boolean isUpgrade = false;
1595
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001596 synchronized (mLock) {
1597 mIsLoaderTaskRunning = true;
1598 }
Joe Onorato36115782010-06-17 13:28:48 -04001599 // Optimize for end-user experience: if the Launcher is up and // running with the
1600 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1601 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001602 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001603 // Elevate priority when Home launches for the first time to avoid
1604 // starving at boot time. Staring at a blank home is not cool.
1605 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001606 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1607 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001608 android.os.Process.setThreadPriority(mIsLaunching
1609 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1610 }
Winson Chung64359a52013-07-08 17:17:08 -07001611 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001612 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001613
Joe Onorato36115782010-06-17 13:28:48 -04001614 if (mStopped) {
1615 break keep_running;
1616 }
1617
1618 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1619 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001620 synchronized (mLock) {
1621 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001622 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001623 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1624 }
1625 }
Joe Onorato36115782010-06-17 13:28:48 -04001626 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001627
1628 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001629 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1630 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001631
1632 // Restore the default thread priority after we are done loading items
1633 synchronized (mLock) {
1634 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1635 }
Joe Onorato36115782010-06-17 13:28:48 -04001636 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001637
Winson Chungaac01e12011-08-17 10:37:13 -07001638 // Update the saved icons if necessary
1639 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001640 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001641 for (Object key : sBgDbIconCache.keySet()) {
1642 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1643 }
1644 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001645 }
Winson Chungaac01e12011-08-17 10:37:13 -07001646
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001647 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001648 // Ensure that all the applications that are in the system are
1649 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001650 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001651 verifyApplications();
1652 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001653 }
1654
Joe Onorato36115782010-06-17 13:28:48 -04001655 // Clear out this reference, otherwise we end up holding it until all of the
1656 // callback runnables are done.
1657 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001658
Joe Onorato36115782010-06-17 13:28:48 -04001659 synchronized (mLock) {
1660 // If we are still the last one to be scheduled, remove ourselves.
1661 if (mLoaderTask == this) {
1662 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001663 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001664 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001665 }
Joe Onorato36115782010-06-17 13:28:48 -04001666 }
1667
1668 public void stopLocked() {
1669 synchronized (LoaderTask.this) {
1670 mStopped = true;
1671 this.notify();
1672 }
1673 }
1674
1675 /**
1676 * Gets the callbacks object. If we've been stopped, or if the launcher object
1677 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1678 * object that was around when the deferred message was scheduled, and if there's
1679 * a new Callbacks object around then also return null. This will save us from
1680 * calling onto it with data that will be ignored.
1681 */
1682 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1683 synchronized (mLock) {
1684 if (mStopped) {
1685 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001686 }
Joe Onorato36115782010-06-17 13:28:48 -04001687
1688 if (mCallbacks == null) {
1689 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001690 }
Joe Onorato36115782010-06-17 13:28:48 -04001691
1692 final Callbacks callbacks = mCallbacks.get();
1693 if (callbacks != oldCallbacks) {
1694 return null;
1695 }
1696 if (callbacks == null) {
1697 Log.w(TAG, "no mCallbacks");
1698 return null;
1699 }
1700
1701 return callbacks;
1702 }
1703 }
1704
Winson Chungc763c4e2013-07-19 13:49:06 -07001705 private void verifyApplications() {
1706 final Context context = mApp.getContext();
1707
1708 // Cross reference all the applications in our apps list with items in the workspace
1709 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001710 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001711 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001712 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001713 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001714 if (tmpInfos.isEmpty()) {
1715 // We are missing an application icon, so add this to the workspace
1716 added.add(app);
1717 // This is a rare event, so lets log it
1718 Log.e(TAG, "Missing Application on load: " + app);
1719 }
1720 }
1721 }
1722 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001723 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001724 }
1725 }
1726
Joe Onorato36115782010-06-17 13:28:48 -04001727 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001728 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001729 LauncherAppState app = LauncherAppState.getInstance();
1730 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001731 final int countX = (int) grid.numColumns;
1732 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001733
Adam Cohendcd297f2013-06-18 13:13:40 -07001734 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001735 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001736 // Return early if we detect that an item is under the hotseat button
1737 if (mCallbacks == null ||
1738 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001739 Log.e(TAG, "Error loading shortcut into hotseat " + item
1740 + " into position (" + item.screenId + ":" + item.cellX + ","
1741 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001742 return false;
1743 }
1744
Dan Sandler295ae182013-12-10 16:05:47 -05001745 final ItemInfo[][] hotseatItems =
1746 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1747
Adam Cohenae4409d2013-11-26 10:34:59 -08001748 if (item.screenId >= grid.numHotseatIcons) {
1749 Log.e(TAG, "Error loading shortcut " + item
1750 + " into hotseat position " + item.screenId
1751 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1752 + ")");
1753 return false;
1754 }
1755
Dan Sandler295ae182013-12-10 16:05:47 -05001756 if (hotseatItems != null) {
1757 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001758 Log.e(TAG, "Error loading shortcut into hotseat " + item
1759 + " into position (" + item.screenId + ":" + item.cellX + ","
1760 + item.cellY + ") occupied by "
1761 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1762 [(int) item.screenId][0]);
1763 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001764 } else {
1765 hotseatItems[(int) item.screenId][0] = item;
1766 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001768 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001769 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001770 items[(int) item.screenId][0] = item;
1771 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001772 return true;
1773 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001774 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1775 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001776 return true;
1777 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001778
Adam Cohendcd297f2013-06-18 13:13:40 -07001779 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001780 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001781 occupied.put(item.screenId, items);
1782 }
1783
Dan Sandler295ae182013-12-10 16:05:47 -05001784 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001785 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1786 item.cellX < 0 || item.cellY < 0 ||
1787 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1788 Log.e(TAG, "Error loading shortcut " + item
1789 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1790 + item.cellX + "," + item.cellY
1791 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1792 return false;
1793 }
1794
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001795 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001796 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1797 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001798 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001799 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001801 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001802 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001804 return false;
1805 }
1806 }
1807 }
1808 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1809 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001810 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001811 }
1812 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001813
Joe Onorato36115782010-06-17 13:28:48 -04001814 return true;
1815 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001816
Winson Chungba9c37f2013-08-30 14:11:37 -07001817 /** Clears all the sBg data structures */
1818 private void clearSBgDataStructures() {
1819 synchronized (sBgLock) {
1820 sBgWorkspaceItems.clear();
1821 sBgAppWidgets.clear();
1822 sBgFolders.clear();
1823 sBgItemsIdMap.clear();
1824 sBgDbIconCache.clear();
1825 sBgWorkspaceScreens.clear();
1826 }
1827 }
1828
Dan Sandlerd5024042014-01-09 15:01:33 -05001829 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001830 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001831 // Log to disk
1832 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1833
Joe Onorato36115782010-06-17 13:28:48 -04001834 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001835
Joe Onorato36115782010-06-17 13:28:48 -04001836 final Context context = mContext;
1837 final ContentResolver contentResolver = context.getContentResolver();
1838 final PackageManager manager = context.getPackageManager();
1839 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1840 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001841 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1842 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001843 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001844
Winson Chung892c74d2013-08-22 16:15:50 -07001845 LauncherAppState app = LauncherAppState.getInstance();
1846 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1847 int countX = (int) grid.numColumns;
1848 int countY = (int) grid.numRows;
1849
Dan Sandlerd5024042014-01-09 15:01:33 -05001850 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1851 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1852 LauncherAppState.getLauncherProvider().deleteDatabase();
1853 }
1854
1855 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1856 // append the user's Launcher2 shortcuts
1857 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1858 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1859 } else {
1860 // Make sure the default workspace is loaded
1861 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001862 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001863 }
Adam Cohene25af792013-06-06 23:08:25 -07001864
Adam Cohen71483f42014-05-15 14:04:01 -07001865 // This code path is for our old migration code and should no longer be exercised
1866 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001867
Winson Chung9f9f00b2013-11-15 13:27:00 -08001868 // Log to disk
1869 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001870
Winson Chung2abf94d2012-07-18 18:16:38 -07001871 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001872 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001873 final HashSet<String> installingPkgs = PackageInstallerCompat
1874 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001875
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001876 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001877 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001878 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001879 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001880 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001881
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001882 // +1 for the hotseat (it can be larger than the workspace)
1883 // Load workspace in reverse order to ensure that latest items are loaded first (and
1884 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001885 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001886
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 try {
1888 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1889 final int intentIndex = c.getColumnIndexOrThrow
1890 (LauncherSettings.Favorites.INTENT);
1891 final int titleIndex = c.getColumnIndexOrThrow
1892 (LauncherSettings.Favorites.TITLE);
1893 final int iconTypeIndex = c.getColumnIndexOrThrow(
1894 LauncherSettings.Favorites.ICON_TYPE);
1895 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1896 final int iconPackageIndex = c.getColumnIndexOrThrow(
1897 LauncherSettings.Favorites.ICON_PACKAGE);
1898 final int iconResourceIndex = c.getColumnIndexOrThrow(
1899 LauncherSettings.Favorites.ICON_RESOURCE);
1900 final int containerIndex = c.getColumnIndexOrThrow(
1901 LauncherSettings.Favorites.CONTAINER);
1902 final int itemTypeIndex = c.getColumnIndexOrThrow(
1903 LauncherSettings.Favorites.ITEM_TYPE);
1904 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1905 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001906 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1907 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001908 final int screenIndex = c.getColumnIndexOrThrow(
1909 LauncherSettings.Favorites.SCREEN);
1910 final int cellXIndex = c.getColumnIndexOrThrow
1911 (LauncherSettings.Favorites.CELLX);
1912 final int cellYIndex = c.getColumnIndexOrThrow
1913 (LauncherSettings.Favorites.CELLY);
1914 final int spanXIndex = c.getColumnIndexOrThrow
1915 (LauncherSettings.Favorites.SPANX);
1916 final int spanYIndex = c.getColumnIndexOrThrow(
1917 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001918 final int restoredIndex = c.getColumnIndexOrThrow(
1919 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001920 final int profileIdIndex = c.getColumnIndexOrThrow(
1921 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001922 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1923 //final int displayModeIndex = c.getColumnIndexOrThrow(
1924 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001925
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001926 ShortcutInfo info;
1927 String intentDescription;
1928 LauncherAppWidgetInfo appWidgetInfo;
1929 int container;
1930 long id;
1931 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001932 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001933
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001934 while (!mStopped && c.moveToNext()) {
1935 try {
1936 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001937 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001938 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001939
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001940 switch (itemType) {
1941 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1942 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001943 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001944 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001945 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001946 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001947 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001948 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001949 if (user == null) {
1950 // User has been deleted remove the item.
1951 itemsToRemove.add(id);
1952 continue;
1953 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001954 try {
1955 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001956 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001957 if (cn != null && cn.getPackageName() != null) {
1958 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1959 cn.getPackageName(), user);
1960 boolean validComponent = validPkg &&
1961 launcherApps.isActivityEnabledForProfile(cn, user);
1962
1963 if (validComponent) {
1964 if (restored) {
1965 // no special handling necessary for this item
1966 restoredRows.add(id);
1967 restored = false;
1968 }
1969 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001970 intent = null;
1971 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1972 // We allow auto install apps to have their intent
1973 // updated after an install.
1974 intent = manager.getLaunchIntentForPackage(
1975 cn.getPackageName());
1976 if (intent != null) {
1977 ContentValues values = new ContentValues();
1978 values.put(LauncherSettings.Favorites.INTENT,
1979 intent.toUri(0));
1980 String where = BaseColumns._ID + "= ?";
1981 String[] args = {Long.toString(id)};
1982 contentResolver.update(contentUri, values, where, args);
1983 }
1984 }
1985
1986 if (intent == null) {
1987 // The app is installed but the component is no
1988 // longer available.
1989 Launcher.addDumpLog(TAG,
1990 "Invalid component removed: " + cn, true);
1991 itemsToRemove.add(id);
1992 continue;
1993 } else {
1994 // no special handling necessary for this item
1995 restoredRows.add(id);
1996 restored = false;
1997 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001998 } else if (restored) {
1999 // Package is not yet available but might be
2000 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002001 Launcher.addDumpLog(TAG,
2002 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002003
2004 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2005 // Restore has started once.
2006 } else if (installingPkgs.contains(cn.getPackageName())) {
2007 // App restore has started. Update the flag
2008 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2009 ContentValues values = new ContentValues();
2010 values.put(LauncherSettings.Favorites.RESTORED,
2011 promiseType);
2012 String where = BaseColumns._ID + "= ?";
2013 String[] args = {Long.toString(id)};
2014 contentResolver.update(contentUri, values, where, args);
2015
2016 } else if (REMOVE_UNRESTORED_ICONS) {
2017 Launcher.addDumpLog(TAG,
2018 "Unrestored package removed: " + cn, true);
2019 itemsToRemove.add(id);
2020 continue;
2021 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002022 } else if (launcherApps.isAppEnabled(
2023 manager, cn.getPackageName(),
2024 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2025 // Package is present but not available.
2026 allowMissingTarget = true;
2027 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2028 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002029 // SdCard is not ready yet. Package might get available,
2030 // once it is ready.
2031 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2032 + " (check again later)", true);
2033 HashSet<String> pkgs = sPendingPackages.get(user);
2034 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002035 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002036 sPendingPackages.put(user, pkgs);
2037 }
2038 pkgs.add(cn.getPackageName());
2039 allowMissingTarget = true;
2040 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002041
2042 } else {
2043 // Do not wait for external media load anymore.
2044 // Log the invalid package, and remove it
2045 Launcher.addDumpLog(TAG,
2046 "Invalid package removed: " + cn, true);
2047 itemsToRemove.add(id);
2048 continue;
Winson Chungee055712013-07-30 14:46:24 -07002049 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002050 } else if (cn == null) {
2051 // For shortcuts with no component, keep them as they are
2052 restoredRows.add(id);
2053 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002054 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002056 Launcher.addDumpLog(TAG,
2057 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002058 continue;
2059 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002060
Chris Wrenf4d08112014-01-16 18:13:56 -05002061 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002062 if (user.equals(UserHandleCompat.myUserHandle())) {
2063 Launcher.addDumpLog(TAG,
2064 "constructing info for partially restored package",
2065 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002066 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002067 intent = getRestoredItemIntent(c, context, intent);
2068 } else {
2069 // Don't restore items for other profiles.
2070 itemsToRemove.add(id);
2071 continue;
2072 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002073 } else if (itemType ==
2074 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002075 info = getShortcutInfo(manager, intent, user, context, c,
2076 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 } else {
2078 info = getShortcutInfo(c, context, iconTypeIndex,
2079 iconPackageIndex, iconResourceIndex, iconIndex,
2080 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002081
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 // App shortcuts that used to be automatically added to Launcher
2083 // didn't always have the correct intent flags set, so do that
2084 // here
2085 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002086 intent.getCategories() != null &&
2087 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002088 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 intent.addFlags(
2090 Intent.FLAG_ACTIVITY_NEW_TASK |
2091 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2092 }
Michael Jurka96879562012-03-22 05:54:33 -07002093 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002094
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002095 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002096 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002097 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 container = c.getInt(containerIndex);
2099 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002100 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002101 info.cellX = c.getInt(cellXIndex);
2102 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002103 info.spanX = 1;
2104 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002105 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002106 info.isDisabled = disabledState;
2107 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2108 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2109 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002110
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002112 if (!checkItemPlacement(occupied, info)) {
2113 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002114 break;
2115 }
2116
2117 switch (container) {
2118 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2119 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2120 sBgWorkspaceItems.add(info);
2121 break;
2122 default:
2123 // Item is in a user folder
2124 FolderInfo folderInfo =
2125 findOrMakeFolder(sBgFolders, container);
2126 folderInfo.add(info);
2127 break;
2128 }
2129 sBgItemsIdMap.put(info.id, info);
2130
2131 // now that we've loaded everthing re-save it with the
2132 // icon in case it disappears somehow.
2133 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002134 } else {
2135 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002136 }
2137 break;
2138
2139 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2140 id = c.getLong(idIndex);
2141 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2142
2143 folderInfo.title = c.getString(titleIndex);
2144 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002145 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002147 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 folderInfo.cellX = c.getInt(cellXIndex);
2149 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002150 folderInfo.spanX = 1;
2151 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002152
Daniel Sandler8802e962010-05-26 16:28:16 -04002153 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002154 if (!checkItemPlacement(occupied, folderInfo)) {
2155 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002156 break;
2157 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002158
Joe Onorato9c1289c2009-08-17 11:03:03 -04002159 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002160 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2161 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2162 sBgWorkspaceItems.add(folderInfo);
2163 break;
Joe Onorato36115782010-06-17 13:28:48 -04002164 }
Joe Onorato17a89222011-02-08 17:26:11 -08002165
Chris Wrenf4d08112014-01-16 18:13:56 -05002166 if (restored) {
2167 // no special handling required for restored folders
2168 restoredRows.add(id);
2169 }
2170
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002171 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2172 sBgFolders.put(folderInfo.id, folderInfo);
2173 break;
2174
2175 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2176 // Read all Launcher-specific widget details
2177 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002178 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002179 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002180 final ComponentName component =
2181 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002182
Sunny Goyal651077b2014-06-30 14:15:31 -07002183 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002184 final boolean isIdValid = (restoreStatus &
2185 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002186
Sunny Goyalff572272014-07-23 13:58:07 -07002187 final boolean wasProviderReady = (restoreStatus &
2188 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002189
Sunny Goyalff572272014-07-23 13:58:07 -07002190 final AppWidgetProviderInfo provider = isIdValid
2191 ? widgets.getAppWidgetInfo(appWidgetId)
2192 : findAppWidgetProviderInfoWithComponent(context, component);
2193
2194 final boolean isProviderReady = isValidProvider(provider);
2195 if (!isSafeMode && wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002196 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002197 + "id=" + id + " appWidgetId=" + appWidgetId;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002198 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002199 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002200 itemsToRemove.add(id);
2201 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002202 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002203 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2204 provider.provider);
2205 int[] minSpan =
2206 Launcher.getMinSpanForWidget(context, provider);
2207 appWidgetInfo.minSpanX = minSpan[0];
2208 appWidgetInfo.minSpanY = minSpan[1];
Sunny Goyalff572272014-07-23 13:58:07 -07002209
2210 int status = restoreStatus;
2211 if (!wasProviderReady) {
2212 // If provider was not previously ready, update the
2213 // status and UI flag.
2214
2215 // Id would be valid only if the widget restore broadcast was received.
2216 if (isIdValid) {
2217 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2218 } else {
2219 status &= ~LauncherAppWidgetInfo
2220 .FLAG_PROVIDER_NOT_READY;
2221 }
2222 }
2223 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002224 } else {
2225 Log.v(TAG, "Widget restore pending id=" + id
2226 + " appWidgetId=" + appWidgetId
2227 + " status =" + restoreStatus);
2228 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002229 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002230 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002231
2232 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2233 // Restore has started once.
2234 } else if (installingPkgs.contains(component.getPackageName())) {
2235 // App restore has started. Update the flag
2236 appWidgetInfo.restoreStatus |=
2237 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002238 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002239 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002240 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002241 itemsToRemove.add(id);
2242 continue;
2243 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002244 }
Sunny Goyalff572272014-07-23 13:58:07 -07002245
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002246 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002247 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002248 appWidgetInfo.cellX = c.getInt(cellXIndex);
2249 appWidgetInfo.cellY = c.getInt(cellYIndex);
2250 appWidgetInfo.spanX = c.getInt(spanXIndex);
2251 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002252
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002253 container = c.getInt(containerIndex);
2254 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2255 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2256 Log.e(TAG, "Widget found where container != " +
2257 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2258 continue;
2259 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002260
Adam Cohene25af792013-06-06 23:08:25 -07002261 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002263 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2264 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002265 break;
2266 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002267
Sunny Goyal94485362014-09-18 16:13:58 -07002268 String providerName = appWidgetInfo.providerName.flattenToString();
2269 if (!providerName.equals(savedProvider) ||
2270 (appWidgetInfo.restoreStatus != restoreStatus)) {
2271 ContentValues values = new ContentValues();
2272 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2273 providerName);
2274 values.put(LauncherSettings.Favorites.RESTORED,
2275 appWidgetInfo.restoreStatus);
2276 String where = BaseColumns._ID + "= ?";
2277 String[] args = {Long.toString(id)};
2278 contentResolver.update(contentUri, values, where, args);
Chris Wrenc3919c02013-09-18 09:48:33 -04002279 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2281 sBgAppWidgets.add(appWidgetInfo);
2282 }
Joe Onorato36115782010-06-17 13:28:48 -04002283 break;
2284 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002286 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 }
2289 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002290 if (c != null) {
2291 c.close();
2292 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 }
2294
Winson Chungba9c37f2013-08-30 14:11:37 -07002295 // Break early if we've stopped loading
2296 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002297 clearSBgDataStructures();
2298 return false;
2299 }
2300
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 if (itemsToRemove.size() > 0) {
2302 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002303 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002304 // Remove dead items
2305 for (long id : itemsToRemove) {
2306 if (DEBUG_LOADERS) {
2307 Log.d(TAG, "Removed id = " + id);
2308 }
2309 // Don't notify content observers
2310 try {
2311 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2312 null, null);
2313 } catch (RemoteException e) {
2314 Log.w(TAG, "Could not remove id = " + id);
2315 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002316 }
2317 }
2318
Chris Wrenf4d08112014-01-16 18:13:56 -05002319 if (restoredRows.size() > 0) {
2320 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002321 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002322 // Update restored items that no longer require special handling
2323 try {
2324 StringBuilder selectionBuilder = new StringBuilder();
2325 selectionBuilder.append(LauncherSettings.Favorites._ID);
2326 selectionBuilder.append(" IN (");
2327 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2328 selectionBuilder.append(")");
2329 ContentValues values = new ContentValues();
2330 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002331 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002332 values, selectionBuilder.toString(), null);
2333 } catch (RemoteException e) {
2334 Log.w(TAG, "Could not update restored rows");
2335 }
2336 }
2337
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002338 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2339 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002340 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002341 null, sWorker);
2342 }
2343
Winson Chungc763c4e2013-07-19 13:49:06 -07002344 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002345 long maxScreenId = 0;
2346 // If we're importing we use the old screen order.
2347 for (ItemInfo item: sBgItemsIdMap.values()) {
2348 long screenId = item.screenId;
2349 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2350 !sBgWorkspaceScreens.contains(screenId)) {
2351 sBgWorkspaceScreens.add(screenId);
2352 if (screenId > maxScreenId) {
2353 maxScreenId = screenId;
2354 }
2355 }
2356 }
2357 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002358 // Log to disk
2359 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2360 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2361 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002362
Michael Jurka414300a2013-08-27 15:42:35 +02002363 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002364 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002365
2366 // Update the max item id after we load an old db
2367 long maxItemId = 0;
2368 // If we're importing we use the old screen order.
2369 for (ItemInfo item: sBgItemsIdMap.values()) {
2370 maxItemId = Math.max(maxItemId, item.id);
2371 }
Michael Jurka414300a2013-08-27 15:42:35 +02002372 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002373 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002374 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2375 for (Integer i : orderedScreens.keySet()) {
2376 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002378 // Log to disk
2379 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2380 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002381
2382 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002383 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002384 for (ItemInfo item: sBgItemsIdMap.values()) {
2385 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002386 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2387 unusedScreens.contains(screenId)) {
2388 unusedScreens.remove(screenId);
2389 }
2390 }
2391
2392 // If there are any empty screens remove them, and update.
2393 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002394 // Log to disk
2395 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2396 TextUtils.join(", ", unusedScreens), true);
2397
Winson Chung933bae62013-08-29 11:42:30 -07002398 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002399 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2400 }
2401 }
2402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 if (DEBUG_LOADERS) {
2404 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2405 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002406 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002407 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002408 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002409
Daniel Sandler566da102013-06-25 23:43:45 -04002410 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002411 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002412 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002413 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002414 line += " | ";
2415 }
Winson Chung892c74d2013-08-22 16:15:50 -07002416 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002417 ItemInfo[][] screen = occupied.get(screenId);
2418 if (x < screen.length && y < screen[x].length) {
2419 line += (screen[x][y] != null) ? "#" : ".";
2420 } else {
2421 line += "!";
2422 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002423 }
Joe Onorato36115782010-06-17 13:28:48 -04002424 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002425 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002426 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002427 }
Joe Onorato36115782010-06-17 13:28:48 -04002428 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002429 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002430 }
2431
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432 /** Filters the set of items who are directly or indirectly (via another container) on the
2433 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002434 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 ArrayList<ItemInfo> allWorkspaceItems,
2436 ArrayList<ItemInfo> currentScreenItems,
2437 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002438 // Purge any null ItemInfos
2439 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2440 while (iter.hasNext()) {
2441 ItemInfo i = iter.next();
2442 if (i == null) {
2443 iter.remove();
2444 }
2445 }
2446
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002447 // Order the set of items by their containers first, this allows use to walk through the
2448 // list sequentially, build up a list of containers that are in the specified screen,
2449 // as well as all items in those containers.
2450 Set<Long> itemsOnScreen = new HashSet<Long>();
2451 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2452 @Override
2453 public int compare(ItemInfo lhs, ItemInfo rhs) {
2454 return (int) (lhs.container - rhs.container);
2455 }
2456 });
2457 for (ItemInfo info : allWorkspaceItems) {
2458 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002459 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002460 currentScreenItems.add(info);
2461 itemsOnScreen.add(info.id);
2462 } else {
2463 otherScreenItems.add(info);
2464 }
2465 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2466 currentScreenItems.add(info);
2467 itemsOnScreen.add(info.id);
2468 } else {
2469 if (itemsOnScreen.contains(info.container)) {
2470 currentScreenItems.add(info);
2471 itemsOnScreen.add(info.id);
2472 } else {
2473 otherScreenItems.add(info);
2474 }
2475 }
2476 }
2477 }
2478
2479 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002480 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002481 ArrayList<LauncherAppWidgetInfo> appWidgets,
2482 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2483 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484
2485 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002486 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002487 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002488 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 currentScreenWidgets.add(widget);
2490 } else {
2491 otherScreenWidgets.add(widget);
2492 }
2493 }
2494 }
2495
2496 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002497 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002498 HashMap<Long, ItemInfo> itemsIdMap,
2499 HashMap<Long, FolderInfo> folders,
2500 HashMap<Long, FolderInfo> currentScreenFolders,
2501 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002502
2503 for (long id : folders.keySet()) {
2504 ItemInfo info = itemsIdMap.get(id);
2505 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002506 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002508 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002509 currentScreenFolders.put(id, folder);
2510 } else {
2511 otherScreenFolders.put(id, folder);
2512 }
2513 }
2514 }
2515
2516 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2517 * right) */
2518 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002519 final LauncherAppState app = LauncherAppState.getInstance();
2520 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 // XXX: review this
2522 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002523 @Override
2524 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002525 int cellCountX = (int) grid.numColumns;
2526 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002527 int screenOffset = cellCountX * cellCountY;
2528 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002529 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002530 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002531 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002532 rhs.cellY * cellCountX + rhs.cellX);
2533 return (int) (lr - rr);
2534 }
2535 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002537
Adam Cohendcd297f2013-06-18 13:13:40 -07002538 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2539 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002540 final Runnable r = new Runnable() {
2541 @Override
2542 public void run() {
2543 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2544 if (callbacks != null) {
2545 callbacks.bindScreens(orderedScreens);
2546 }
2547 }
2548 };
2549 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2550 }
2551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2553 final ArrayList<ItemInfo> workspaceItems,
2554 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2555 final HashMap<Long, FolderInfo> folders,
2556 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002557
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 final boolean postOnMainThread = (deferredBindRunnables != null);
2559
2560 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002561 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002563 final int start = i;
2564 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002565 final Runnable r = new Runnable() {
2566 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002567 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002568 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002569 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002570 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2571 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002572 }
2573 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002574 };
2575 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002576 synchronized (deferredBindRunnables) {
2577 deferredBindRunnables.add(r);
2578 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002579 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002580 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002581 }
Joe Onorato36115782010-06-17 13:28:48 -04002582 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583
2584 // Bind the folders
2585 if (!folders.isEmpty()) {
2586 final Runnable r = new Runnable() {
2587 public void run() {
2588 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2589 if (callbacks != null) {
2590 callbacks.bindFolders(folders);
2591 }
2592 }
2593 };
2594 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002595 synchronized (deferredBindRunnables) {
2596 deferredBindRunnables.add(r);
2597 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002599 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002600 }
2601 }
2602
2603 // Bind the widgets, one at a time
2604 N = appWidgets.size();
2605 for (int i = 0; i < N; i++) {
2606 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2607 final Runnable r = new Runnable() {
2608 public void run() {
2609 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2610 if (callbacks != null) {
2611 callbacks.bindAppWidget(widget);
2612 }
2613 }
2614 };
2615 if (postOnMainThread) {
2616 deferredBindRunnables.add(r);
2617 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002618 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002619 }
2620 }
2621 }
2622
2623 /**
2624 * Binds all loaded data to actual views on the main thread.
2625 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002626 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 final long t = SystemClock.uptimeMillis();
2628 Runnable r;
2629
2630 // Don't use these two variables in any of the callback runnables.
2631 // Otherwise we hold a reference to them.
2632 final Callbacks oldCallbacks = mCallbacks.get();
2633 if (oldCallbacks == null) {
2634 // This launcher has exited and nobody bothered to tell us. Just bail.
2635 Log.w(TAG, "LoaderTask running with no launcher");
2636 return;
2637 }
2638
Winson Chung9b9fb962013-11-15 15:39:34 -08002639 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2641 ArrayList<LauncherAppWidgetInfo> appWidgets =
2642 new ArrayList<LauncherAppWidgetInfo>();
2643 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2644 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002645 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002646 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002647 workspaceItems.addAll(sBgWorkspaceItems);
2648 appWidgets.addAll(sBgAppWidgets);
2649 folders.putAll(sBgFolders);
2650 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002651 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 }
2653
Derek Prothro7aff3992013-12-10 14:00:37 -05002654 final boolean isLoadingSynchronously =
2655 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002656 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002657 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002658 if (currScreen >= orderedScreenIds.size()) {
2659 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002660 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002661 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002662 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002663 final long currentScreenId = currentScreen < 0
2664 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002665
2666 // Load all the items that are on the current page first (and in the process, unbind
2667 // all the existing workspace items before we call startBinding() below.
2668 unbindWorkspaceItemsOnMainThread();
2669
2670 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2672 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2673 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2674 new ArrayList<LauncherAppWidgetInfo>();
2675 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2676 new ArrayList<LauncherAppWidgetInfo>();
2677 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2678 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2679
Winson Chung9b9fb962013-11-15 15:39:34 -08002680 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002682 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002683 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002684 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002685 otherFolders);
2686 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2687 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2688
2689 // Tell the workspace that we're about to start binding items
2690 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002691 public void run() {
2692 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2693 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002694 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002695 }
2696 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002697 };
Winson Chung81b52252012-08-27 15:34:29 -07002698 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002699
Adam Cohendcd297f2013-06-18 13:13:40 -07002700 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2701
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002702 // Load items on the current page
2703 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2704 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002705 if (isLoadingSynchronously) {
2706 r = new Runnable() {
2707 public void run() {
2708 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002709 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002710 callbacks.onPageBoundSynchronously(currentScreen);
2711 }
2712 }
2713 };
Winson Chung81b52252012-08-27 15:34:29 -07002714 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002715 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002716
Winson Chung4a2afa32012-07-19 14:53:05 -07002717 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2718 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002719 synchronized (mDeferredBindRunnables) {
2720 mDeferredBindRunnables.clear();
2721 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002722 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002723 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002724
2725 // Tell the workspace that we're done binding items
2726 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002727 public void run() {
2728 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2729 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002730 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002731 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002732
Winson Chung98e030b2012-05-07 16:01:11 -07002733 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002734 if (DEBUG_LOADERS) {
2735 Log.d(TAG, "bound workspace in "
2736 + (SystemClock.uptimeMillis()-t) + "ms");
2737 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002738
2739 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002740 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002741 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002742 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002743 synchronized (mDeferredBindRunnables) {
2744 mDeferredBindRunnables.add(r);
2745 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002746 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002747 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002748 }
Joe Onorato36115782010-06-17 13:28:48 -04002749 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002750
Joe Onorato36115782010-06-17 13:28:48 -04002751 private void loadAndBindAllApps() {
2752 if (DEBUG_LOADERS) {
2753 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2754 }
2755 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002756 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002757 synchronized (LoaderTask.this) {
2758 if (mStopped) {
2759 return;
2760 }
2761 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002762 }
Joe Onorato36115782010-06-17 13:28:48 -04002763 } else {
2764 onlyBindAllApps();
2765 }
2766 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002767
Joe Onorato36115782010-06-17 13:28:48 -04002768 private void onlyBindAllApps() {
2769 final Callbacks oldCallbacks = mCallbacks.get();
2770 if (oldCallbacks == null) {
2771 // This launcher has exited and nobody bothered to tell us. Just bail.
2772 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2773 return;
2774 }
2775
2776 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002777 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002778 final ArrayList<AppInfo> list
2779 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002780 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002781 public void run() {
2782 final long t = SystemClock.uptimeMillis();
2783 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2784 if (callbacks != null) {
2785 callbacks.bindAllApplications(list);
2786 }
2787 if (DEBUG_LOADERS) {
2788 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2789 + (SystemClock.uptimeMillis()-t) + "ms");
2790 }
2791 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002792 };
2793 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002794 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002795 r.run();
2796 } else {
2797 mHandler.post(r);
2798 }
Joe Onorato36115782010-06-17 13:28:48 -04002799 }
2800
Winson Chung64359a52013-07-08 17:17:08 -07002801 private void loadAllApps() {
2802 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002803
Joe Onorato36115782010-06-17 13:28:48 -04002804 final Callbacks oldCallbacks = mCallbacks.get();
2805 if (oldCallbacks == null) {
2806 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002807 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002808 return;
2809 }
2810
2811 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2812 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2813
Kenny Guyed131872014-04-30 03:02:21 +01002814 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2815
Winson Chung64359a52013-07-08 17:17:08 -07002816 // Clear the list of apps
2817 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002818 SharedPreferences prefs = mContext.getSharedPreferences(
2819 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002820 for (UserHandleCompat user : profiles) {
2821 // Query for the set of apps
2822 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2823 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2824 if (DEBUG_LOADERS) {
2825 Log.d(TAG, "getActivityList took "
2826 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2827 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2828 }
2829 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002830 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002831 if (apps == null || apps.isEmpty()) {
2832 return;
2833 }
2834 // Sort the applications by name
2835 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2836 Collections.sort(apps,
2837 new LauncherModel.ShortcutNameComparator(mLabelCache));
2838 if (DEBUG_LOADERS) {
2839 Log.d(TAG, "sort took "
2840 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2841 }
Joe Onorato36115782010-06-17 13:28:48 -04002842
Kenny Guyed131872014-04-30 03:02:21 +01002843 // Create the ApplicationInfos
2844 for (int i = 0; i < apps.size(); i++) {
2845 LauncherActivityInfoCompat app = apps.get(i);
2846 // This builds the icon bitmaps.
2847 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2848 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002849
2850 if (!user.equals(UserHandleCompat.myUserHandle())) {
2851 // Add shortcuts for packages which were installed while launcher was dead.
2852 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2853 + mUserManager.getSerialNumberForUser(user);
2854 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2855 HashSet<String> newPackageSet = new HashSet<String>();
2856
2857 for (LauncherActivityInfoCompat info : apps) {
2858 String packageName = info.getComponentName().getPackageName();
2859 if (!packagesAdded.contains(packageName)
2860 && !newPackageSet.contains(packageName)) {
2861 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2862 }
2863 newPackageSet.add(packageName);
2864 }
2865
2866 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2867 }
Winson Chung64359a52013-07-08 17:17:08 -07002868 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002869 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002870 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2871 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002872
2873 // Post callback on main thread
2874 mHandler.post(new Runnable() {
2875 public void run() {
2876 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002877 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002878 if (callbacks != null) {
2879 callbacks.bindAllApplications(added);
2880 if (DEBUG_LOADERS) {
2881 Log.d(TAG, "bound " + added.size() + " apps in "
2882 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2883 }
2884 } else {
2885 Log.i(TAG, "not binding apps: no Launcher activity");
2886 }
2887 }
2888 });
2889
Joe Onorato36115782010-06-17 13:28:48 -04002890 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002891 Log.d(TAG, "Icons processed in "
2892 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002893 }
2894 }
2895
2896 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002897 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002898 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2899 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2900 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2901 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2902 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2903 }
Joe Onorato36115782010-06-17 13:28:48 -04002904 }
2905 }
2906
2907 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002908 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002909 }
2910
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002911 private class AppsAvailabilityCheck extends BroadcastReceiver {
2912
2913 @Override
2914 public void onReceive(Context context, Intent intent) {
2915 synchronized (sBgLock) {
2916 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2917 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002918 final PackageManager manager = context.getPackageManager();
2919 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2920 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002921 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2922 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002923 packagesRemoved.clear();
2924 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002925 for (String pkg : entry.getValue()) {
2926 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002927 boolean packageOnSdcard = launcherApps.isAppEnabled(
2928 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2929 if (packageOnSdcard) {
2930 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2931 packagesUnavailable.add(pkg);
2932 } else {
2933 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2934 packagesRemoved.add(pkg);
2935 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 }
2937 }
2938 if (!packagesRemoved.isEmpty()) {
2939 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2940 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2941 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002942 if (!packagesUnavailable.isEmpty()) {
2943 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2944 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2945 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002946 }
Sunny Goyal34942622014-08-29 17:20:55 -07002947 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002948 }
2949 }
2950 }
2951
Joe Onorato36115782010-06-17 13:28:48 -04002952 private class PackageUpdatedTask implements Runnable {
2953 int mOp;
2954 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002955 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002956
2957 public static final int OP_NONE = 0;
2958 public static final int OP_ADD = 1;
2959 public static final int OP_UPDATE = 2;
2960 public static final int OP_REMOVE = 3; // uninstlled
2961 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2962
2963
Kenny Guyed131872014-04-30 03:02:21 +01002964 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002965 mOp = op;
2966 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002967 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002968 }
2969
2970 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002971 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002972
2973 final String[] packages = mPackages;
2974 final int N = packages.length;
2975 switch (mOp) {
2976 case OP_ADD:
2977 for (int i=0; i<N; i++) {
2978 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01002979 mIconCache.remove(packages[i], mUser);
2980 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002981 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002982
2983 // Auto add shortcuts for added packages.
2984 if (!UserHandleCompat.myUserHandle().equals(mUser)) {
2985 SharedPreferences prefs = context.getSharedPreferences(
2986 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2987 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2988 + mUserManager.getSerialNumberForUser(mUser);
2989 Set<String> shortcutSet = new HashSet<String>(
2990 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2991
2992 for (int i=0; i<N; i++) {
2993 if (!shortcutSet.contains(packages[i])) {
2994 shortcutSet.add(packages[i]);
2995 List<LauncherActivityInfoCompat> activities =
2996 mLauncherApps.getActivityList(packages[i], mUser);
2997 if (activities != null && !activities.isEmpty()) {
2998 InstallShortcutReceiver.queueInstallShortcut(
2999 activities.get(0), context);
3000 }
3001 }
3002 }
3003
3004 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3005 }
Joe Onorato36115782010-06-17 13:28:48 -04003006 break;
3007 case OP_UPDATE:
3008 for (int i=0; i<N; i++) {
3009 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003010 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003011 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003012 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003013 }
3014 break;
3015 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003016 // Remove the packageName for the set of auto-installed shortcuts. This
3017 // will ensure that the shortcut when the app is installed again.
3018 if (!UserHandleCompat.myUserHandle().equals(mUser)) {
3019 SharedPreferences prefs = context.getSharedPreferences(
3020 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3021 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3022 + mUserManager.getSerialNumberForUser(mUser);
3023 HashSet<String> shortcutSet = new HashSet<String>(
3024 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3025 shortcutSet.removeAll(Arrays.asList(mPackages));
3026 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3027 }
3028 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003029 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003030 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003031 for (int i=0; i<N; i++) {
3032 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003033 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003034 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003035 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003036 }
3037 break;
3038 }
3039
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003040 ArrayList<AppInfo> added = null;
3041 ArrayList<AppInfo> modified = null;
3042 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003043
Adam Cohen487f7dd2012-06-28 18:12:10 -07003044 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003045 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003046 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003047 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003048 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003049 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003050 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003051 }
Winson Chung5d55f332012-07-16 20:45:03 -07003052 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003053 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003054 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003055 }
3056
Sunny Goyale0f58d72014-11-10 18:05:31 -08003057 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003058 if (callbacks == null) {
3059 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3060 return;
3061 }
3062
Sunny Goyal4390ace2014-10-13 11:33:11 -07003063 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3064 new HashMap<ComponentName, AppInfo>();
3065
Joe Onorato36115782010-06-17 13:28:48 -04003066 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003067 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003068 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003069 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003070 addAndBindAddedWorkspaceApps(context, addedInfos);
3071 } else {
3072 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003073 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003074 for (AppInfo ai : added) {
3075 addedOrUpdatedApps.put(ai.componentName, ai);
3076 }
Joe Onorato36115782010-06-17 13:28:48 -04003077 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003078
Joe Onorato36115782010-06-17 13:28:48 -04003079 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003080 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003081 for (AppInfo ai : modified) {
3082 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003083 }
3084
Joe Onorato36115782010-06-17 13:28:48 -04003085 mHandler.post(new Runnable() {
3086 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003087 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003088 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003089 callbacks.bindAppsUpdated(modifiedFinal);
3090 }
3091 }
3092 });
3093 }
Winson Chung83892cc2013-05-01 16:53:33 -07003094
Sunny Goyal4390ace2014-10-13 11:33:11 -07003095 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003096 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003097 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3098 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3099 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3100
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003101 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003102 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003103 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003104 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3105 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003106 boolean infoUpdated = false;
3107 boolean shortcutUpdated = false;
3108
3109 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003110 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003111 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003112 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3113 si.iconResource.resourceName, mIconCache, context);
3114 if (icon != null) {
3115 si.setIcon(icon);
3116 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003117 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003118 }
3119 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003120
3121 ComponentName cn = si.getTargetComponent();
3122 if (cn != null && packageSet.contains(cn.getPackageName())) {
3123 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3124
3125 if (si.isPromise()) {
3126 mIconCache.deletePreloadedIcon(cn, mUser);
3127 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3128 // Auto install icon
3129 PackageManager pm = context.getPackageManager();
3130 ResolveInfo matched = pm.resolveActivity(
3131 new Intent(Intent.ACTION_MAIN)
3132 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3133 PackageManager.MATCH_DEFAULT_ONLY);
3134 if (matched == null) {
3135 // Try to find the best match activity.
3136 Intent intent = pm.getLaunchIntentForPackage(
3137 cn.getPackageName());
3138 if (intent != null) {
3139 cn = intent.getComponent();
3140 appInfo = addedOrUpdatedApps.get(cn);
3141 }
3142
3143 if ((intent == null) || (appInfo == null)) {
3144 removedShortcuts.add(si);
3145 continue;
3146 }
3147 si.promisedIntent = intent;
3148 }
3149 }
3150
3151 // Restore the shortcut.
3152 si.intent = si.promisedIntent;
3153 si.promisedIntent = null;
3154 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3155 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3156 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3157
3158 infoUpdated = true;
3159 si.updateIcon(mIconCache);
3160 }
3161
3162 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3163 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3164 si.updateIcon(mIconCache);
3165 si.title = appInfo.title.toString();
3166 si.contentDescription = appInfo.contentDescription;
3167 infoUpdated = true;
3168 }
3169
3170 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3171 // Since package was just updated, the target must be available now.
3172 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3173 shortcutUpdated = true;
3174 }
3175 }
3176
3177 if (infoUpdated || shortcutUpdated) {
3178 updatedShortcuts.add(si);
3179 }
3180 if (infoUpdated) {
3181 updateItemInDatabase(context, si);
3182 }
3183 } else if (info instanceof LauncherAppWidgetInfo) {
3184 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3185 if (mUser.equals(widgetInfo.user)
3186 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3187 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3188 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3189 widgets.add(widgetInfo);
3190 updateItemInDatabase(context, widgetInfo);
3191 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003192 }
3193 }
3194 }
3195
Sunny Goyal4390ace2014-10-13 11:33:11 -07003196 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3197 mHandler.post(new Runnable() {
3198
3199 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003200 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003201 if (callbacks == cb && cb != null) {
3202 callbacks.bindShortcutsChanged(
3203 updatedShortcuts, removedShortcuts, mUser);
3204 }
3205 }
3206 });
3207 if (!removedShortcuts.isEmpty()) {
3208 deleteItemsFromDatabase(context, removedShortcuts);
3209 }
3210 }
3211 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003212 mHandler.post(new Runnable() {
3213 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003214 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003215 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003216 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003217 }
3218 }
3219 });
3220 }
3221 }
3222
Winson Chungdf95eb12013-10-16 14:57:07 -07003223 final ArrayList<String> removedPackageNames =
3224 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003225 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003226 // Mark all packages in the broadcast to be removed
3227 removedPackageNames.addAll(Arrays.asList(packages));
3228 } else if (mOp == OP_UPDATE) {
3229 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003230 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003231 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003232 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003233 }
3234 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003235 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003236
Winson Chungdf95eb12013-10-16 14:57:07 -07003237 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003238 final int removeReason;
3239 if (mOp == OP_UNAVAILABLE) {
3240 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3241 } else {
3242 // Remove all the components associated with this package
3243 for (String pn : removedPackageNames) {
3244 deletePackageFromDatabase(context, pn, mUser);
3245 }
3246 // Remove all the specific components
3247 for (AppInfo a : removedApps) {
3248 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3249 deleteItemsFromDatabase(context, infos);
3250 }
3251 removeReason = 0;
3252 }
3253
Winson Chungdf95eb12013-10-16 14:57:07 -07003254 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003255 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003256 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003257 mHandler.post(new Runnable() {
3258 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003259 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003260 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003261 callbacks.bindComponentsRemoved(
3262 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003263 }
3264 }
3265 });
Joe Onoratobe386092009-11-17 17:32:16 -08003266 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003267
Michael Jurkac402cd92013-05-20 15:49:32 +02003268 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003269 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003270 mHandler.post(new Runnable() {
3271 @Override
3272 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003273 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003274 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003275 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003276 }
3277 }
3278 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003279
3280 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003281 mHandler.post(new Runnable() {
3282 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003283 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003284 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003285 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003286 }
3287 }
3288 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003289 }
3290 }
3291
Michael Jurkac402cd92013-05-20 15:49:32 +02003292 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3293 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3294 PackageManager packageManager = context.getPackageManager();
3295 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Sunny Goyalffe83f12014-08-14 17:39:34 -07003296 widgetsAndShortcuts.addAll(AppWidgetManagerCompat.getInstance(context).getAllProviders());
3297
Michael Jurkac402cd92013-05-20 15:49:32 +02003298 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3299 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003300 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003301 return widgetsAndShortcuts;
3302 }
3303
Kenny Guyed131872014-04-30 03:02:21 +01003304 private static boolean isPackageDisabled(Context context, String packageName,
3305 UserHandleCompat user) {
3306 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3307 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003308 }
Adam Cohen556f6132014-01-15 15:18:08 -08003309
Kenny Guyed131872014-04-30 03:02:21 +01003310 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3311 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003312 if (cn == null) {
3313 return false;
3314 }
Kenny Guyed131872014-04-30 03:02:21 +01003315 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3316 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003317 return false;
3318 }
Kenny Guyed131872014-04-30 03:02:21 +01003319 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003320 }
3321
Adam Cohena28b78e2014-05-20 17:03:04 -07003322 public static boolean isValidPackage(Context context, String packageName,
3323 UserHandleCompat user) {
3324 if (packageName == null) {
3325 return false;
3326 }
3327 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3328 return launcherApps.isPackageEnabledForProfile(packageName, user);
3329 }
3330
Joe Onorato9c1289c2009-08-17 11:03:03 -04003331 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003332 * Make an ShortcutInfo object for a restored application or shortcut item that points
3333 * to a package that is not yet installed on the system.
3334 */
Sunny Goyal34942622014-08-29 17:20:55 -07003335 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3336 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003337 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003338 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003339 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3340
3341 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3342 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3343 if (!TextUtils.isEmpty(title)) {
3344 info.title = title;
3345 }
3346 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3347 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3348 if (TextUtils.isEmpty(info.title)) {
3349 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3350 }
3351 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3352 } else {
3353 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3354 }
3355
Kenny Guyc2bd8102014-06-30 12:30:31 +01003356 info.contentDescription = mUserManager.getBadgedLabelForUser(
3357 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003358 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003359 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003360 return info;
3361 }
3362
3363 /**
3364 * Make an Intent object for a restored application or shortcut item that points
3365 * to the market page for the item.
3366 */
3367 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3368 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003369 return getMarketIntent(componentName.getPackageName());
3370 }
3371
3372 static Intent getMarketIntent(String packageName) {
3373 return new Intent(Intent.ACTION_VIEW)
3374 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003375 .scheme("market")
3376 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003377 .appendQueryParameter("id", packageName)
3378 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003379 }
3380
3381 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003382 * This is called from the code that adds shortcuts from the intent receiver. This
3383 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003384 */
Kenny Guyed131872014-04-30 03:02:21 +01003385 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3386 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003387 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003388 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003389
Joe Onorato56d82912010-03-07 14:32:10 -05003390 /**
3391 * Make an ShortcutInfo object for a shortcut that is an application.
3392 *
3393 * If c is not null, then it will be used to fill in missing data like the title and icon.
3394 */
Kenny Guyed131872014-04-30 03:02:21 +01003395 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3396 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003397 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003398 if (user == null) {
3399 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003400 return null;
3401 }
3402
Kenny Guyed131872014-04-30 03:02:21 +01003403 ComponentName componentName = intent.getComponent();
3404 if (componentName == null) {
3405 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3406 return null;
3407 }
3408
3409 Intent newIntent = new Intent(intent.getAction(), null);
3410 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3411 newIntent.setComponent(componentName);
3412 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003413 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003414 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3415 return null;
3416 }
3417
3418 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003419
Joe Onorato56d82912010-03-07 14:32:10 -05003420 // the resource -- This may implicitly give us back the fallback icon,
3421 // but don't worry about that. All we're doing with usingFallbackIcon is
3422 // to avoid saving lots of copies of that in the database, and most apps
3423 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003424 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003425
Joe Onorato56d82912010-03-07 14:32:10 -05003426 // the db
3427 if (icon == null) {
3428 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003429 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003430 }
3431 }
3432 // the fallback icon
3433 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003434 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003435 info.usingFallbackIcon = true;
3436 }
3437 info.setIcon(icon);
3438
Kenny Guyed131872014-04-30 03:02:21 +01003439 // From the cache.
3440 if (labelCache != null) {
3441 info.title = labelCache.get(componentName);
3442 }
3443
Joe Onorato56d82912010-03-07 14:32:10 -05003444 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003445 if (info.title == null && lai != null) {
3446 info.title = lai.getLabel();
3447 if (labelCache != null) {
3448 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003449 }
Joe Onorato56d82912010-03-07 14:32:10 -05003450 }
3451 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003452 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003453 if (c != null) {
3454 info.title = c.getString(titleIndex);
3455 }
3456 }
3457 // fall back to the class name of the activity
3458 if (info.title == null) {
3459 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003460 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003461 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003462 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003463 info.contentDescription = mUserManager.getBadgedLabelForUser(
3464 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003465 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003466 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003467
Winson Chung64359a52013-07-08 17:17:08 -07003468 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3469 ItemInfoFilter f) {
3470 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3471 for (ItemInfo i : infos) {
3472 if (i instanceof ShortcutInfo) {
3473 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003474 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003475 if (cn != null && f.filterItem(null, info, cn)) {
3476 filtered.add(info);
3477 }
3478 } else if (i instanceof FolderInfo) {
3479 FolderInfo info = (FolderInfo) i;
3480 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003481 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003482 if (cn != null && f.filterItem(info, s, cn)) {
3483 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003484 }
3485 }
Winson Chung64359a52013-07-08 17:17:08 -07003486 } else if (i instanceof LauncherAppWidgetInfo) {
3487 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3488 ComponentName cn = info.providerName;
3489 if (cn != null && f.filterItem(null, info, cn)) {
3490 filtered.add(info);
3491 }
Winson Chung8a435102012-08-30 17:16:53 -07003492 }
3493 }
Winson Chung64359a52013-07-08 17:17:08 -07003494 return new ArrayList<ItemInfo>(filtered);
3495 }
3496
Kenny Guyed131872014-04-30 03:02:21 +01003497 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3498 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003499 ItemInfoFilter filter = new ItemInfoFilter() {
3500 @Override
3501 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003502 if (info.user == null) {
3503 return cn.equals(cname);
3504 } else {
3505 return cn.equals(cname) && info.user.equals(user);
3506 }
Winson Chung64359a52013-07-08 17:17:08 -07003507 }
3508 };
3509 return filterItemInfos(sBgItemsIdMap.values(), filter);
3510 }
3511
Sunny Goyal1a745e82014-10-02 15:58:31 -07003512 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003513 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003514 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003515 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003516 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3517 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003518
Joe Onorato56d82912010-03-07 14:32:10 -05003519 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003520 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003521 // Non-app shortcuts are only supported for current user.
3522 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003523 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003524
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003525 // TODO: If there's an explicit component and we can't install that, delete it.
3526
Joe Onorato56d82912010-03-07 14:32:10 -05003527 info.title = c.getString(titleIndex);
3528
Joe Onorato9c1289c2009-08-17 11:03:03 -04003529 int iconType = c.getInt(iconTypeIndex);
3530 switch (iconType) {
3531 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3532 String packageName = c.getString(iconPackageIndex);
3533 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003534 info.customIcon = false;
3535 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003536 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003537 // the db
3538 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003539 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003540 }
3541 // the fallback icon
3542 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003543 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003544 info.usingFallbackIcon = true;
3545 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003546 break;
3547 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003548 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003549 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003550 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003551 info.customIcon = false;
3552 info.usingFallbackIcon = true;
3553 } else {
3554 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003555 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003556 break;
3557 default:
Kenny Guyed131872014-04-30 03:02:21 +01003558 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003559 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003560 info.customIcon = false;
3561 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003562 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003563 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003564 return info;
3565 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003566
Michael Jurka931dc972011-08-05 15:08:15 -07003567 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003568 @SuppressWarnings("all") // suppress dead code warning
3569 final boolean debug = false;
3570 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003571 Log.d(TAG, "getIconFromCursor app="
3572 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3573 }
3574 byte[] data = c.getBlob(iconIndex);
3575 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003576 return Utilities.createIconBitmap(
3577 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003578 } catch (Exception e) {
3579 return null;
3580 }
3581 }
3582
Winson Chunga9abd0e2010-10-27 17:18:37 -07003583 /**
Winson Chung55cef262010-10-28 14:14:18 -07003584 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3585 */
Sunny Goyal0fc1be12014-08-11 17:05:23 -07003586 static AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
Winson Chung55cef262010-10-28 14:14:18 -07003587 ComponentName component) {
3588 List<AppWidgetProviderInfo> widgets =
3589 AppWidgetManager.getInstance(context).getInstalledProviders();
3590 for (AppWidgetProviderInfo info : widgets) {
3591 if (info.provider.equals(component)) {
3592 return info;
3593 }
3594 }
3595 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003596 }
3597
Sunny Goyal2350bc92014-10-14 16:42:54 -07003598 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003599 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3600 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3601 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3602
Adam Cohend9198822011-11-22 16:42:47 -08003603 if (intent == null) {
3604 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3605 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3606 return null;
3607 }
3608
Joe Onorato0589f0f2010-02-08 13:44:00 -08003609 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003610 boolean customIcon = false;
3611 ShortcutIconResource iconResource = null;
3612
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003613 if (bitmap instanceof Bitmap) {
3614 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003615 customIcon = true;
3616 } else {
3617 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003618 if (extra instanceof ShortcutIconResource) {
3619 iconResource = (ShortcutIconResource) extra;
3620 icon = Utilities.createIconBitmap(iconResource.packageName,
3621 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003622 }
3623 }
3624
Michael Jurkac9d95c52011-08-29 14:03:34 -07003625 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003626
Kenny Guyed131872014-04-30 03:02:21 +01003627 // Only support intents for current user for now. Intents sent from other
3628 // users wouldn't get here without intent forwarding anyway.
3629 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003630 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003631 icon = mIconCache.getDefaultIcon(info.user);
3632 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003633 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003634 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003635
Joe Onorato0589f0f2010-02-08 13:44:00 -08003636 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003637 info.contentDescription = mUserManager.getBadgedLabelForUser(
3638 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003639 info.intent = intent;
3640 info.customIcon = customIcon;
3641 info.iconResource = iconResource;
3642
3643 return info;
3644 }
3645
Winson Chungaac01e12011-08-17 10:37:13 -07003646 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3647 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003648 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003649 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003650 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003651 }
Joe Onorato56d82912010-03-07 14:32:10 -05003652 // If this icon doesn't have a custom icon, check to see
3653 // what's stored in the DB, and if it doesn't match what
3654 // we're going to show, store what we are going to show back
3655 // into the DB. We do this so when we're loading, if the
3656 // package manager can't find an icon (for example because
3657 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003658 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003659 cache.put(info, c.getBlob(iconIndex));
3660 return true;
3661 }
3662 return false;
3663 }
3664 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3665 boolean needSave = false;
3666 try {
3667 if (data != null) {
3668 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3669 Bitmap loaded = info.getIcon(mIconCache);
3670 needSave = !saved.sameAs(loaded);
3671 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003672 needSave = true;
3673 }
Winson Chungaac01e12011-08-17 10:37:13 -07003674 } catch (Exception e) {
3675 needSave = true;
3676 }
3677 if (needSave) {
3678 Log.d(TAG, "going to save icon bitmap for info=" + info);
3679 // This is slower than is ideal, but this only happens once
3680 // or when the app is updated with a new icon.
3681 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003682 }
3683 }
3684
Joe Onorato9c1289c2009-08-17 11:03:03 -04003685 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003686 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003687 * or make a new one.
3688 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003689 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003690 // See if a placeholder was created for us already
3691 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003692 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003693 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003694 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003695 folders.put(id, folderInfo);
3696 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003697 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003698 }
3699
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003700 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003701 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003702 return new Comparator<AppInfo>() {
3703 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003704 if (a.user.equals(b.user)) {
3705 int result = collator.compare(a.title.toString().trim(),
3706 b.title.toString().trim());
3707 if (result == 0) {
3708 result = a.componentName.compareTo(b.componentName);
3709 }
3710 return result;
3711 } else {
3712 // TODO Need to figure out rules for sorting
3713 // profiles, this puts work second.
3714 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003715 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003716 }
Winson Chung11904872012-09-17 16:58:46 -07003717 };
3718 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003719 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3720 = new Comparator<AppInfo>() {
3721 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003722 if (a.firstInstallTime < b.firstInstallTime) return 1;
3723 if (a.firstInstallTime > b.firstInstallTime) return -1;
3724 return 0;
3725 }
3726 };
Winson Chung5308f242011-08-18 12:12:41 -07003727 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3728 if (info.activityInfo != null) {
3729 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3730 } else {
3731 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3732 }
3733 }
Kenny Guyed131872014-04-30 03:02:21 +01003734 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003735 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003736 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003737 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003738 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003739 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003740 }
Kenny Guyed131872014-04-30 03:02:21 +01003741 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003742 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003743 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003744 }
Kenny Guyed131872014-04-30 03:02:21 +01003745 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003746 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003747 ComponentName keyA = a.getComponentName();
3748 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003749 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003750 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003751 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003752 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003753
Winson Chung5308f242011-08-18 12:12:41 -07003754 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003755 }
Winson Chung5308f242011-08-18 12:12:41 -07003756 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003757 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003758 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003759 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003760
Winson Chung5308f242011-08-18 12:12:41 -07003761 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003762 }
Winson Chung11904872012-09-17 16:58:46 -07003763 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003764 }
3765 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003766 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003767 private final AppWidgetManagerCompat mManager;
3768 private final PackageManager mPackageManager;
3769 private final HashMap<Object, String> mLabelCache;
3770 private final Collator mCollator;
3771
3772 WidgetAndShortcutNameComparator(Context context) {
3773 mManager = AppWidgetManagerCompat.getInstance(context);
3774 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003775 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003776 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003777 }
3778 public final int compare(Object a, Object b) {
3779 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003780 if (mLabelCache.containsKey(a)) {
3781 labelA = mLabelCache.get(a);
3782 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003783 labelA = (a instanceof AppWidgetProviderInfo)
3784 ? mManager.loadLabel((AppWidgetProviderInfo) a)
3785 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003786 mLabelCache.put(a, labelA);
3787 }
3788 if (mLabelCache.containsKey(b)) {
3789 labelB = mLabelCache.get(b);
3790 } else {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003791 labelB = (b instanceof AppWidgetProviderInfo)
3792 ? mManager.loadLabel((AppWidgetProviderInfo) b)
3793 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003794 mLabelCache.put(b, labelB);
3795 }
Winson Chung11904872012-09-17 16:58:46 -07003796 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003797 }
3798 };
Joe Onoratobe386092009-11-17 17:32:16 -08003799
Sunny Goyal651077b2014-06-30 14:15:31 -07003800 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3801 return (provider != null) && (provider.provider != null)
3802 && (provider.provider.getPackageName() != null);
3803 }
3804
Joe Onoratobe386092009-11-17 17:32:16 -08003805 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003806 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003807 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3808 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3809 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3810 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003811 if (mLoaderTask != null) {
3812 mLoaderTask.dumpState();
3813 } else {
3814 Log.d(TAG, "mLoaderTask=null");
3815 }
Joe Onoratobe386092009-11-17 17:32:16 -08003816 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003817
3818 public Callbacks getCallback() {
3819 return mCallbacks != null ? mCallbacks.get() : null;
3820 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003821}