blob: 95ebaec87309dd11f87222ec162acb6f4525aea7 [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.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
Sunny Goyale0f58d72014-11-10 18:05:31 -080032import android.content.pm.LauncherApps.Callback;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040034import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070036import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.content.res.Resources;
38import android.database.Cursor;
39import android.graphics.Bitmap;
40import android.graphics.BitmapFactory;
41import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040049import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080050import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070051import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070077import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079/**
80 * Maintains in-memory state of the Launcher. It is expected that there should be only one
81 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070082 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 */
Kenny Guyed131872014-04-30 03:02:21 +010084public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010085 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080086 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040087 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070088 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080089 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
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
Adam Cohen59400422014-03-05 18:07:04 -0800176 // sBgWidgetProviders is the set of widget providers including custom internal widgets
177 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
178 public static boolean sWidgetProvidersDirty;
179
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700180 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700181 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
182 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700183
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 // </ only access in worker thread >
185
186 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187
Reena Lee99a73f32011-10-24 17:27:37 -0700188 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700189
Kenny Guyed131872014-04-30 03:02:21 +0100190 private final LauncherAppsCompat mLauncherApps;
191 private final UserManagerCompat mUserManager;
192
Joe Onorato9c1289c2009-08-17 11:03:03 -0400193 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700194 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400195 public int getCurrentWorkspaceScreen();
196 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700197 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
198 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700199 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700200 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500201 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700202 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400203 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200204 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700205 public void bindAppsAdded(ArrayList<Long> newScreens,
206 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700207 ArrayList<ItemInfo> addAnimated,
208 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200209 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700210 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
211 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
212 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700213 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700214 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700215 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700216 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200217 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100218 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700219 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700220 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700221 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400222 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223
Winson Chung64359a52013-07-08 17:17:08 -0700224 public interface ItemInfoFilter {
225 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
226 }
227
Bjorn Bringert1307f632013-10-03 22:31:03 +0100228 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800229 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400230
Winson Chungee055712013-07-30 14:46:24 -0700231 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700232 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400233 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
234 // resource string.
235 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
236 ProviderInfo providerInfo =
237 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
238 ProviderInfo redirectProvider =
239 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700240
241 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400242 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700243
244 if (mOldContentProviderExists) {
245 Log.d(TAG, "Old launcher provider exists.");
246 } else {
247 Log.d(TAG, "Old launcher provider does not exist.");
248 }
249
Daniel Sandlere4f98912013-06-25 15:13:26 -0400250 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100251 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800252 mIconCache = iconCache;
253
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400254 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700255 Configuration config = res.getConfiguration();
256 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100257 mLauncherApps = LauncherAppsCompat.getInstance(context);
258 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800259 }
260
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700261 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
262 * posted on the main thread handler. */
263 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700264 runOnMainThread(r, 0);
265 }
266 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700267 if (sWorkerThread.getThreadId() == Process.myTid()) {
268 // If we are on the worker thread, post onto the main handler
269 mHandler.post(r);
270 } else {
271 r.run();
272 }
273 }
274
275 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
276 * posted on the worker thread handler. */
277 private static void runOnWorkerThread(Runnable r) {
278 if (sWorkerThread.getThreadId() == Process.myTid()) {
279 r.run();
280 } else {
281 // If we are not on the worker thread, then post to the worker handler
282 sWorker.post(r);
283 }
284 }
285
Winson Chunge43a1e72014-01-15 10:33:02 -0800286 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
287 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800288 }
289
Winson Chungc9168342013-06-26 14:54:55 -0700290 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
291 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700292 LauncherAppState app = LauncherAppState.getInstance();
293 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
294 final int xCount = (int) grid.numColumns;
295 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700296 boolean[][] occupied = new boolean[xCount][yCount];
297
298 int cellX, cellY, spanX, spanY;
299 for (int i = 0; i < items.size(); ++i) {
300 final ItemInfo item = items.get(i);
301 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
302 if (item.screenId == screen) {
303 cellX = item.cellX;
304 cellY = item.cellY;
305 spanX = item.spanX;
306 spanY = item.spanY;
307 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
308 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
309 occupied[x][y] = true;
310 }
311 }
312 }
313 }
314 }
315
316 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
317 }
318 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700319 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700320 int firstScreenIndex,
321 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700322 // Lock on the app so that we don't try and get the items while apps are being added
323 LauncherAppState app = LauncherAppState.getInstance();
324 LauncherModel model = app.getModel();
325 boolean found = false;
326 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700327 if (sWorkerThread.getThreadId() != Process.myTid()) {
328 // Flush the LauncherModel worker thread, so that if we just did another
329 // processInstallShortcut, we give it time for its shortcut to get added to the
330 // database (getItemsInLocalCoordinates reads the database)
331 model.flushWorkerThread();
332 }
Winson Chungc9168342013-06-26 14:54:55 -0700333 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700334
335 // Try adding to the workspace screens incrementally, starting at the default or center
336 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700337 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
338 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700339 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700340 int[] tmpCoordinates = new int[2];
341 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700342 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700343 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700344 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700345 }
346 }
347 }
Winson Chungc9168342013-06-26 14:54:55 -0700348 return null;
349 }
350
Sunny Goyale755d462014-07-22 13:48:29 -0700351 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500352 // Process the updated package state
353 Runnable r = new Runnable() {
354 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800355 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500356 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700357 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500358 }
359 }
360 };
361 mHandler.post(r);
362 }
363
Sunny Goyala22666f2014-09-18 13:25:15 -0700364 public void updatePackageBadge(final String packageName) {
365 // Process the updated package badge
366 Runnable r = new Runnable() {
367 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800368 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700369 if (callbacks != null) {
370 callbacks.updatePackageBadge(packageName);
371 }
372 }
373 };
374 mHandler.post(r);
375 }
376
Adam Cohen76a47a12014-02-05 11:47:43 -0800377 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800378 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800379
380 if (allAppsApps == null) {
381 throw new RuntimeException("allAppsApps must not be null");
382 }
383 if (allAppsApps.isEmpty()) {
384 return;
385 }
386
387 // Process the newly added applications and add them to the database first
388 Runnable r = new Runnable() {
389 public void run() {
390 runOnMainThread(new Runnable() {
391 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800392 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800393 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500394 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800395 }
396 }
397 });
398 }
399 };
400 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700401 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800402
403 public void addAndBindAddedWorkspaceApps(final Context context,
404 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800405 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800406
407 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800408 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
409 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800410 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700411 return;
Winson Chung997a9232013-07-24 15:33:46 -0700412 }
Winson Chung64359a52013-07-08 17:17:08 -0700413 // Process the newly added applications and add them to the database first
414 Runnable r = new Runnable() {
415 public void run() {
416 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
417 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
418
Winson Chung76828c82013-08-19 15:43:29 -0700419 // Get the list of workspace screens. We need to append to this list and
420 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
421 // called.
422 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
423 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
424 for (Integer i : orderedScreens.keySet()) {
425 long screenId = orderedScreens.get(i);
426 workspaceScreens.add(screenId);
427 }
428
Winson Chung64359a52013-07-08 17:17:08 -0700429 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700430 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700431 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700432 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700433 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700434 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700435
436 // Short-circuit this logic if the icon exists somewhere on the workspace
Sunny Goyale0f58d72014-11-10 18:05:31 -0800437 if (shortcutExists(context, name, launchIntent, a.user)) {
Winson Chung64359a52013-07-08 17:17:08 -0700438 continue;
439 }
440
Winson Chung87412982013-10-03 18:34:14 -0700441 // Add this icon to the db, creating a new page if necessary. If there
442 // is only the empty page then we just add items to the first page.
443 // Otherwise, we add them to the next pages.
444 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700445 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700446 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700447 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200448 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700449
450 // If we can't find a valid position, then just add a new screen.
451 // This takes time so we need to re-queue the add until the new
452 // page is added. Create as many screens as necessary to satisfy
453 // the startSearchPageIndex.
454 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700455 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 while (numPagesToAdd > 0) {
457 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700458 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700459 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700460 addedWorkspaceScreensFinal.add(screenId);
461 numPagesToAdd--;
462 }
Winson Chung76828c82013-08-19 15:43:29 -0700463
Winson Chung64359a52013-07-08 17:17:08 -0700464 // Find the coordinate again
465 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700466 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700467 }
468 if (coords == null) {
469 throw new RuntimeException("Coordinates should not be null");
470 }
471
Winson Chung997a9232013-07-24 15:33:46 -0700472 ShortcutInfo shortcutInfo;
473 if (a instanceof ShortcutInfo) {
474 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200475 } else if (a instanceof AppInfo) {
476 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700477 } else {
478 throw new RuntimeException("Unexpected info type");
479 }
Winson Chung94d67682013-09-25 16:29:40 -0700480
Winson Chung64359a52013-07-08 17:17:08 -0700481 // Add the shortcut to the db
482 addItemToDatabase(context, shortcutInfo,
483 LauncherSettings.Favorites.CONTAINER_DESKTOP,
484 coords.first, coords.second[0], coords.second[1], false);
485 // Save the ShortcutInfo for binding in the workspace
486 addedShortcutsFinal.add(shortcutInfo);
487 }
488 }
489
Winson Chung76828c82013-08-19 15:43:29 -0700490 // Update the workspace screens
491 updateWorkspaceScreenOrder(context, workspaceScreens);
492
Adam Cohen76a47a12014-02-05 11:47:43 -0800493 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700494 runOnMainThread(new Runnable() {
495 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800496 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700497 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700498 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
499 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700500 if (!addedShortcutsFinal.isEmpty()) {
501 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
502 long lastScreenId = info.screenId;
503 for (ItemInfo i : addedShortcutsFinal) {
504 if (i.screenId == lastScreenId) {
505 addAnimated.add(i);
506 } else {
507 addNotAnimated.add(i);
508 }
Winson Chung997a9232013-07-24 15:33:46 -0700509 }
510 }
Winson Chungd64d1762013-08-20 14:37:16 -0700511 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800512 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700513 }
Winson Chung64359a52013-07-08 17:17:08 -0700514 }
Winson Chung997a9232013-07-24 15:33:46 -0700515 });
516 }
Winson Chung64359a52013-07-08 17:17:08 -0700517 }
518 };
519 runOnWorkerThread(r);
520 }
521
Winson Chung81b52252012-08-27 15:34:29 -0700522 public void unbindItemInfosAndClearQueuedBindRunnables() {
523 if (sWorkerThread.getThreadId() == Process.myTid()) {
524 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
525 "main thread");
526 }
527
528 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400529 synchronized (mDeferredBindRunnables) {
530 mDeferredBindRunnables.clear();
531 }
Winson Chung81b52252012-08-27 15:34:29 -0700532 // Remove any queued bind runnables
533 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
534 // Unbind all the workspace items
535 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700536 }
537
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700538 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700539 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700540 // Ensure that we don't use the same workspace items data structure on the main thread
541 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700542 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
543 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700544 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700545 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
546 tmpAppWidgets.addAll(sBgAppWidgets);
547 }
548 Runnable r = new Runnable() {
549 @Override
550 public void run() {
551 for (ItemInfo item : tmpWorkspaceItems) {
552 item.unbind();
553 }
554 for (ItemInfo item : tmpAppWidgets) {
555 item.unbind();
556 }
557 }
558 };
559 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700560 }
561
Joe Onorato9c1289c2009-08-17 11:03:03 -0400562 /**
563 * Adds an item to the DB if it was not created previously, or move it to a new
564 * <container, screen, cellX, cellY>
565 */
566 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700567 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400568 if (item.container == ItemInfo.NO_ID) {
569 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400571 } else {
572 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 }
575 }
576
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700577 static void checkItemInfoLocked(
578 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
579 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
580 if (modelItem != null && item != modelItem) {
581 // check all the data is consistent
582 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
583 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
584 ShortcutInfo shortcut = (ShortcutInfo) item;
585 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
586 modelShortcut.intent.filterEquals(shortcut.intent) &&
587 modelShortcut.id == shortcut.id &&
588 modelShortcut.itemType == shortcut.itemType &&
589 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700590 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700591 modelShortcut.cellX == shortcut.cellX &&
592 modelShortcut.cellY == shortcut.cellY &&
593 modelShortcut.spanX == shortcut.spanX &&
594 modelShortcut.spanY == shortcut.spanY &&
595 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
596 (modelShortcut.dropPos != null &&
597 shortcut.dropPos != null &&
598 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
599 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
600 // For all intents and purposes, this is the same object
601 return;
602 }
603 }
604
605 // the modelItem needs to match up perfectly with item if our model is
606 // to be consistent with the database-- for now, just require
607 // modelItem == item or the equality check above
608 String msg = "item: " + ((item != null) ? item.toString() : "null") +
609 "modelItem: " +
610 ((modelItem != null) ? modelItem.toString() : "null") +
611 "Error: ItemInfo passed to checkItemInfo doesn't match original";
612 RuntimeException e = new RuntimeException(msg);
613 if (stackTrace != null) {
614 e.setStackTrace(stackTrace);
615 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800616 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700617 }
618 }
619
Michael Jurka816474f2012-06-25 14:49:02 -0700620 static void checkItemInfo(final ItemInfo item) {
621 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
622 final long itemId = item.id;
623 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700624 public void run() {
625 synchronized (sBgLock) {
626 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700627 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700628 }
629 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700630 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700631 }
632
Michael Jurkac9d95c52011-08-29 14:03:34 -0700633 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
634 final ItemInfo item, final String callingFunction) {
635 final long itemId = item.id;
636 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
637 final ContentResolver cr = context.getContentResolver();
638
Adam Cohen487f7dd2012-06-28 18:12:10 -0700639 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700640 Runnable r = new Runnable() {
641 public void run() {
642 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700643 updateItemArrays(item, itemId, stackTrace);
644 }
645 };
646 runOnWorkerThread(r);
647 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700648
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700649 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
650 final ArrayList<ItemInfo> items, final String callingFunction) {
651 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700652
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700653 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
654 Runnable r = new Runnable() {
655 public void run() {
656 ArrayList<ContentProviderOperation> ops =
657 new ArrayList<ContentProviderOperation>();
658 int count = items.size();
659 for (int i = 0; i < count; i++) {
660 ItemInfo item = items.get(i);
661 final long itemId = item.id;
662 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
663 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700664
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700665 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
666 updateItemArrays(item, itemId, stackTrace);
667
668 }
669 try {
670 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
671 } catch (Exception e) {
672 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700673 }
674 }
675 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700676 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700677 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700678
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700679 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
680 // Lock on mBgLock *after* the db operation
681 synchronized (sBgLock) {
682 checkItemInfoLocked(itemId, item, stackTrace);
683
684 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
685 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
686 // Item is in a folder, make sure this folder exists
687 if (!sBgFolders.containsKey(item.container)) {
688 // An items container is being set to a that of an item which is not in
689 // the list of Folders.
690 String msg = "item: " + item + " container being set to: " +
691 item.container + ", not in the list of folders";
692 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700693 }
694 }
695
696 // Items are added/removed from the corresponding FolderInfo elsewhere, such
697 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
698 // that are on the desktop, as appropriate
699 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800700 if (modelItem != null &&
701 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
702 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700703 switch (modelItem.itemType) {
704 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
705 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
706 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
707 if (!sBgWorkspaceItems.contains(modelItem)) {
708 sBgWorkspaceItems.add(modelItem);
709 }
710 break;
711 default:
712 break;
713 }
714 } else {
715 sBgWorkspaceItems.remove(modelItem);
716 }
717 }
718 }
719
Michael Jurkac7700af2013-05-14 20:17:58 +0200720 public void flushWorkerThread() {
721 mFlushingWorkerThread = true;
722 Runnable waiter = new Runnable() {
723 public void run() {
724 synchronized (this) {
725 notifyAll();
726 mFlushingWorkerThread = false;
727 }
728 }
729 };
730
731 synchronized(waiter) {
732 runOnWorkerThread(waiter);
733 if (mLoaderTask != null) {
734 synchronized(mLoaderTask) {
735 mLoaderTask.notify();
736 }
737 }
738 boolean success = false;
739 while (!success) {
740 try {
741 waiter.wait();
742 success = true;
743 } catch (InterruptedException e) {
744 }
745 }
746 }
747 }
748
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400750 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700751 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700752 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700753 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 item.cellX = cellX;
756 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757
Winson Chung3d503fb2011-07-13 17:25:49 -0700758 // We store hotseat items in canonical form which is this orientation invariant position
759 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700763 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700764 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700765 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766
767 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400768 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700769 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
770 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800771 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700772 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400773
Michael Jurkac9d95c52011-08-29 14:03:34 -0700774 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700775 }
776
777 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700778 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
779 * cellX, cellY have already been updated on the ItemInfos.
780 */
781 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
782 final long container, final int screen) {
783
784 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
785 int count = items.size();
786
787 for (int i = 0; i < count; i++) {
788 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700789 item.container = container;
790
791 // We store hotseat items in canonical form which is this orientation invariant position
792 // in the hotseat
793 if (context instanceof Launcher && screen < 0 &&
794 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700795 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700796 item.cellY);
797 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700798 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700799 }
800
801 final ContentValues values = new ContentValues();
802 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
803 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
804 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800805 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700806 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700807
808 contentValues.add(values);
809 }
810 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
811 }
812
813 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700814 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800815 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700816 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700817 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700818 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800819 item.cellX = cellX;
820 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700821 item.spanX = spanX;
822 item.spanY = spanY;
823
824 // We store hotseat items in canonical form which is this orientation invariant position
825 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700830 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700831 }
Adam Cohend4844c32011-02-18 19:25:06 -0800832
Adam Cohend4844c32011-02-18 19:25:06 -0800833 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800834 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700835 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
836 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800837 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700838 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
839 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700840 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800841
Michael Jurka816474f2012-06-25 14:49:02 -0700842 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700843 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700844
845 /**
846 * Update an item to the database in a specified container.
847 */
848 static void updateItemInDatabase(Context context, final ItemInfo item) {
849 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100850 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700851 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800852 }
853
854 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400855 * Returns true if the shortcuts already exists in the database.
856 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800857 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800858 static boolean shortcutExists(Context context, String title, Intent intent,
859 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400860 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700861 final Intent intentWithPkg, intentWithoutPkg;
862
863 if (intent.getComponent() != null) {
864 // If component is not null, an intent with null package will produce
865 // the same result and should also be a match.
866 if (intent.getPackage() != null) {
867 intentWithPkg = intent;
868 intentWithoutPkg = new Intent(intent).setPackage(null);
869 } else {
870 intentWithPkg = new Intent(intent).setPackage(
871 intent.getComponent().getPackageName());
872 intentWithoutPkg = intent;
873 }
874 } else {
875 intentWithPkg = intent;
876 intentWithoutPkg = intent;
877 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800878 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
879 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400880 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800881 new String[] { "title", "intent", "profileId" },
882 "title=? and (intent=? or intent=?) and profileId=?",
883 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
884 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800886 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400887 } finally {
888 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800889 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700890 }
891
Joe Onorato9c1289c2009-08-17 11:03:03 -0400892 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700893 * Returns an ItemInfo array containing all the items in the LauncherModel.
894 * The ItemInfo.id is not set through this function.
895 */
896 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
897 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
898 final ContentResolver cr = context.getContentResolver();
899 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
900 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100901 LauncherSettings.Favorites.SCREEN,
902 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
903 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
904 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700905
906 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
907 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
908 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
909 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
910 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800911 final int rankIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.RANK);
Winson Chungaafa03c2010-06-11 17:34:16 -0700912 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
913 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100914 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
915 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 try {
917 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700918 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700919 item.cellX = c.getInt(cellXIndex);
920 item.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -0800921 item.rank = c.getInt(rankIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700922 item.spanX = Math.max(1, c.getInt(spanXIndex));
923 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700924 item.container = c.getInt(containerIndex);
925 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700926 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100927 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100928 item.user = userManager.getUserForSerialNumber(serialNumber);
929 // Skip if user has been deleted.
930 if (item.user != null) {
931 items.add(item);
932 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700933 }
934 } catch (Exception e) {
935 items.clear();
936 } finally {
937 c.close();
938 }
939
940 return items;
941 }
942
943 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400944 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
945 */
946 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
947 final ContentResolver cr = context.getContentResolver();
948 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
949 "_id=? and (itemType=? or itemType=?)",
950 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700951 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700952
Joe Onorato9c1289c2009-08-17 11:03:03 -0400953 try {
954 if (c.moveToFirst()) {
955 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
956 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
957 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
958 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
959 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
960 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800961
Joe Onorato9c1289c2009-08-17 11:03:03 -0400962 FolderInfo folderInfo = null;
963 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700964 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
965 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400966 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700967 }
968
Joe Onorato9c1289c2009-08-17 11:03:03 -0400969 folderInfo.title = c.getString(titleIndex);
970 folderInfo.id = id;
971 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700972 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700973 folderInfo.cellX = c.getInt(cellXIndex);
974 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975
976 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700977 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978 } finally {
979 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700980 }
981
982 return null;
983 }
984
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 /**
986 * Add an item to the database in a specified container. Sets the container, screen, cellX and
987 * cellY fields of the item. Also assigns an ID to the item.
988 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700989 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700990 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400991 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400992 item.cellX = cellX;
993 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700994 // We store hotseat items in canonical form which is this orientation invariant position
995 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700997 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700999 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001000 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001002
1003 final ContentValues values = new ContentValues();
1004 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001005 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006
Michael Jurka414300a2013-08-27 15:42:35 +02001007 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001008 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001009
Jason Monk8e19cf22014-03-20 15:06:57 -04001010 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001011 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001012 public void run() {
1013 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1014 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001015
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001016 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001017 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001018 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001019 sBgItemsIdMap.put(item.id, item);
1020 switch (item.itemType) {
1021 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1022 sBgFolders.put(item.id, (FolderInfo) item);
1023 // Fall through
1024 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1025 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1026 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1027 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1028 sBgWorkspaceItems.add(item);
1029 } else {
1030 if (!sBgFolders.containsKey(item.container)) {
1031 // Adding an item to a folder that doesn't exist.
1032 String msg = "adding item: " + item + " to a folder that " +
1033 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001034 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001035 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001036 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001037 break;
1038 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1039 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1040 break;
1041 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001042 }
1043 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001044 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001045 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001046 }
1047
Joe Onorato9c1289c2009-08-17 11:03:03 -04001048 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001049 * Creates a new unique child id, for a given cell span across all layouts.
1050 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001051 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001052 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001053 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001054 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001055 }
1056
Sunny Goyal34942622014-08-29 17:20:55 -07001057 private static ArrayList<ItemInfo> getItemsByPackageName(
1058 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001059 ItemInfoFilter filter = new ItemInfoFilter() {
1060 @Override
1061 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1062 return cn.getPackageName().equals(pn) && info.user.equals(user);
1063 }
1064 };
Sunny Goyal34942622014-08-29 17:20:55 -07001065 return filterItemInfos(sBgItemsIdMap.values(), filter);
1066 }
1067
1068 /**
1069 * Removes all the items from the database corresponding to the specified package.
1070 */
1071 static void deletePackageFromDatabase(Context context, final String pn,
1072 final UserHandleCompat user) {
1073 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001074 }
1075
1076 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001077 * Removes the specified item from the database
1078 * @param context
1079 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001080 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001081 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001082 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1083 items.add(item);
1084 deleteItemsFromDatabase(context, items);
1085 }
1086
1087 /**
1088 * Removes the specified items from the database
1089 * @param context
1090 * @param item
1091 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001092 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001093 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001094
Michael Jurka83df1882011-08-31 20:59:26 -07001095 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001096 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001097 for (ItemInfo item : items) {
1098 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1099 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001100
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001101 // Lock on mBgLock *after* the db operation
1102 synchronized (sBgLock) {
1103 switch (item.itemType) {
1104 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1105 sBgFolders.remove(item.id);
1106 for (ItemInfo info: sBgItemsIdMap.values()) {
1107 if (info.container == item.id) {
1108 // We are deleting a folder which still contains items that
1109 // think they are contained by that folder.
1110 String msg = "deleting a folder (" + item + ") which still " +
1111 "contains items (" + info + ")";
1112 Log.e(TAG, msg);
1113 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001114 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001115 sBgWorkspaceItems.remove(item);
1116 break;
1117 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1118 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1119 sBgWorkspaceItems.remove(item);
1120 break;
1121 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1122 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1123 break;
1124 }
1125 sBgItemsIdMap.remove(item.id);
1126 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001127 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001128 }
1129 }
Michael Jurka83df1882011-08-31 20:59:26 -07001130 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001131 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001132 }
1133
1134 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001135 * Update the order of the workspace screens in the database. The array list contains
1136 * a list of screen ids in the order that they should appear.
1137 */
Winson Chungc9168342013-06-26 14:54:55 -07001138 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001139 // Log to disk
1140 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1141 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1142
Winson Chung64359a52013-07-08 17:17:08 -07001143 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001144 final ContentResolver cr = context.getContentResolver();
1145 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1146
1147 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001148 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001149 while (iter.hasNext()) {
1150 long id = iter.next();
1151 if (id < 0) {
1152 iter.remove();
1153 }
1154 }
1155
1156 Runnable r = new Runnable() {
1157 @Override
1158 public void run() {
Yura085c8532014-02-11 15:15:29 +00001159 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001161 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001162 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 for (int i = 0; i < count; i++) {
1164 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001165 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1167 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001168 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 }
Yura085c8532014-02-11 15:15:29 +00001170
1171 try {
1172 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1173 } catch (Exception ex) {
1174 throw new RuntimeException(ex);
1175 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001176
Winson Chungba9c37f2013-08-30 14:11:37 -07001177 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001178 sBgWorkspaceScreens.clear();
1179 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001180 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001181 }
1182 };
1183 runOnWorkerThread(r);
1184 }
1185
1186 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001187 * Remove the contents of the specified folder from the database
1188 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001189 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001190 final ContentResolver cr = context.getContentResolver();
1191
Michael Jurkac9d95c52011-08-29 14:03:34 -07001192 Runnable r = new Runnable() {
1193 public void run() {
1194 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001195 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001196 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 sBgItemsIdMap.remove(info.id);
1198 sBgFolders.remove(info.id);
1199 sBgDbIconCache.remove(info);
1200 sBgWorkspaceItems.remove(info);
1201 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001202
Michael Jurkac9d95c52011-08-29 14:03:34 -07001203 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1204 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001206 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001207 for (ItemInfo childInfo : info.contents) {
1208 sBgItemsIdMap.remove(childInfo.id);
1209 sBgDbIconCache.remove(childInfo);
1210 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001211 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001212 }
1213 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001215 }
1216
1217 /**
1218 * Set this as the current Launcher activity object for the loader.
1219 */
1220 public void initialize(Callbacks callbacks) {
1221 synchronized (mLock) {
1222 mCallbacks = new WeakReference<Callbacks>(callbacks);
1223 }
1224 }
1225
Kenny Guyed131872014-04-30 03:02:21 +01001226 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001227 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001228 int op = PackageUpdatedTask.OP_UPDATE;
1229 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1230 user));
1231 }
1232
1233 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001234 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001235 int op = PackageUpdatedTask.OP_REMOVE;
1236 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1237 user));
1238 }
1239
1240 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001241 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001242 int op = PackageUpdatedTask.OP_ADD;
1243 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1244 user));
1245 }
1246
1247 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001248 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001249 boolean replacing) {
1250 if (!replacing) {
1251 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1252 user));
1253 if (mAppsCanBeOnRemoveableStorage) {
1254 // Only rebind if we support removable storage. It catches the
1255 // case where
1256 // apps on the external sd card need to be reloaded
1257 startLoaderFromBackground();
1258 }
1259 } else {
1260 // If we are replacing then just update the packages in the list
1261 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1262 packageNames, user));
1263 }
1264 }
1265
1266 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001267 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001268 boolean replacing) {
1269 if (!replacing) {
1270 enqueuePackageUpdated(new PackageUpdatedTask(
1271 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1272 user));
1273 }
Kenny Guyed131872014-04-30 03:02:21 +01001274 }
1275
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001276 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001277 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1278 * ACTION_PACKAGE_CHANGED.
1279 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001280 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001281 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001282 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001283
Joe Onorato36115782010-06-17 13:28:48 -04001284 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001285 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001286 // If we have changed locale we need to clear out the labels in all apps/workspace.
1287 forceReload();
1288 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1289 // Check if configuration change was an mcc/mnc change which would affect app resources
1290 // and we would need to clear out the labels in all apps/workspace. Same handling as
1291 // above for ACTION_LOCALE_CHANGED
1292 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001293 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001294 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001295 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001296 forceReload();
1297 }
1298 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001299 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001300 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1301 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001302 Callbacks callbacks = getCallback();
1303 if (callbacks != null) {
1304 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001305 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001306 }
1307 }
1308
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001309 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001310 resetLoadedState(true, true);
1311
Reena Lee93f824a2011-09-23 17:20:28 -07001312 // Do this here because if the launcher activity is running it will be restarted.
1313 // If it's not running startLoaderFromBackground will merely tell it that it needs
1314 // to reload.
1315 startLoaderFromBackground();
1316 }
1317
Winson Chungf0c6ae02012-03-21 16:10:31 -07001318 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1319 synchronized (mLock) {
1320 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1321 // mWorkspaceLoaded to true later
1322 stopLoaderLocked();
1323 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1324 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1325 }
1326 }
1327
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001328 /**
1329 * When the launcher is in the background, it's possible for it to miss paired
1330 * configuration changes. So whenever we trigger the loader from the background
1331 * tell the launcher that it needs to re-run the loader when it comes back instead
1332 * of doing it now.
1333 */
1334 public void startLoaderFromBackground() {
1335 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001336 Callbacks callbacks = getCallback();
1337 if (callbacks != null) {
1338 // Only actually run the loader if they're not paused.
1339 if (!callbacks.setLoadOnResume()) {
1340 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001341 }
1342 }
1343 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001344 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001345 }
Joe Onorato36115782010-06-17 13:28:48 -04001346 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001347
Reena Lee93f824a2011-09-23 17:20:28 -07001348 // If there is already a loader task running, tell it to stop.
1349 // returns true if isLaunching() was true on the old task
1350 private boolean stopLoaderLocked() {
1351 boolean isLaunching = false;
1352 LoaderTask oldTask = mLoaderTask;
1353 if (oldTask != null) {
1354 if (oldTask.isLaunching()) {
1355 isLaunching = true;
1356 }
1357 oldTask.stopLocked();
1358 }
1359 return isLaunching;
1360 }
1361
Adam Cohen1a85c582014-09-30 09:48:49 -07001362 public boolean isCurrentCallbacks(Callbacks callbacks) {
1363 return (mCallbacks != null && mCallbacks.get() == callbacks);
1364 }
1365
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001366 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001367 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1368 }
1369
1370 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001371 synchronized (mLock) {
1372 if (DEBUG_LOADERS) {
1373 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1374 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001375
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001376 // Clear any deferred bind-runnables from the synchronized load process
1377 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001378 synchronized (mDeferredBindRunnables) {
1379 mDeferredBindRunnables.clear();
1380 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381
Joe Onorato36115782010-06-17 13:28:48 -04001382 // Don't bother to start the thread if we know it's not going to do anything
1383 if (mCallbacks != null && mCallbacks.get() != null) {
1384 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001385 // also, don't downgrade isLaunching if we're already running
1386 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001387 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001388 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1389 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1391 } else {
1392 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1393 sWorker.post(mLoaderTask);
1394 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001395 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001396 }
1397 }
1398
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001399 void bindRemainingSynchronousPages() {
1400 // Post the remaining side pages to be loaded
1401 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001402 Runnable[] deferredBindRunnables = null;
1403 synchronized (mDeferredBindRunnables) {
1404 deferredBindRunnables = mDeferredBindRunnables.toArray(
1405 new Runnable[mDeferredBindRunnables.size()]);
1406 mDeferredBindRunnables.clear();
1407 }
1408 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001409 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001410 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 }
1412 }
1413
Joe Onorato36115782010-06-17 13:28:48 -04001414 public void stopLoader() {
1415 synchronized (mLock) {
1416 if (mLoaderTask != null) {
1417 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001418 }
1419 }
Joe Onorato36115782010-06-17 13:28:48 -04001420 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001421
Winson Chung76828c82013-08-19 15:43:29 -07001422 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1423 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1424 final ContentResolver contentResolver = context.getContentResolver();
1425 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1426 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1427 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1428
1429 try {
1430 final int idIndex = sc.getColumnIndexOrThrow(
1431 LauncherSettings.WorkspaceScreens._ID);
1432 final int rankIndex = sc.getColumnIndexOrThrow(
1433 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1434 while (sc.moveToNext()) {
1435 try {
1436 long screenId = sc.getLong(idIndex);
1437 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001438 orderedScreens.put(rank, screenId);
1439 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001440 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001441 }
1442 }
1443 } finally {
1444 sc.close();
1445 }
Winson Chunga90303b2013-11-15 13:05:06 -08001446
1447 // Log to disk
1448 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1449 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1450 for (Integer i : orderedScreens.keySet()) {
1451 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1452 }
1453 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1454 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001455 return orderedScreens;
1456 }
1457
Michael Jurkac57b7a82011-08-09 22:02:20 -07001458 public boolean isAllAppsLoaded() {
1459 return mAllAppsLoaded;
1460 }
1461
Winson Chung36a62fe2012-05-06 18:04:42 -07001462 boolean isLoadingWorkspace() {
1463 synchronized (mLock) {
1464 if (mLoaderTask != null) {
1465 return mLoaderTask.isLoadingWorkspace();
1466 }
1467 }
1468 return false;
1469 }
1470
Joe Onorato36115782010-06-17 13:28:48 -04001471 /**
1472 * Runnable for the thread that loads the contents of the launcher:
1473 * - workspace icons
1474 * - widgets
1475 * - all apps icons
1476 */
1477 private class LoaderTask implements Runnable {
1478 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001479 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001480 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001481 private boolean mStopped;
1482 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001483 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001484
Winson Chungc3eecff2011-07-11 17:44:15 -07001485 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001486
Dan Sandlerd5024042014-01-09 15:01:33 -05001487 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001488 mContext = context;
1489 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001490 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001491 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001492 }
1493
Joe Onorato36115782010-06-17 13:28:48 -04001494 boolean isLaunching() {
1495 return mIsLaunching;
1496 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001497
Winson Chung36a62fe2012-05-06 18:04:42 -07001498 boolean isLoadingWorkspace() {
1499 return mIsLoadingAndBindingWorkspace;
1500 }
1501
Winson Chungc763c4e2013-07-19 13:49:06 -07001502 /** Returns whether this is an upgrade path */
1503 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001504 mIsLoadingAndBindingWorkspace = true;
1505
Joe Onorato36115782010-06-17 13:28:48 -04001506 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001507 if (DEBUG_LOADERS) {
1508 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001509 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001510
Winson Chungc763c4e2013-07-19 13:49:06 -07001511 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001512 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001513 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001514 synchronized (LoaderTask.this) {
1515 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001516 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001517 }
1518 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001519 }
1520 }
1521
Joe Onorato36115782010-06-17 13:28:48 -04001522 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001523 bindWorkspace(-1, isUpgradePath);
1524 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001525 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001526
Joe Onorato36115782010-06-17 13:28:48 -04001527 private void waitForIdle() {
1528 // Wait until the either we're stopped or the other threads are done.
1529 // This way we don't start loading all apps until the workspace has settled
1530 // down.
1531 synchronized (LoaderTask.this) {
1532 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001533
Joe Onorato36115782010-06-17 13:28:48 -04001534 mHandler.postIdle(new Runnable() {
1535 public void run() {
1536 synchronized (LoaderTask.this) {
1537 mLoadAndBindStepFinished = true;
1538 if (DEBUG_LOADERS) {
1539 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001540 }
Joe Onorato36115782010-06-17 13:28:48 -04001541 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001542 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001543 }
Joe Onorato36115782010-06-17 13:28:48 -04001544 });
1545
Michael Jurkac7700af2013-05-14 20:17:58 +02001546 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001547 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001548 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1549 // wait no longer than 1sec at a time
1550 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001551 } catch (InterruptedException ex) {
1552 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001553 }
1554 }
Joe Onorato36115782010-06-17 13:28:48 -04001555 if (DEBUG_LOADERS) {
1556 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001557 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001558 + "ms for previous step to finish binding");
1559 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001560 }
Joe Onorato36115782010-06-17 13:28:48 -04001561 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001562
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001563 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001564 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001565 // Ensure that we have a valid page index to load synchronously
1566 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1567 "valid page index");
1568 }
1569 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1570 // Ensure that we don't try and bind a specified page when the pages have not been
1571 // loaded already (we should load everything asynchronously in that case)
1572 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1573 }
1574 synchronized (mLock) {
1575 if (mIsLoaderTaskRunning) {
1576 // Ensure that we are never running the background loading at this point since
1577 // we also touch the background collections
1578 throw new RuntimeException("Error! Background loading is already running");
1579 }
1580 }
1581
1582 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1583 // data structures, we can't allow any other thread to touch that data, but because
1584 // this call is synchronous, we can get away with not locking).
1585
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001586 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001587 // operations from the previous activity. We need to ensure that all queued operations
1588 // are executed before any synchronous binding work is done.
1589 mHandler.flush();
1590
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001591 // Divide the set of loaded items into those that we are binding synchronously, and
1592 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001593 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001594 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1595 // arise from that.
1596 onlyBindAllApps();
1597 }
1598
Joe Onorato36115782010-06-17 13:28:48 -04001599 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001600 boolean isUpgrade = false;
1601
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001602 synchronized (mLock) {
1603 mIsLoaderTaskRunning = true;
1604 }
Joe Onorato36115782010-06-17 13:28:48 -04001605 // Optimize for end-user experience: if the Launcher is up and // running with the
1606 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1607 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001608 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001609 // Elevate priority when Home launches for the first time to avoid
1610 // starving at boot time. Staring at a blank home is not cool.
1611 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001612 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1613 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001614 android.os.Process.setThreadPriority(mIsLaunching
1615 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1616 }
Winson Chung64359a52013-07-08 17:17:08 -07001617 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001618 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001619
Joe Onorato36115782010-06-17 13:28:48 -04001620 if (mStopped) {
1621 break keep_running;
1622 }
1623
1624 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1625 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001626 synchronized (mLock) {
1627 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001628 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001629 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1630 }
1631 }
Joe Onorato36115782010-06-17 13:28:48 -04001632 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001633
1634 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001635 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1636 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001637
1638 // Restore the default thread priority after we are done loading items
1639 synchronized (mLock) {
1640 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1641 }
Joe Onorato36115782010-06-17 13:28:48 -04001642 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001643
Winson Chungaac01e12011-08-17 10:37:13 -07001644 // Update the saved icons if necessary
1645 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001646 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001647 for (Object key : sBgDbIconCache.keySet()) {
1648 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1649 }
1650 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001651 }
Winson Chungaac01e12011-08-17 10:37:13 -07001652
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001653 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001654 // Ensure that all the applications that are in the system are
1655 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001656 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001657 verifyApplications();
1658 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001659 }
1660
Joe Onorato36115782010-06-17 13:28:48 -04001661 // Clear out this reference, otherwise we end up holding it until all of the
1662 // callback runnables are done.
1663 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001664
Joe Onorato36115782010-06-17 13:28:48 -04001665 synchronized (mLock) {
1666 // If we are still the last one to be scheduled, remove ourselves.
1667 if (mLoaderTask == this) {
1668 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001669 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001670 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001671 }
Joe Onorato36115782010-06-17 13:28:48 -04001672 }
1673
1674 public void stopLocked() {
1675 synchronized (LoaderTask.this) {
1676 mStopped = true;
1677 this.notify();
1678 }
1679 }
1680
1681 /**
1682 * Gets the callbacks object. If we've been stopped, or if the launcher object
1683 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1684 * object that was around when the deferred message was scheduled, and if there's
1685 * a new Callbacks object around then also return null. This will save us from
1686 * calling onto it with data that will be ignored.
1687 */
1688 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1689 synchronized (mLock) {
1690 if (mStopped) {
1691 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001692 }
Joe Onorato36115782010-06-17 13:28:48 -04001693
1694 if (mCallbacks == null) {
1695 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001696 }
Joe Onorato36115782010-06-17 13:28:48 -04001697
1698 final Callbacks callbacks = mCallbacks.get();
1699 if (callbacks != oldCallbacks) {
1700 return null;
1701 }
1702 if (callbacks == null) {
1703 Log.w(TAG, "no mCallbacks");
1704 return null;
1705 }
1706
1707 return callbacks;
1708 }
1709 }
1710
Winson Chungc763c4e2013-07-19 13:49:06 -07001711 private void verifyApplications() {
1712 final Context context = mApp.getContext();
1713
1714 // Cross reference all the applications in our apps list with items in the workspace
1715 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001716 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001717 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001718 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001719 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001720 if (tmpInfos.isEmpty()) {
1721 // We are missing an application icon, so add this to the workspace
1722 added.add(app);
1723 // This is a rare event, so lets log it
1724 Log.e(TAG, "Missing Application on load: " + app);
1725 }
1726 }
1727 }
1728 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001729 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001730 }
1731 }
1732
Joe Onorato36115782010-06-17 13:28:48 -04001733 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001734 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001735 LauncherAppState app = LauncherAppState.getInstance();
1736 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001737 final int countX = (int) grid.numColumns;
1738 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001739
Adam Cohendcd297f2013-06-18 13:13:40 -07001740 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001741 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001742 // Return early if we detect that an item is under the hotseat button
1743 if (mCallbacks == null ||
1744 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001745 Log.e(TAG, "Error loading shortcut into hotseat " + item
1746 + " into position (" + item.screenId + ":" + item.cellX + ","
1747 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001748 return false;
1749 }
1750
Dan Sandler295ae182013-12-10 16:05:47 -05001751 final ItemInfo[][] hotseatItems =
1752 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1753
Adam Cohenae4409d2013-11-26 10:34:59 -08001754 if (item.screenId >= grid.numHotseatIcons) {
1755 Log.e(TAG, "Error loading shortcut " + item
1756 + " into hotseat position " + item.screenId
1757 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1758 + ")");
1759 return false;
1760 }
1761
Dan Sandler295ae182013-12-10 16:05:47 -05001762 if (hotseatItems != null) {
1763 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001764 Log.e(TAG, "Error loading shortcut into hotseat " + item
1765 + " into position (" + item.screenId + ":" + item.cellX + ","
1766 + item.cellY + ") occupied by "
1767 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1768 [(int) item.screenId][0]);
1769 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001770 } else {
1771 hotseatItems[(int) item.screenId][0] = item;
1772 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001773 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001774 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001775 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001776 items[(int) item.screenId][0] = item;
1777 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001778 return true;
1779 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001780 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1781 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001782 return true;
1783 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001784
Adam Cohendcd297f2013-06-18 13:13:40 -07001785 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001786 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001787 occupied.put(item.screenId, items);
1788 }
1789
Dan Sandler295ae182013-12-10 16:05:47 -05001790 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001791 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1792 item.cellX < 0 || item.cellY < 0 ||
1793 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1794 Log.e(TAG, "Error loading shortcut " + item
1795 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1796 + item.cellX + "," + item.cellY
1797 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1798 return false;
1799 }
1800
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001801 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001802 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1803 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001804 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001805 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001806 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001807 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001808 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001810 return false;
1811 }
1812 }
1813 }
1814 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1815 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001816 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001817 }
1818 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001819
Joe Onorato36115782010-06-17 13:28:48 -04001820 return true;
1821 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001822
Winson Chungba9c37f2013-08-30 14:11:37 -07001823 /** Clears all the sBg data structures */
1824 private void clearSBgDataStructures() {
1825 synchronized (sBgLock) {
1826 sBgWorkspaceItems.clear();
1827 sBgAppWidgets.clear();
1828 sBgFolders.clear();
1829 sBgItemsIdMap.clear();
1830 sBgDbIconCache.clear();
1831 sBgWorkspaceScreens.clear();
1832 }
1833 }
1834
Dan Sandlerd5024042014-01-09 15:01:33 -05001835 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001836 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001837 // Log to disk
1838 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1839
Joe Onorato36115782010-06-17 13:28:48 -04001840 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001841
Joe Onorato36115782010-06-17 13:28:48 -04001842 final Context context = mContext;
1843 final ContentResolver contentResolver = context.getContentResolver();
1844 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001845 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001846 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1847 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001848 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001849
Winson Chung892c74d2013-08-22 16:15:50 -07001850 LauncherAppState app = LauncherAppState.getInstance();
1851 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1852 int countX = (int) grid.numColumns;
1853 int countY = (int) grid.numRows;
1854
Dan Sandlerd5024042014-01-09 15:01:33 -05001855 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1856 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1857 LauncherAppState.getLauncherProvider().deleteDatabase();
1858 }
1859
1860 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1861 // append the user's Launcher2 shortcuts
1862 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1863 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1864 } else {
1865 // Make sure the default workspace is loaded
1866 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001867 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001868 }
Adam Cohene25af792013-06-06 23:08:25 -07001869
Adam Cohen71483f42014-05-15 14:04:01 -07001870 // This code path is for our old migration code and should no longer be exercised
1871 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001872
Winson Chung9f9f00b2013-11-15 13:27:00 -08001873 // Log to disk
1874 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001875
Winson Chung2abf94d2012-07-18 18:16:38 -07001876 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001877 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001878 final HashSet<String> installingPkgs = PackageInstallerCompat
1879 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001880
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001882 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001883 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001884 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001885 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001886
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 // +1 for the hotseat (it can be larger than the workspace)
1888 // Load workspace in reverse order to ensure that latest items are loaded first (and
1889 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001890 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001891
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001892 try {
1893 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1894 final int intentIndex = c.getColumnIndexOrThrow
1895 (LauncherSettings.Favorites.INTENT);
1896 final int titleIndex = c.getColumnIndexOrThrow
1897 (LauncherSettings.Favorites.TITLE);
1898 final int iconTypeIndex = c.getColumnIndexOrThrow(
1899 LauncherSettings.Favorites.ICON_TYPE);
1900 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1901 final int iconPackageIndex = c.getColumnIndexOrThrow(
1902 LauncherSettings.Favorites.ICON_PACKAGE);
1903 final int iconResourceIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.ICON_RESOURCE);
1905 final int containerIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.CONTAINER);
1907 final int itemTypeIndex = c.getColumnIndexOrThrow(
1908 LauncherSettings.Favorites.ITEM_TYPE);
1909 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1910 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001911 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1912 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001913 final int screenIndex = c.getColumnIndexOrThrow(
1914 LauncherSettings.Favorites.SCREEN);
1915 final int cellXIndex = c.getColumnIndexOrThrow
1916 (LauncherSettings.Favorites.CELLX);
1917 final int cellYIndex = c.getColumnIndexOrThrow
1918 (LauncherSettings.Favorites.CELLY);
1919 final int spanXIndex = c.getColumnIndexOrThrow
1920 (LauncherSettings.Favorites.SPANX);
1921 final int spanYIndex = c.getColumnIndexOrThrow(
1922 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001923 final int rankIndex = c.getColumnIndexOrThrow(
1924 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001925 final int restoredIndex = c.getColumnIndexOrThrow(
1926 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001927 final int profileIdIndex = c.getColumnIndexOrThrow(
1928 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001929 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1930 //final int displayModeIndex = c.getColumnIndexOrThrow(
1931 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001932
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001933 ShortcutInfo info;
1934 String intentDescription;
1935 LauncherAppWidgetInfo appWidgetInfo;
1936 int container;
1937 long id;
1938 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001939 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001940
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 while (!mStopped && c.moveToNext()) {
1942 try {
1943 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001944 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001945 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001946
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001947 switch (itemType) {
1948 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1949 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001950 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001951 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001952 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001953 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001954 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001955 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001956 if (user == null) {
1957 // User has been deleted remove the item.
1958 itemsToRemove.add(id);
1959 continue;
1960 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001961 try {
1962 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001963 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001964 if (cn != null && cn.getPackageName() != null) {
1965 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1966 cn.getPackageName(), user);
1967 boolean validComponent = validPkg &&
1968 launcherApps.isActivityEnabledForProfile(cn, user);
1969
1970 if (validComponent) {
1971 if (restored) {
1972 // no special handling necessary for this item
1973 restoredRows.add(id);
1974 restored = false;
1975 }
1976 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001977 intent = null;
1978 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1979 // We allow auto install apps to have their intent
1980 // updated after an install.
1981 intent = manager.getLaunchIntentForPackage(
1982 cn.getPackageName());
1983 if (intent != null) {
1984 ContentValues values = new ContentValues();
1985 values.put(LauncherSettings.Favorites.INTENT,
1986 intent.toUri(0));
1987 String where = BaseColumns._ID + "= ?";
1988 String[] args = {Long.toString(id)};
1989 contentResolver.update(contentUri, values, where, args);
1990 }
1991 }
1992
1993 if (intent == null) {
1994 // The app is installed but the component is no
1995 // longer available.
1996 Launcher.addDumpLog(TAG,
1997 "Invalid component removed: " + cn, true);
1998 itemsToRemove.add(id);
1999 continue;
2000 } else {
2001 // no special handling necessary for this item
2002 restoredRows.add(id);
2003 restored = false;
2004 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002005 } else if (restored) {
2006 // Package is not yet available but might be
2007 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002008 Launcher.addDumpLog(TAG,
2009 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002010
2011 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2012 // Restore has started once.
2013 } else if (installingPkgs.contains(cn.getPackageName())) {
2014 // App restore has started. Update the flag
2015 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2016 ContentValues values = new ContentValues();
2017 values.put(LauncherSettings.Favorites.RESTORED,
2018 promiseType);
2019 String where = BaseColumns._ID + "= ?";
2020 String[] args = {Long.toString(id)};
2021 contentResolver.update(contentUri, values, where, args);
2022
2023 } else if (REMOVE_UNRESTORED_ICONS) {
2024 Launcher.addDumpLog(TAG,
2025 "Unrestored package removed: " + cn, true);
2026 itemsToRemove.add(id);
2027 continue;
2028 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002029 } else if (launcherApps.isAppEnabled(
2030 manager, cn.getPackageName(),
2031 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2032 // Package is present but not available.
2033 allowMissingTarget = true;
2034 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2035 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002036 // SdCard is not ready yet. Package might get available,
2037 // once it is ready.
2038 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2039 + " (check again later)", true);
2040 HashSet<String> pkgs = sPendingPackages.get(user);
2041 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002042 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002043 sPendingPackages.put(user, pkgs);
2044 }
2045 pkgs.add(cn.getPackageName());
2046 allowMissingTarget = true;
2047 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002048
2049 } else {
2050 // Do not wait for external media load anymore.
2051 // Log the invalid package, and remove it
2052 Launcher.addDumpLog(TAG,
2053 "Invalid package removed: " + cn, true);
2054 itemsToRemove.add(id);
2055 continue;
Winson Chungee055712013-07-30 14:46:24 -07002056 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002057 } else if (cn == null) {
2058 // For shortcuts with no component, keep them as they are
2059 restoredRows.add(id);
2060 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002061 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002062 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002063 Launcher.addDumpLog(TAG,
2064 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 continue;
2066 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002067
Chris Wrenf4d08112014-01-16 18:13:56 -05002068 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002069 if (user.equals(UserHandleCompat.myUserHandle())) {
2070 Launcher.addDumpLog(TAG,
2071 "constructing info for partially restored package",
2072 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002073 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002074 intent = getRestoredItemIntent(c, context, intent);
2075 } else {
2076 // Don't restore items for other profiles.
2077 itemsToRemove.add(id);
2078 continue;
2079 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002080 } else if (itemType ==
2081 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002082 info = getShortcutInfo(manager, intent, user, context, c,
2083 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 } else {
2085 info = getShortcutInfo(c, context, iconTypeIndex,
2086 iconPackageIndex, iconResourceIndex, iconIndex,
2087 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002088
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 // App shortcuts that used to be automatically added to Launcher
2090 // didn't always have the correct intent flags set, so do that
2091 // here
2092 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002093 intent.getCategories() != null &&
2094 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002095 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002096 intent.addFlags(
2097 Intent.FLAG_ACTIVITY_NEW_TASK |
2098 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2099 }
Michael Jurka96879562012-03-22 05:54:33 -07002100 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002101
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002102 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002103 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002104 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 container = c.getInt(containerIndex);
2106 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002107 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002108 info.cellX = c.getInt(cellXIndex);
2109 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002110 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002111 info.spanX = 1;
2112 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002113 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002114 info.isDisabled = disabledState;
2115 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2116 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2117 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002118
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002119 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002120 if (!checkItemPlacement(occupied, info)) {
2121 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 break;
2123 }
2124
2125 switch (container) {
2126 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2127 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2128 sBgWorkspaceItems.add(info);
2129 break;
2130 default:
2131 // Item is in a user folder
2132 FolderInfo folderInfo =
2133 findOrMakeFolder(sBgFolders, container);
2134 folderInfo.add(info);
2135 break;
2136 }
2137 sBgItemsIdMap.put(info.id, info);
2138
2139 // now that we've loaded everthing re-save it with the
2140 // icon in case it disappears somehow.
2141 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002142 } else {
2143 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 }
2145 break;
2146
2147 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2148 id = c.getLong(idIndex);
2149 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2150
2151 folderInfo.title = c.getString(titleIndex);
2152 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002153 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002155 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002156 folderInfo.cellX = c.getInt(cellXIndex);
2157 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002158 folderInfo.spanX = 1;
2159 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002160
Daniel Sandler8802e962010-05-26 16:28:16 -04002161 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002162 if (!checkItemPlacement(occupied, folderInfo)) {
2163 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002164 break;
2165 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002166
Joe Onorato9c1289c2009-08-17 11:03:03 -04002167 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002168 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2169 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2170 sBgWorkspaceItems.add(folderInfo);
2171 break;
Joe Onorato36115782010-06-17 13:28:48 -04002172 }
Joe Onorato17a89222011-02-08 17:26:11 -08002173
Chris Wrenf4d08112014-01-16 18:13:56 -05002174 if (restored) {
2175 // no special handling required for restored folders
2176 restoredRows.add(id);
2177 }
2178
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2180 sBgFolders.put(folderInfo.id, folderInfo);
2181 break;
2182
2183 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002184 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002185 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002186 boolean customWidget = itemType ==
2187 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2188
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002189 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002190 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002191 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002192 final ComponentName component =
2193 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002194
Sunny Goyal651077b2014-06-30 14:15:31 -07002195 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002196 final boolean isIdValid = (restoreStatus &
2197 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002198
Sunny Goyalff572272014-07-23 13:58:07 -07002199 final boolean wasProviderReady = (restoreStatus &
2200 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002201
Adam Cohen59400422014-03-05 18:07:04 -08002202 final LauncherAppWidgetProviderInfo provider =
2203 LauncherModel.getProviderInfo(context,
2204 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002205
2206 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002207 if (!isSafeMode && !customWidget &&
2208 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002209 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002210 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002211
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002212 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002213 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002214 itemsToRemove.add(id);
2215 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002216 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002217 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2218 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002219
2220 if (!customWidget) {
2221 int[] minSpan =
2222 Launcher.getMinSpanForWidget(context, provider);
2223 appWidgetInfo.minSpanX = minSpan[0];
2224 appWidgetInfo.minSpanY = minSpan[1];
2225 }
Sunny Goyalff572272014-07-23 13:58:07 -07002226
2227 int status = restoreStatus;
2228 if (!wasProviderReady) {
2229 // If provider was not previously ready, update the
2230 // status and UI flag.
2231
2232 // Id would be valid only if the widget restore broadcast was received.
2233 if (isIdValid) {
2234 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2235 } else {
2236 status &= ~LauncherAppWidgetInfo
2237 .FLAG_PROVIDER_NOT_READY;
2238 }
2239 }
2240 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002241 } else {
2242 Log.v(TAG, "Widget restore pending id=" + id
2243 + " appWidgetId=" + appWidgetId
2244 + " status =" + restoreStatus);
2245 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002246 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002247 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002248
2249 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2250 // Restore has started once.
2251 } else if (installingPkgs.contains(component.getPackageName())) {
2252 // App restore has started. Update the flag
2253 appWidgetInfo.restoreStatus |=
2254 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002255 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002256 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002257 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002258 itemsToRemove.add(id);
2259 continue;
2260 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002261 }
Sunny Goyalff572272014-07-23 13:58:07 -07002262
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002264 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002265 appWidgetInfo.cellX = c.getInt(cellXIndex);
2266 appWidgetInfo.cellY = c.getInt(cellYIndex);
2267 appWidgetInfo.spanX = c.getInt(spanXIndex);
2268 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002269
Adam Cohen59400422014-03-05 18:07:04 -08002270 if (!customWidget) {
2271 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2272 appWidgetInfo.minSpanX = minSpan[0];
2273 appWidgetInfo.minSpanY = minSpan[1];
2274 }
2275
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 container = c.getInt(containerIndex);
2277 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2278 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2279 Log.e(TAG, "Widget found where container != " +
2280 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2281 continue;
2282 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002283
Adam Cohene25af792013-06-06 23:08:25 -07002284 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002286 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2287 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 break;
2289 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002290
Adam Cohen59400422014-03-05 18:07:04 -08002291 if (!customWidget) {
2292 String providerName =
2293 appWidgetInfo.providerName.flattenToString();
2294 if (!providerName.equals(savedProvider) ||
2295 (appWidgetInfo.restoreStatus != restoreStatus)) {
2296 ContentValues values = new ContentValues();
2297 values.put(
2298 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2299 providerName);
2300 values.put(LauncherSettings.Favorites.RESTORED,
2301 appWidgetInfo.restoreStatus);
2302 String where = BaseColumns._ID + "= ?";
2303 String[] args = {Long.toString(id)};
2304 contentResolver.update(contentUri, values, where, args);
2305 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002306 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002307 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2308 sBgAppWidgets.add(appWidgetInfo);
2309 }
Joe Onorato36115782010-06-17 13:28:48 -04002310 break;
2311 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002313 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002314 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002315 }
2316 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002317 if (c != null) {
2318 c.close();
2319 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002320 }
2321
Winson Chungba9c37f2013-08-30 14:11:37 -07002322 // Break early if we've stopped loading
2323 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002324 clearSBgDataStructures();
2325 return false;
2326 }
2327
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002328 if (itemsToRemove.size() > 0) {
2329 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002330 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002331 // Remove dead items
2332 for (long id : itemsToRemove) {
2333 if (DEBUG_LOADERS) {
2334 Log.d(TAG, "Removed id = " + id);
2335 }
2336 // Don't notify content observers
2337 try {
2338 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2339 null, null);
2340 } catch (RemoteException e) {
2341 Log.w(TAG, "Could not remove id = " + id);
2342 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002343 }
2344 }
2345
Chris Wrenf4d08112014-01-16 18:13:56 -05002346 if (restoredRows.size() > 0) {
2347 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002348 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002349 // Update restored items that no longer require special handling
2350 try {
2351 StringBuilder selectionBuilder = new StringBuilder();
2352 selectionBuilder.append(LauncherSettings.Favorites._ID);
2353 selectionBuilder.append(" IN (");
2354 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2355 selectionBuilder.append(")");
2356 ContentValues values = new ContentValues();
2357 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002358 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002359 values, selectionBuilder.toString(), null);
2360 } catch (RemoteException e) {
2361 Log.w(TAG, "Could not update restored rows");
2362 }
2363 }
2364
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002365 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2366 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002367 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002368 null, sWorker);
2369 }
2370
Winson Chungc763c4e2013-07-19 13:49:06 -07002371 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002372 long maxScreenId = 0;
2373 // If we're importing we use the old screen order.
2374 for (ItemInfo item: sBgItemsIdMap.values()) {
2375 long screenId = item.screenId;
2376 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2377 !sBgWorkspaceScreens.contains(screenId)) {
2378 sBgWorkspaceScreens.add(screenId);
2379 if (screenId > maxScreenId) {
2380 maxScreenId = screenId;
2381 }
2382 }
2383 }
2384 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002385 // Log to disk
2386 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2387 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2388 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002389
Michael Jurka414300a2013-08-27 15:42:35 +02002390 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002391 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002392
2393 // Update the max item id after we load an old db
2394 long maxItemId = 0;
2395 // If we're importing we use the old screen order.
2396 for (ItemInfo item: sBgItemsIdMap.values()) {
2397 maxItemId = Math.max(maxItemId, item.id);
2398 }
Michael Jurka414300a2013-08-27 15:42:35 +02002399 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002400 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002401 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2402 for (Integer i : orderedScreens.keySet()) {
2403 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002404 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002405 // Log to disk
2406 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2407 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002408
2409 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002410 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002411 for (ItemInfo item: sBgItemsIdMap.values()) {
2412 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002413 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2414 unusedScreens.contains(screenId)) {
2415 unusedScreens.remove(screenId);
2416 }
2417 }
2418
2419 // If there are any empty screens remove them, and update.
2420 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002421 // Log to disk
2422 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2423 TextUtils.join(", ", unusedScreens), true);
2424
Winson Chung933bae62013-08-29 11:42:30 -07002425 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002426 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2427 }
2428 }
2429
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002430 if (DEBUG_LOADERS) {
2431 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2432 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002433 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002434 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002436
Daniel Sandler566da102013-06-25 23:43:45 -04002437 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002438 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002439 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002440 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002441 line += " | ";
2442 }
Winson Chung892c74d2013-08-22 16:15:50 -07002443 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002444 ItemInfo[][] screen = occupied.get(screenId);
2445 if (x < screen.length && y < screen[x].length) {
2446 line += (screen[x][y] != null) ? "#" : ".";
2447 } else {
2448 line += "!";
2449 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002450 }
Joe Onorato36115782010-06-17 13:28:48 -04002451 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002453 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002454 }
Joe Onorato36115782010-06-17 13:28:48 -04002455 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002456 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002457 }
2458
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 /** Filters the set of items who are directly or indirectly (via another container) on the
2460 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002461 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002462 ArrayList<ItemInfo> allWorkspaceItems,
2463 ArrayList<ItemInfo> currentScreenItems,
2464 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002465 // Purge any null ItemInfos
2466 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2467 while (iter.hasNext()) {
2468 ItemInfo i = iter.next();
2469 if (i == null) {
2470 iter.remove();
2471 }
2472 }
2473
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474 // Order the set of items by their containers first, this allows use to walk through the
2475 // list sequentially, build up a list of containers that are in the specified screen,
2476 // as well as all items in those containers.
2477 Set<Long> itemsOnScreen = new HashSet<Long>();
2478 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2479 @Override
2480 public int compare(ItemInfo lhs, ItemInfo rhs) {
2481 return (int) (lhs.container - rhs.container);
2482 }
2483 });
2484 for (ItemInfo info : allWorkspaceItems) {
2485 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002486 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002487 currentScreenItems.add(info);
2488 itemsOnScreen.add(info.id);
2489 } else {
2490 otherScreenItems.add(info);
2491 }
2492 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2493 currentScreenItems.add(info);
2494 itemsOnScreen.add(info.id);
2495 } else {
2496 if (itemsOnScreen.contains(info.container)) {
2497 currentScreenItems.add(info);
2498 itemsOnScreen.add(info.id);
2499 } else {
2500 otherScreenItems.add(info);
2501 }
2502 }
2503 }
2504 }
2505
2506 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002507 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 ArrayList<LauncherAppWidgetInfo> appWidgets,
2509 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2510 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511
2512 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002513 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002514 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002515 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002516 currentScreenWidgets.add(widget);
2517 } else {
2518 otherScreenWidgets.add(widget);
2519 }
2520 }
2521 }
2522
2523 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002524 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002525 HashMap<Long, ItemInfo> itemsIdMap,
2526 HashMap<Long, FolderInfo> folders,
2527 HashMap<Long, FolderInfo> currentScreenFolders,
2528 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529
2530 for (long id : folders.keySet()) {
2531 ItemInfo info = itemsIdMap.get(id);
2532 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002533 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002535 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536 currentScreenFolders.put(id, folder);
2537 } else {
2538 otherScreenFolders.put(id, folder);
2539 }
2540 }
2541 }
2542
2543 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2544 * right) */
2545 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002546 final LauncherAppState app = LauncherAppState.getInstance();
2547 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002548 // XXX: review this
2549 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002550 @Override
2551 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002552 int cellCountX = (int) grid.numColumns;
2553 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002554 int screenOffset = cellCountX * cellCountY;
2555 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002556 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002557 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002558 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002559 rhs.cellY * cellCountX + rhs.cellX);
2560 return (int) (lr - rr);
2561 }
2562 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002563 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002564
Adam Cohendcd297f2013-06-18 13:13:40 -07002565 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2566 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002567 final Runnable r = new Runnable() {
2568 @Override
2569 public void run() {
2570 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2571 if (callbacks != null) {
2572 callbacks.bindScreens(orderedScreens);
2573 }
2574 }
2575 };
2576 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2577 }
2578
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002579 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2580 final ArrayList<ItemInfo> workspaceItems,
2581 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2582 final HashMap<Long, FolderInfo> folders,
2583 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002584
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002585 final boolean postOnMainThread = (deferredBindRunnables != null);
2586
2587 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002588 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002589 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002590 final int start = i;
2591 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002592 final Runnable r = new Runnable() {
2593 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002594 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002595 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002596 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002597 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2598 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002599 }
2600 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002601 };
2602 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002603 synchronized (deferredBindRunnables) {
2604 deferredBindRunnables.add(r);
2605 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002606 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002607 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002608 }
Joe Onorato36115782010-06-17 13:28:48 -04002609 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002610
2611 // Bind the folders
2612 if (!folders.isEmpty()) {
2613 final Runnable r = new Runnable() {
2614 public void run() {
2615 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2616 if (callbacks != null) {
2617 callbacks.bindFolders(folders);
2618 }
2619 }
2620 };
2621 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002622 synchronized (deferredBindRunnables) {
2623 deferredBindRunnables.add(r);
2624 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002625 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002626 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 }
2628 }
2629
2630 // Bind the widgets, one at a time
2631 N = appWidgets.size();
2632 for (int i = 0; i < N; i++) {
2633 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2634 final Runnable r = new Runnable() {
2635 public void run() {
2636 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2637 if (callbacks != null) {
2638 callbacks.bindAppWidget(widget);
2639 }
2640 }
2641 };
2642 if (postOnMainThread) {
2643 deferredBindRunnables.add(r);
2644 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002645 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002646 }
2647 }
2648 }
2649
2650 /**
2651 * Binds all loaded data to actual views on the main thread.
2652 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002653 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002654 final long t = SystemClock.uptimeMillis();
2655 Runnable r;
2656
2657 // Don't use these two variables in any of the callback runnables.
2658 // Otherwise we hold a reference to them.
2659 final Callbacks oldCallbacks = mCallbacks.get();
2660 if (oldCallbacks == null) {
2661 // This launcher has exited and nobody bothered to tell us. Just bail.
2662 Log.w(TAG, "LoaderTask running with no launcher");
2663 return;
2664 }
2665
Winson Chung9b9fb962013-11-15 15:39:34 -08002666 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2668 ArrayList<LauncherAppWidgetInfo> appWidgets =
2669 new ArrayList<LauncherAppWidgetInfo>();
2670 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2671 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002672 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002673 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002674 workspaceItems.addAll(sBgWorkspaceItems);
2675 appWidgets.addAll(sBgAppWidgets);
2676 folders.putAll(sBgFolders);
2677 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002678 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002679 }
2680
Derek Prothro7aff3992013-12-10 14:00:37 -05002681 final boolean isLoadingSynchronously =
2682 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002683 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002684 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002685 if (currScreen >= orderedScreenIds.size()) {
2686 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002687 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002688 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002689 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002690 final long currentScreenId = currentScreen < 0
2691 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002692
2693 // Load all the items that are on the current page first (and in the process, unbind
2694 // all the existing workspace items before we call startBinding() below.
2695 unbindWorkspaceItemsOnMainThread();
2696
2697 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002698 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2699 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2700 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2701 new ArrayList<LauncherAppWidgetInfo>();
2702 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2703 new ArrayList<LauncherAppWidgetInfo>();
2704 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2705 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2706
Winson Chung9b9fb962013-11-15 15:39:34 -08002707 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002708 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002709 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002710 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002711 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002712 otherFolders);
2713 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2714 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2715
2716 // Tell the workspace that we're about to start binding items
2717 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002718 public void run() {
2719 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2720 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002721 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002722 }
2723 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002724 };
Winson Chung81b52252012-08-27 15:34:29 -07002725 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002726
Adam Cohendcd297f2013-06-18 13:13:40 -07002727 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2728
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002729 // Load items on the current page
2730 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2731 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002732 if (isLoadingSynchronously) {
2733 r = new Runnable() {
2734 public void run() {
2735 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002736 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002737 callbacks.onPageBoundSynchronously(currentScreen);
2738 }
2739 }
2740 };
Winson Chung81b52252012-08-27 15:34:29 -07002741 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002742 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002743
Winson Chung4a2afa32012-07-19 14:53:05 -07002744 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2745 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002746 synchronized (mDeferredBindRunnables) {
2747 mDeferredBindRunnables.clear();
2748 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002749 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002750 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002751
2752 // Tell the workspace that we're done binding items
2753 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002754 public void run() {
2755 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2756 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002757 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002758 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002759
Winson Chung98e030b2012-05-07 16:01:11 -07002760 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002761 if (DEBUG_LOADERS) {
2762 Log.d(TAG, "bound workspace in "
2763 + (SystemClock.uptimeMillis()-t) + "ms");
2764 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002765
2766 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002767 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002768 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002769 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002770 synchronized (mDeferredBindRunnables) {
2771 mDeferredBindRunnables.add(r);
2772 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002773 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002774 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002775 }
Joe Onorato36115782010-06-17 13:28:48 -04002776 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002777
Joe Onorato36115782010-06-17 13:28:48 -04002778 private void loadAndBindAllApps() {
2779 if (DEBUG_LOADERS) {
2780 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2781 }
2782 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002783 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002784 synchronized (LoaderTask.this) {
2785 if (mStopped) {
2786 return;
2787 }
2788 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002789 }
Joe Onorato36115782010-06-17 13:28:48 -04002790 } else {
2791 onlyBindAllApps();
2792 }
2793 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002794
Joe Onorato36115782010-06-17 13:28:48 -04002795 private void onlyBindAllApps() {
2796 final Callbacks oldCallbacks = mCallbacks.get();
2797 if (oldCallbacks == null) {
2798 // This launcher has exited and nobody bothered to tell us. Just bail.
2799 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2800 return;
2801 }
2802
2803 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002804 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002805 final ArrayList<AppInfo> list
2806 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002807 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002808 public void run() {
2809 final long t = SystemClock.uptimeMillis();
2810 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2811 if (callbacks != null) {
2812 callbacks.bindAllApplications(list);
2813 }
2814 if (DEBUG_LOADERS) {
2815 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2816 + (SystemClock.uptimeMillis()-t) + "ms");
2817 }
2818 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002819 };
2820 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002821 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002822 r.run();
2823 } else {
2824 mHandler.post(r);
2825 }
Joe Onorato36115782010-06-17 13:28:48 -04002826 }
2827
Winson Chung64359a52013-07-08 17:17:08 -07002828 private void loadAllApps() {
2829 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002830
Joe Onorato36115782010-06-17 13:28:48 -04002831 final Callbacks oldCallbacks = mCallbacks.get();
2832 if (oldCallbacks == null) {
2833 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002834 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002835 return;
2836 }
2837
2838 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2839 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2840
Kenny Guyed131872014-04-30 03:02:21 +01002841 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2842
Winson Chung64359a52013-07-08 17:17:08 -07002843 // Clear the list of apps
2844 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002845 SharedPreferences prefs = mContext.getSharedPreferences(
2846 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002847 for (UserHandleCompat user : profiles) {
2848 // Query for the set of apps
2849 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2850 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2851 if (DEBUG_LOADERS) {
2852 Log.d(TAG, "getActivityList took "
2853 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2854 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2855 }
2856 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002857 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002858 if (apps == null || apps.isEmpty()) {
2859 return;
2860 }
2861 // Sort the applications by name
2862 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2863 Collections.sort(apps,
2864 new LauncherModel.ShortcutNameComparator(mLabelCache));
2865 if (DEBUG_LOADERS) {
2866 Log.d(TAG, "sort took "
2867 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2868 }
Joe Onorato36115782010-06-17 13:28:48 -04002869
Kenny Guyed131872014-04-30 03:02:21 +01002870 // Create the ApplicationInfos
2871 for (int i = 0; i < apps.size(); i++) {
2872 LauncherActivityInfoCompat app = apps.get(i);
2873 // This builds the icon bitmaps.
2874 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2875 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002876
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002877 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002878 // Add shortcuts for packages which were installed while launcher was dead.
2879 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2880 + mUserManager.getSerialNumberForUser(user);
2881 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2882 HashSet<String> newPackageSet = new HashSet<String>();
2883
2884 for (LauncherActivityInfoCompat info : apps) {
2885 String packageName = info.getComponentName().getPackageName();
2886 if (!packagesAdded.contains(packageName)
2887 && !newPackageSet.contains(packageName)) {
2888 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2889 }
2890 newPackageSet.add(packageName);
2891 }
2892
2893 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2894 }
Winson Chung64359a52013-07-08 17:17:08 -07002895 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002896 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002897 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2898 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002899
2900 // Post callback on main thread
2901 mHandler.post(new Runnable() {
2902 public void run() {
2903 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002904 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002905 if (callbacks != null) {
2906 callbacks.bindAllApplications(added);
2907 if (DEBUG_LOADERS) {
2908 Log.d(TAG, "bound " + added.size() + " apps in "
2909 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2910 }
2911 } else {
2912 Log.i(TAG, "not binding apps: no Launcher activity");
2913 }
2914 }
2915 });
2916
Joe Onorato36115782010-06-17 13:28:48 -04002917 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002918 Log.d(TAG, "Icons processed in "
2919 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002920 }
2921 }
2922
2923 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002924 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002925 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2926 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2927 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2928 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2929 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2930 }
Joe Onorato36115782010-06-17 13:28:48 -04002931 }
2932 }
2933
2934 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002935 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002936 }
2937
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002938 private class AppsAvailabilityCheck extends BroadcastReceiver {
2939
2940 @Override
2941 public void onReceive(Context context, Intent intent) {
2942 synchronized (sBgLock) {
2943 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2944 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002945 final PackageManager manager = context.getPackageManager();
2946 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2947 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002948 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2949 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002950 packagesRemoved.clear();
2951 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002952 for (String pkg : entry.getValue()) {
2953 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002954 boolean packageOnSdcard = launcherApps.isAppEnabled(
2955 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2956 if (packageOnSdcard) {
2957 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2958 packagesUnavailable.add(pkg);
2959 } else {
2960 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2961 packagesRemoved.add(pkg);
2962 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002963 }
2964 }
2965 if (!packagesRemoved.isEmpty()) {
2966 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2967 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2968 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002969 if (!packagesUnavailable.isEmpty()) {
2970 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2971 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2972 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002973 }
Sunny Goyal34942622014-08-29 17:20:55 -07002974 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002975 }
2976 }
2977 }
2978
Joe Onorato36115782010-06-17 13:28:48 -04002979 private class PackageUpdatedTask implements Runnable {
2980 int mOp;
2981 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002982 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002983
2984 public static final int OP_NONE = 0;
2985 public static final int OP_ADD = 1;
2986 public static final int OP_UPDATE = 2;
2987 public static final int OP_REMOVE = 3; // uninstlled
2988 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2989
2990
Kenny Guyed131872014-04-30 03:02:21 +01002991 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002992 mOp = op;
2993 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002994 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002995 }
2996
2997 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002998 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002999
3000 final String[] packages = mPackages;
3001 final int N = packages.length;
3002 switch (mOp) {
3003 case OP_ADD:
3004 for (int i=0; i<N; i++) {
3005 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003006 mIconCache.remove(packages[i], mUser);
3007 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003008 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003009
3010 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003011 if (ADD_MANAGED_PROFILE_SHORTCUTS
3012 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003013 SharedPreferences prefs = context.getSharedPreferences(
3014 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3015 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3016 + mUserManager.getSerialNumberForUser(mUser);
3017 Set<String> shortcutSet = new HashSet<String>(
3018 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3019
3020 for (int i=0; i<N; i++) {
3021 if (!shortcutSet.contains(packages[i])) {
3022 shortcutSet.add(packages[i]);
3023 List<LauncherActivityInfoCompat> activities =
3024 mLauncherApps.getActivityList(packages[i], mUser);
3025 if (activities != null && !activities.isEmpty()) {
3026 InstallShortcutReceiver.queueInstallShortcut(
3027 activities.get(0), context);
3028 }
3029 }
3030 }
3031
3032 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3033 }
Joe Onorato36115782010-06-17 13:28:48 -04003034 break;
3035 case OP_UPDATE:
3036 for (int i=0; i<N; i++) {
3037 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003038 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003039 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003040 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003041 }
3042 break;
3043 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003044 // Remove the packageName for the set of auto-installed shortcuts. This
3045 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003046 if (ADD_MANAGED_PROFILE_SHORTCUTS
3047 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003048 SharedPreferences prefs = context.getSharedPreferences(
3049 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3050 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3051 + mUserManager.getSerialNumberForUser(mUser);
3052 HashSet<String> shortcutSet = new HashSet<String>(
3053 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3054 shortcutSet.removeAll(Arrays.asList(mPackages));
3055 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3056 }
3057 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003058 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003059 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003060 for (int i=0; i<N; i++) {
3061 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003062 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003063 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003064 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003065 }
3066 break;
3067 }
3068
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003069 ArrayList<AppInfo> added = null;
3070 ArrayList<AppInfo> modified = null;
3071 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003072
Adam Cohen487f7dd2012-06-28 18:12:10 -07003073 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003074 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003075 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003076 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003077 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003078 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003079 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003080 }
Winson Chung5d55f332012-07-16 20:45:03 -07003081 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003082 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003083 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003084 }
3085
Sunny Goyale0f58d72014-11-10 18:05:31 -08003086 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003087 if (callbacks == null) {
3088 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3089 return;
3090 }
3091
Sunny Goyal4390ace2014-10-13 11:33:11 -07003092 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3093 new HashMap<ComponentName, AppInfo>();
3094
Joe Onorato36115782010-06-17 13:28:48 -04003095 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003096 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003097 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003098 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003099 addAndBindAddedWorkspaceApps(context, addedInfos);
3100 } else {
3101 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003102 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003103 for (AppInfo ai : added) {
3104 addedOrUpdatedApps.put(ai.componentName, ai);
3105 }
Joe Onorato36115782010-06-17 13:28:48 -04003106 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003107
Joe Onorato36115782010-06-17 13:28:48 -04003108 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003109 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003110 for (AppInfo ai : modified) {
3111 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003112 }
3113
Joe Onorato36115782010-06-17 13:28:48 -04003114 mHandler.post(new Runnable() {
3115 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003116 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003117 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003118 callbacks.bindAppsUpdated(modifiedFinal);
3119 }
3120 }
3121 });
3122 }
Winson Chung83892cc2013-05-01 16:53:33 -07003123
Sunny Goyal4390ace2014-10-13 11:33:11 -07003124 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003125 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003126 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3127 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3128 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3129
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003130 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003131 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003132 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003133 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3134 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003135 boolean infoUpdated = false;
3136 boolean shortcutUpdated = false;
3137
3138 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003139 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003140 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003141 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3142 si.iconResource.resourceName, mIconCache, context);
3143 if (icon != null) {
3144 si.setIcon(icon);
3145 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003146 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003147 }
3148 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003149
3150 ComponentName cn = si.getTargetComponent();
3151 if (cn != null && packageSet.contains(cn.getPackageName())) {
3152 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3153
3154 if (si.isPromise()) {
3155 mIconCache.deletePreloadedIcon(cn, mUser);
3156 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3157 // Auto install icon
3158 PackageManager pm = context.getPackageManager();
3159 ResolveInfo matched = pm.resolveActivity(
3160 new Intent(Intent.ACTION_MAIN)
3161 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3162 PackageManager.MATCH_DEFAULT_ONLY);
3163 if (matched == null) {
3164 // Try to find the best match activity.
3165 Intent intent = pm.getLaunchIntentForPackage(
3166 cn.getPackageName());
3167 if (intent != null) {
3168 cn = intent.getComponent();
3169 appInfo = addedOrUpdatedApps.get(cn);
3170 }
3171
3172 if ((intent == null) || (appInfo == null)) {
3173 removedShortcuts.add(si);
3174 continue;
3175 }
3176 si.promisedIntent = intent;
3177 }
3178 }
3179
3180 // Restore the shortcut.
3181 si.intent = si.promisedIntent;
3182 si.promisedIntent = null;
3183 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3184 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3185 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3186
3187 infoUpdated = true;
3188 si.updateIcon(mIconCache);
3189 }
3190
3191 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3192 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3193 si.updateIcon(mIconCache);
3194 si.title = appInfo.title.toString();
3195 si.contentDescription = appInfo.contentDescription;
3196 infoUpdated = true;
3197 }
3198
3199 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3200 // Since package was just updated, the target must be available now.
3201 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3202 shortcutUpdated = true;
3203 }
3204 }
3205
3206 if (infoUpdated || shortcutUpdated) {
3207 updatedShortcuts.add(si);
3208 }
3209 if (infoUpdated) {
3210 updateItemInDatabase(context, si);
3211 }
3212 } else if (info instanceof LauncherAppWidgetInfo) {
3213 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3214 if (mUser.equals(widgetInfo.user)
3215 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3216 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3217 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3218 widgets.add(widgetInfo);
3219 updateItemInDatabase(context, widgetInfo);
3220 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003221 }
3222 }
3223 }
3224
Sunny Goyal4390ace2014-10-13 11:33:11 -07003225 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3226 mHandler.post(new Runnable() {
3227
3228 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003229 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003230 if (callbacks == cb && cb != null) {
3231 callbacks.bindShortcutsChanged(
3232 updatedShortcuts, removedShortcuts, mUser);
3233 }
3234 }
3235 });
3236 if (!removedShortcuts.isEmpty()) {
3237 deleteItemsFromDatabase(context, removedShortcuts);
3238 }
3239 }
3240 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003241 mHandler.post(new Runnable() {
3242 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003243 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003244 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003245 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003246 }
3247 }
3248 });
3249 }
3250 }
3251
Winson Chungdf95eb12013-10-16 14:57:07 -07003252 final ArrayList<String> removedPackageNames =
3253 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003254 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003255 // Mark all packages in the broadcast to be removed
3256 removedPackageNames.addAll(Arrays.asList(packages));
3257 } else if (mOp == OP_UPDATE) {
3258 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003259 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003260 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003261 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003262 }
3263 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003264 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003265
Winson Chungdf95eb12013-10-16 14:57:07 -07003266 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003267 final int removeReason;
3268 if (mOp == OP_UNAVAILABLE) {
3269 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3270 } else {
3271 // Remove all the components associated with this package
3272 for (String pn : removedPackageNames) {
3273 deletePackageFromDatabase(context, pn, mUser);
3274 }
3275 // Remove all the specific components
3276 for (AppInfo a : removedApps) {
3277 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3278 deleteItemsFromDatabase(context, infos);
3279 }
3280 removeReason = 0;
3281 }
3282
Winson Chungdf95eb12013-10-16 14:57:07 -07003283 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003284 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003285 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003286 mHandler.post(new Runnable() {
3287 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003288 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003289 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003290 callbacks.bindComponentsRemoved(
3291 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003292 }
3293 }
3294 });
Joe Onoratobe386092009-11-17 17:32:16 -08003295 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003296
Michael Jurkac402cd92013-05-20 15:49:32 +02003297 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003298 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003299 mHandler.post(new Runnable() {
3300 @Override
3301 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003302 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003303 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003304 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003305 }
3306 }
3307 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003308
3309 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003310 mHandler.post(new Runnable() {
3311 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003312 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003313 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003314 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003315 }
3316 }
3317 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003318 }
3319 }
3320
Adam Cohen59400422014-03-05 18:07:04 -08003321 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3322 synchronized (sBgLock) {
3323 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3324 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3325 }
3326 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3327 List<AppWidgetProviderInfo> widgets =
3328 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3329 LauncherAppWidgetProviderInfo info;
3330 for (AppWidgetProviderInfo pInfo : widgets) {
3331 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3332 sBgWidgetProviders.put(info.provider, info);
3333 }
3334
3335 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3336 for (CustomAppWidget widget : customWidgets) {
3337 info = new LauncherAppWidgetProviderInfo(context, widget);
3338 sBgWidgetProviders.put(info.provider, info);
3339 }
3340 sWidgetProvidersDirty = false;
3341 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3342 }
3343 }
3344
3345 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3346 synchronized (sBgLock) {
3347 if (sBgWidgetProviders == null) {
3348 getWidgetProviders(ctx);
3349 }
3350 return sBgWidgetProviders.get(name);
3351 }
3352 }
3353
Michael Jurkac402cd92013-05-20 15:49:32 +02003354 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3355 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3356 PackageManager packageManager = context.getPackageManager();
3357 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003358 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003359 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3360 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003361 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003362 return widgetsAndShortcuts;
3363 }
3364
Kenny Guyed131872014-04-30 03:02:21 +01003365 private static boolean isPackageDisabled(Context context, String packageName,
3366 UserHandleCompat user) {
3367 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3368 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003369 }
Adam Cohen556f6132014-01-15 15:18:08 -08003370
Kenny Guyed131872014-04-30 03:02:21 +01003371 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3372 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003373 if (cn == null) {
3374 return false;
3375 }
Kenny Guyed131872014-04-30 03:02:21 +01003376 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3377 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003378 return false;
3379 }
Kenny Guyed131872014-04-30 03:02:21 +01003380 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003381 }
3382
Adam Cohena28b78e2014-05-20 17:03:04 -07003383 public static boolean isValidPackage(Context context, String packageName,
3384 UserHandleCompat user) {
3385 if (packageName == null) {
3386 return false;
3387 }
3388 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3389 return launcherApps.isPackageEnabledForProfile(packageName, user);
3390 }
3391
Joe Onorato9c1289c2009-08-17 11:03:03 -04003392 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003393 * Make an ShortcutInfo object for a restored application or shortcut item that points
3394 * to a package that is not yet installed on the system.
3395 */
Sunny Goyal34942622014-08-29 17:20:55 -07003396 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3397 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003398 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003399 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003400 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3401
3402 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3403 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3404 if (!TextUtils.isEmpty(title)) {
3405 info.title = title;
3406 }
3407 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3408 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3409 if (TextUtils.isEmpty(info.title)) {
3410 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3411 }
3412 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3413 } else {
3414 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3415 }
3416
Kenny Guyc2bd8102014-06-30 12:30:31 +01003417 info.contentDescription = mUserManager.getBadgedLabelForUser(
3418 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003419 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003420 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003421 return info;
3422 }
3423
3424 /**
3425 * Make an Intent object for a restored application or shortcut item that points
3426 * to the market page for the item.
3427 */
3428 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3429 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003430 return getMarketIntent(componentName.getPackageName());
3431 }
3432
3433 static Intent getMarketIntent(String packageName) {
3434 return new Intent(Intent.ACTION_VIEW)
3435 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003436 .scheme("market")
3437 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003438 .appendQueryParameter("id", packageName)
3439 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003440 }
3441
3442 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003443 * This is called from the code that adds shortcuts from the intent receiver. This
3444 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003445 */
Kenny Guyed131872014-04-30 03:02:21 +01003446 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3447 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003448 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003449 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003450
Joe Onorato56d82912010-03-07 14:32:10 -05003451 /**
3452 * Make an ShortcutInfo object for a shortcut that is an application.
3453 *
3454 * If c is not null, then it will be used to fill in missing data like the title and icon.
3455 */
Kenny Guyed131872014-04-30 03:02:21 +01003456 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3457 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003458 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003459 if (user == null) {
3460 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003461 return null;
3462 }
3463
Kenny Guyed131872014-04-30 03:02:21 +01003464 ComponentName componentName = intent.getComponent();
3465 if (componentName == null) {
3466 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3467 return null;
3468 }
3469
3470 Intent newIntent = new Intent(intent.getAction(), null);
3471 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3472 newIntent.setComponent(componentName);
3473 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003474 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003475 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3476 return null;
3477 }
3478
3479 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003480
Joe Onorato56d82912010-03-07 14:32:10 -05003481 // the resource -- This may implicitly give us back the fallback icon,
3482 // but don't worry about that. All we're doing with usingFallbackIcon is
3483 // to avoid saving lots of copies of that in the database, and most apps
3484 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003485 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003486
Joe Onorato56d82912010-03-07 14:32:10 -05003487 // the db
3488 if (icon == null) {
3489 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003490 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003491 }
3492 }
3493 // the fallback icon
3494 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003495 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003496 info.usingFallbackIcon = true;
3497 }
3498 info.setIcon(icon);
3499
Kenny Guyed131872014-04-30 03:02:21 +01003500 // From the cache.
3501 if (labelCache != null) {
3502 info.title = labelCache.get(componentName);
3503 }
3504
Joe Onorato56d82912010-03-07 14:32:10 -05003505 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003506 if (info.title == null && lai != null) {
3507 info.title = lai.getLabel();
3508 if (labelCache != null) {
3509 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003510 }
Joe Onorato56d82912010-03-07 14:32:10 -05003511 }
3512 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003513 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003514 if (c != null) {
3515 info.title = c.getString(titleIndex);
3516 }
3517 }
3518 // fall back to the class name of the activity
3519 if (info.title == null) {
3520 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003521 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003522 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003523 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003524 info.contentDescription = mUserManager.getBadgedLabelForUser(
3525 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003526 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003527 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003528
Winson Chung64359a52013-07-08 17:17:08 -07003529 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3530 ItemInfoFilter f) {
3531 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3532 for (ItemInfo i : infos) {
3533 if (i instanceof ShortcutInfo) {
3534 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003535 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003536 if (cn != null && f.filterItem(null, info, cn)) {
3537 filtered.add(info);
3538 }
3539 } else if (i instanceof FolderInfo) {
3540 FolderInfo info = (FolderInfo) i;
3541 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003542 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003543 if (cn != null && f.filterItem(info, s, cn)) {
3544 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003545 }
3546 }
Winson Chung64359a52013-07-08 17:17:08 -07003547 } else if (i instanceof LauncherAppWidgetInfo) {
3548 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3549 ComponentName cn = info.providerName;
3550 if (cn != null && f.filterItem(null, info, cn)) {
3551 filtered.add(info);
3552 }
Winson Chung8a435102012-08-30 17:16:53 -07003553 }
3554 }
Winson Chung64359a52013-07-08 17:17:08 -07003555 return new ArrayList<ItemInfo>(filtered);
3556 }
3557
Kenny Guyed131872014-04-30 03:02:21 +01003558 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3559 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003560 ItemInfoFilter filter = new ItemInfoFilter() {
3561 @Override
3562 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003563 if (info.user == null) {
3564 return cn.equals(cname);
3565 } else {
3566 return cn.equals(cname) && info.user.equals(user);
3567 }
Winson Chung64359a52013-07-08 17:17:08 -07003568 }
3569 };
3570 return filterItemInfos(sBgItemsIdMap.values(), filter);
3571 }
3572
Sunny Goyal1a745e82014-10-02 15:58:31 -07003573 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003574 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003575 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003576 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003577 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3578 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003579
Joe Onorato56d82912010-03-07 14:32:10 -05003580 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003581 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003582 // Non-app shortcuts are only supported for current user.
3583 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003584 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003585
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003586 // TODO: If there's an explicit component and we can't install that, delete it.
3587
Joe Onorato56d82912010-03-07 14:32:10 -05003588 info.title = c.getString(titleIndex);
3589
Joe Onorato9c1289c2009-08-17 11:03:03 -04003590 int iconType = c.getInt(iconTypeIndex);
3591 switch (iconType) {
3592 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3593 String packageName = c.getString(iconPackageIndex);
3594 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003595 info.customIcon = false;
3596 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003597 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003598 // the db
3599 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003600 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003601 }
3602 // the fallback icon
3603 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003604 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003605 info.usingFallbackIcon = true;
3606 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003607 break;
3608 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003609 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003610 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003611 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003612 info.customIcon = false;
3613 info.usingFallbackIcon = true;
3614 } else {
3615 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003616 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003617 break;
3618 default:
Kenny Guyed131872014-04-30 03:02:21 +01003619 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003620 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003621 info.customIcon = false;
3622 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003623 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003624 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003625 return info;
3626 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003627
Michael Jurka931dc972011-08-05 15:08:15 -07003628 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003629 @SuppressWarnings("all") // suppress dead code warning
3630 final boolean debug = false;
3631 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003632 Log.d(TAG, "getIconFromCursor app="
3633 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3634 }
3635 byte[] data = c.getBlob(iconIndex);
3636 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003637 return Utilities.createIconBitmap(
3638 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003639 } catch (Exception e) {
3640 return null;
3641 }
3642 }
3643
Sunny Goyal2350bc92014-10-14 16:42:54 -07003644 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003645 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3646 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3647 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3648
Adam Cohend9198822011-11-22 16:42:47 -08003649 if (intent == null) {
3650 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3651 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3652 return null;
3653 }
3654
Joe Onorato0589f0f2010-02-08 13:44:00 -08003655 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003656 boolean customIcon = false;
3657 ShortcutIconResource iconResource = null;
3658
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003659 if (bitmap instanceof Bitmap) {
3660 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003661 customIcon = true;
3662 } else {
3663 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003664 if (extra instanceof ShortcutIconResource) {
3665 iconResource = (ShortcutIconResource) extra;
3666 icon = Utilities.createIconBitmap(iconResource.packageName,
3667 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003668 }
3669 }
3670
Michael Jurkac9d95c52011-08-29 14:03:34 -07003671 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003672
Kenny Guyed131872014-04-30 03:02:21 +01003673 // Only support intents for current user for now. Intents sent from other
3674 // users wouldn't get here without intent forwarding anyway.
3675 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003676 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003677 icon = mIconCache.getDefaultIcon(info.user);
3678 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003679 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003680 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003681
Joe Onorato0589f0f2010-02-08 13:44:00 -08003682 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003683 info.contentDescription = mUserManager.getBadgedLabelForUser(
3684 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003685 info.intent = intent;
3686 info.customIcon = customIcon;
3687 info.iconResource = iconResource;
3688
3689 return info;
3690 }
3691
Winson Chungaac01e12011-08-17 10:37:13 -07003692 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3693 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003694 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003695 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003696 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003697 }
Joe Onorato56d82912010-03-07 14:32:10 -05003698 // If this icon doesn't have a custom icon, check to see
3699 // what's stored in the DB, and if it doesn't match what
3700 // we're going to show, store what we are going to show back
3701 // into the DB. We do this so when we're loading, if the
3702 // package manager can't find an icon (for example because
3703 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003704 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003705 cache.put(info, c.getBlob(iconIndex));
3706 return true;
3707 }
3708 return false;
3709 }
3710 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3711 boolean needSave = false;
3712 try {
3713 if (data != null) {
3714 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3715 Bitmap loaded = info.getIcon(mIconCache);
3716 needSave = !saved.sameAs(loaded);
3717 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003718 needSave = true;
3719 }
Winson Chungaac01e12011-08-17 10:37:13 -07003720 } catch (Exception e) {
3721 needSave = true;
3722 }
3723 if (needSave) {
3724 Log.d(TAG, "going to save icon bitmap for info=" + info);
3725 // This is slower than is ideal, but this only happens once
3726 // or when the app is updated with a new icon.
3727 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003728 }
3729 }
3730
Joe Onorato9c1289c2009-08-17 11:03:03 -04003731 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003732 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003733 * or make a new one.
3734 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003735 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003736 // See if a placeholder was created for us already
3737 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003738 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003739 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003740 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003741 folders.put(id, folderInfo);
3742 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003743 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003744 }
3745
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003746 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003747 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003748 return new Comparator<AppInfo>() {
3749 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003750 if (a.user.equals(b.user)) {
3751 int result = collator.compare(a.title.toString().trim(),
3752 b.title.toString().trim());
3753 if (result == 0) {
3754 result = a.componentName.compareTo(b.componentName);
3755 }
3756 return result;
3757 } else {
3758 // TODO Need to figure out rules for sorting
3759 // profiles, this puts work second.
3760 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003761 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003762 }
Winson Chung11904872012-09-17 16:58:46 -07003763 };
3764 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003765 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3766 = new Comparator<AppInfo>() {
3767 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003768 if (a.firstInstallTime < b.firstInstallTime) return 1;
3769 if (a.firstInstallTime > b.firstInstallTime) return -1;
3770 return 0;
3771 }
3772 };
Winson Chung5308f242011-08-18 12:12:41 -07003773 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3774 if (info.activityInfo != null) {
3775 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3776 } else {
3777 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3778 }
3779 }
Kenny Guyed131872014-04-30 03:02:21 +01003780 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003781 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003782 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003783 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003784 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003785 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003786 }
Kenny Guyed131872014-04-30 03:02:21 +01003787 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003788 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003789 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003790 }
Kenny Guyed131872014-04-30 03:02:21 +01003791 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003792 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003793 ComponentName keyA = a.getComponentName();
3794 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003795 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003796 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003797 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003798 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003799
Winson Chung5308f242011-08-18 12:12:41 -07003800 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003801 }
Winson Chung5308f242011-08-18 12:12:41 -07003802 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003803 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003804 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003805 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003806
Winson Chung5308f242011-08-18 12:12:41 -07003807 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003808 }
Winson Chung11904872012-09-17 16:58:46 -07003809 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003810 }
3811 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003812 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003813 private final AppWidgetManagerCompat mManager;
3814 private final PackageManager mPackageManager;
3815 private final HashMap<Object, String> mLabelCache;
3816 private final Collator mCollator;
3817
3818 WidgetAndShortcutNameComparator(Context context) {
3819 mManager = AppWidgetManagerCompat.getInstance(context);
3820 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003821 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003822 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003823 }
3824 public final int compare(Object a, Object b) {
3825 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003826 if (mLabelCache.containsKey(a)) {
3827 labelA = mLabelCache.get(a);
3828 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003829 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3830 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003831 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003832 mLabelCache.put(a, labelA);
3833 }
3834 if (mLabelCache.containsKey(b)) {
3835 labelB = mLabelCache.get(b);
3836 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003837 labelB = (b instanceof LauncherAppWidgetProviderInfo)
3838 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003839 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003840 mLabelCache.put(b, labelB);
3841 }
Winson Chung11904872012-09-17 16:58:46 -07003842 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003843 }
3844 };
Joe Onoratobe386092009-11-17 17:32:16 -08003845
Sunny Goyal651077b2014-06-30 14:15:31 -07003846 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3847 return (provider != null) && (provider.provider != null)
3848 && (provider.provider.getPackageName() != null);
3849 }
3850
Joe Onoratobe386092009-11-17 17:32:16 -08003851 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003852 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003853 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3854 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3855 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3856 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003857 if (mLoaderTask != null) {
3858 mLoaderTask.dumpState();
3859 } else {
3860 Log.d(TAG, "mLoaderTask=null");
3861 }
Joe Onoratobe386092009-11-17 17:32:16 -08003862 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003863
3864 public Callbacks getCallback() {
3865 return mCallbacks != null ? mCallbacks.get() : null;
3866 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003867}