blob: c0444bb0d40fa87af831ab5beb861d4ad440f54c [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetManager;
21import android.appwidget.AppWidgetProviderInfo;
Winson Chungc9168342013-06-26 14:54:55 -070022import android.content.*;
Joe Onorato0589f0f2010-02-08 13:44:00 -080023import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.pm.ActivityInfo;
Adam Cohen00fcb492011-11-02 21:53:47 -070025import android.content.pm.PackageInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.pm.PackageManager;
Adam Cohen00fcb492011-11-02 21:53:47 -070027import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070029import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.res.Resources;
31import android.database.Cursor;
32import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
34import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080035import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040036import android.os.Handler;
37import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080038import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070040import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040041import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040042import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080043import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070044import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070045import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010046
Daniel Sandler325dc232013-06-05 22:57:57 -040047import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
Romain Guyedcce092010-03-04 13:03:17 -080048
Michael Jurkac2f801e2011-07-12 14:19:46 -070049import java.lang.ref.WeakReference;
50import java.net.URISyntaxException;
51import java.text.Collator;
52import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070053import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070054import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070055import java.util.Collections;
56import java.util.Comparator;
57import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070058import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070059import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070060import java.util.List;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070061import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070062import java.util.TreeMap;
Winson Chunga0b7e862013-09-05 16:03:15 -070063import java.util.concurrent.atomic.AtomicBoolean;
Michael Jurkac2f801e2011-07-12 14:19:46 -070064
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065/**
66 * Maintains in-memory state of the Launcher. It is expected that there should be only one
67 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070068 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 */
Joe Onoratof99f8c12009-10-31 17:27:36 -040070public class LauncherModel extends BroadcastReceiver {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080071 static final boolean DEBUG_LOADERS = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -040072 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070073
Daniel Sandler8707e0f2013-08-15 15:54:18 -070074 // true = use a "More Apps" folder for non-workspace apps on upgrade
75 // false = strew non-workspace apps across the workspace on upgrade
76 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
77
Dan Sandlerd5024042014-01-09 15:01:33 -050078 public static final int LOADER_FLAG_NONE = 0;
79 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
80 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
81
Joe Onorato36115782010-06-17 13:28:48 -040082 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050083 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080084
Winson Chungee055712013-07-30 14:46:24 -070085 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -080086 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -040087
Daniel Sandlercc8befa2013-06-11 14:45:48 -040088 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040089 private final Object mLock = new Object();
90 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040091 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070092 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020093 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Winson Chung81b52252012-08-27 15:34:29 -070095 // Specific runnable types that are run on the main thread deferred handler, this allows us to
96 // clear all queued binding runnables when the Launcher activity is destroyed.
97 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
98 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
99
100
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700101 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
102 static {
103 sWorkerThread.start();
104 }
105 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
106
Joe Onoratocc67f472010-06-08 10:54:30 -0700107 // We start off with everything not loaded. After that, we assume that
108 // our monitoring of the package manager provides all updates and we never
109 // need to do a requery. These are only ever touched from the loader thread.
110 private boolean mWorkspaceLoaded;
111 private boolean mAllAppsLoaded;
112
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700113 // When we are loading pages synchronously, we can't just post the binding of items on the side
114 // pages as this delays the rotation process. Instead, we wait for a callback from the first
115 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
116 // a normal load, we also clear this set of Runnables.
117 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
118
Joe Onorato9c1289c2009-08-17 11:03:03 -0400119 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700121 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700122 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800123
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700124 // The lock that must be acquired before referencing any static bg data structures. Unlike
125 // other locks, this one can generally be held long-term because we never expect any of these
126 // static data structures to be referenced outside of the worker thread except on the first
127 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700128 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700129
Adam Cohen487f7dd2012-06-28 18:12:10 -0700130 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700131 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700132 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133
Adam Cohen487f7dd2012-06-28 18:12:10 -0700134 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
135 // created by LauncherModel that are directly on the home screen (however, no widgets or
136 // shortcuts within folders).
137 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138
Adam Cohen487f7dd2012-06-28 18:12:10 -0700139 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
140 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 new ArrayList<LauncherAppWidgetInfo>();
142
Adam Cohen487f7dd2012-06-28 18:12:10 -0700143 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
144 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
147 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700148
149 // sBgWorkspaceScreens is the ordered set of workspace screens.
150 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
151
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 // </ only access in worker thread >
153
154 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800155 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156
Reena Lee99a73f32011-10-24 17:27:37 -0700157 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700158
Joe Onorato9c1289c2009-08-17 11:03:03 -0400159 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700160 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400161 public int getCurrentWorkspaceScreen();
162 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700163 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
164 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700165 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700166 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500167 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700168 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400169 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200170 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700171 public void bindAppsAdded(ArrayList<Long> newScreens,
172 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700173 ArrayList<ItemInfo> addAnimated,
174 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200175 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700176 public void bindComponentsRemoved(ArrayList<String> packageNames,
Winson Chungdf95eb12013-10-16 14:57:07 -0700177 ArrayList<AppInfo> appInfos);
Michael Jurkac402cd92013-05-20 15:49:32 +0200178 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100179 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700180 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700181 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700182 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
Winson Chung64359a52013-07-08 17:17:08 -0700185 public interface ItemInfoFilter {
186 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
187 }
188
Bjorn Bringert1307f632013-10-03 22:31:03 +0100189 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800190 Context context = app.getContext();
191 ContentResolver contentResolver = context.getContentResolver();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400192
Winson Chungee055712013-07-30 14:46:24 -0700193 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Winson Chunga6945242014-01-08 14:04:34 -0800194 mOldContentProviderExists = (contentResolver.acquireContentProviderClient(
195 LauncherSettings.Favorites.OLD_CONTENT_URI) != null);
Daniel Sandlere4f98912013-06-25 15:13:26 -0400196 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100197 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800198 mIconCache = iconCache;
199
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400200 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700201 Configuration config = res.getConfiguration();
202 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800203 }
204
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700205 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
206 * posted on the main thread handler. */
207 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700208 runOnMainThread(r, 0);
209 }
210 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700211 if (sWorkerThread.getThreadId() == Process.myTid()) {
212 // If we are on the worker thread, post onto the main handler
213 mHandler.post(r);
214 } else {
215 r.run();
216 }
217 }
218
219 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
220 * posted on the worker thread handler. */
221 private static void runOnWorkerThread(Runnable r) {
222 if (sWorkerThread.getThreadId() == Process.myTid()) {
223 r.run();
224 } else {
225 // If we are not on the worker thread, then post to the worker handler
226 sWorker.post(r);
227 }
228 }
229
Winson Chunge43a1e72014-01-15 10:33:02 -0800230 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
231 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800232 }
233
Winson Chungc9168342013-06-26 14:54:55 -0700234 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
235 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700236 LauncherAppState app = LauncherAppState.getInstance();
237 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
238 final int xCount = (int) grid.numColumns;
239 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700240 boolean[][] occupied = new boolean[xCount][yCount];
241
242 int cellX, cellY, spanX, spanY;
243 for (int i = 0; i < items.size(); ++i) {
244 final ItemInfo item = items.get(i);
245 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
246 if (item.screenId == screen) {
247 cellX = item.cellX;
248 cellY = item.cellY;
249 spanX = item.spanX;
250 spanY = item.spanY;
251 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
252 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
253 occupied[x][y] = true;
254 }
255 }
256 }
257 }
258 }
259
260 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
261 }
262 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700263 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700264 int firstScreenIndex,
265 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700266 // Lock on the app so that we don't try and get the items while apps are being added
267 LauncherAppState app = LauncherAppState.getInstance();
268 LauncherModel model = app.getModel();
269 boolean found = false;
270 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700271 if (sWorkerThread.getThreadId() != Process.myTid()) {
272 // Flush the LauncherModel worker thread, so that if we just did another
273 // processInstallShortcut, we give it time for its shortcut to get added to the
274 // database (getItemsInLocalCoordinates reads the database)
275 model.flushWorkerThread();
276 }
Winson Chungc9168342013-06-26 14:54:55 -0700277 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700278
279 // Try adding to the workspace screens incrementally, starting at the default or center
280 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700281 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
282 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700283 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700284 int[] tmpCoordinates = new int[2];
285 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700286 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700287 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700288 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700289 }
290 }
291 }
Winson Chungc9168342013-06-26 14:54:55 -0700292 return null;
293 }
294
Adam Cohen76a47a12014-02-05 11:47:43 -0800295 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
296 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
297
298 if (allAppsApps == null) {
299 throw new RuntimeException("allAppsApps must not be null");
300 }
301 if (allAppsApps.isEmpty()) {
302 return;
303 }
304
305 // Process the newly added applications and add them to the database first
306 Runnable r = new Runnable() {
307 public void run() {
308 runOnMainThread(new Runnable() {
309 public void run() {
310 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
311 if (callbacks == cb && cb != null) {
312 callbacks.bindAppsAdded(null, null, null, allAppsApps);
313 }
314 }
315 });
316 }
317 };
318 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700319 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800320
321 public void addAndBindAddedWorkspaceApps(final Context context,
322 final ArrayList<ItemInfo> workspaceApps) {
323 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
324
325 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800326 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
327 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800328 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700329 return;
Winson Chung997a9232013-07-24 15:33:46 -0700330 }
Winson Chung64359a52013-07-08 17:17:08 -0700331 // Process the newly added applications and add them to the database first
332 Runnable r = new Runnable() {
333 public void run() {
334 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
335 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
336
Winson Chung76828c82013-08-19 15:43:29 -0700337 // Get the list of workspace screens. We need to append to this list and
338 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
339 // called.
340 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
341 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
342 for (Integer i : orderedScreens.keySet()) {
343 long screenId = orderedScreens.get(i);
344 workspaceScreens.add(screenId);
345 }
346
Winson Chung64359a52013-07-08 17:17:08 -0700347 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700348 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700349 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700350 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700351 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700352 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700353
354 // Short-circuit this logic if the icon exists somewhere on the workspace
355 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
356 continue;
357 }
358
Winson Chung87412982013-10-03 18:34:14 -0700359 // Add this icon to the db, creating a new page if necessary. If there
360 // is only the empty page then we just add items to the first page.
361 // Otherwise, we add them to the next pages.
362 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700363 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700364 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700365 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200366 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700367
368 // If we can't find a valid position, then just add a new screen.
369 // This takes time so we need to re-queue the add until the new
370 // page is added. Create as many screens as necessary to satisfy
371 // the startSearchPageIndex.
372 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700373 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700374 while (numPagesToAdd > 0) {
375 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700376 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700377 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700378 addedWorkspaceScreensFinal.add(screenId);
379 numPagesToAdd--;
380 }
Winson Chung76828c82013-08-19 15:43:29 -0700381
Winson Chung64359a52013-07-08 17:17:08 -0700382 // Find the coordinate again
383 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700384 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700385 }
386 if (coords == null) {
387 throw new RuntimeException("Coordinates should not be null");
388 }
389
Winson Chung997a9232013-07-24 15:33:46 -0700390 ShortcutInfo shortcutInfo;
391 if (a instanceof ShortcutInfo) {
392 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200393 } else if (a instanceof AppInfo) {
394 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700395 } else {
396 throw new RuntimeException("Unexpected info type");
397 }
Winson Chung94d67682013-09-25 16:29:40 -0700398
Winson Chung64359a52013-07-08 17:17:08 -0700399 // Add the shortcut to the db
400 addItemToDatabase(context, shortcutInfo,
401 LauncherSettings.Favorites.CONTAINER_DESKTOP,
402 coords.first, coords.second[0], coords.second[1], false);
403 // Save the ShortcutInfo for binding in the workspace
404 addedShortcutsFinal.add(shortcutInfo);
405 }
406 }
407
Winson Chung76828c82013-08-19 15:43:29 -0700408 // Update the workspace screens
409 updateWorkspaceScreenOrder(context, workspaceScreens);
410
Adam Cohen76a47a12014-02-05 11:47:43 -0800411 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700412 runOnMainThread(new Runnable() {
413 public void run() {
414 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
415 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700416 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
417 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700418 if (!addedShortcutsFinal.isEmpty()) {
419 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
420 long lastScreenId = info.screenId;
421 for (ItemInfo i : addedShortcutsFinal) {
422 if (i.screenId == lastScreenId) {
423 addAnimated.add(i);
424 } else {
425 addNotAnimated.add(i);
426 }
Winson Chung997a9232013-07-24 15:33:46 -0700427 }
428 }
Winson Chungd64d1762013-08-20 14:37:16 -0700429 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800430 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700431 }
Winson Chung64359a52013-07-08 17:17:08 -0700432 }
Winson Chung997a9232013-07-24 15:33:46 -0700433 });
434 }
Winson Chung64359a52013-07-08 17:17:08 -0700435 }
436 };
437 runOnWorkerThread(r);
438 }
439
Joe Onorato56d82912010-03-07 14:32:10 -0500440 public Bitmap getFallbackIcon() {
Winson Chung5801ef02013-10-16 13:46:28 -0700441 if (mDefaultIcon == null) {
442 final Context context = LauncherAppState.getInstance().getContext();
443 mDefaultIcon = Utilities.createIconBitmap(
444 mIconCache.getFullResDefaultActivityIcon(), context);
445 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800446 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400447 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800448
Winson Chung81b52252012-08-27 15:34:29 -0700449 public void unbindItemInfosAndClearQueuedBindRunnables() {
450 if (sWorkerThread.getThreadId() == Process.myTid()) {
451 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
452 "main thread");
453 }
454
455 // Clear any deferred bind runnables
456 mDeferredBindRunnables.clear();
457 // Remove any queued bind runnables
458 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
459 // Unbind all the workspace items
460 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700461 }
462
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700463 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700464 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700465 // Ensure that we don't use the same workspace items data structure on the main thread
466 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700467 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
468 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700469 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700470 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
471 tmpAppWidgets.addAll(sBgAppWidgets);
472 }
473 Runnable r = new Runnable() {
474 @Override
475 public void run() {
476 for (ItemInfo item : tmpWorkspaceItems) {
477 item.unbind();
478 }
479 for (ItemInfo item : tmpAppWidgets) {
480 item.unbind();
481 }
482 }
483 };
484 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700485 }
486
Joe Onorato9c1289c2009-08-17 11:03:03 -0400487 /**
488 * Adds an item to the DB if it was not created previously, or move it to a new
489 * <container, screen, cellX, cellY>
490 */
491 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700492 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400493 if (item.container == ItemInfo.NO_ID) {
494 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700495 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400496 } else {
497 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700498 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800499 }
500 }
501
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700502 static void checkItemInfoLocked(
503 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
504 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
505 if (modelItem != null && item != modelItem) {
506 // check all the data is consistent
507 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
508 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
509 ShortcutInfo shortcut = (ShortcutInfo) item;
510 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
511 modelShortcut.intent.filterEquals(shortcut.intent) &&
512 modelShortcut.id == shortcut.id &&
513 modelShortcut.itemType == shortcut.itemType &&
514 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700515 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700516 modelShortcut.cellX == shortcut.cellX &&
517 modelShortcut.cellY == shortcut.cellY &&
518 modelShortcut.spanX == shortcut.spanX &&
519 modelShortcut.spanY == shortcut.spanY &&
520 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
521 (modelShortcut.dropPos != null &&
522 shortcut.dropPos != null &&
523 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
524 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
525 // For all intents and purposes, this is the same object
526 return;
527 }
528 }
529
530 // the modelItem needs to match up perfectly with item if our model is
531 // to be consistent with the database-- for now, just require
532 // modelItem == item or the equality check above
533 String msg = "item: " + ((item != null) ? item.toString() : "null") +
534 "modelItem: " +
535 ((modelItem != null) ? modelItem.toString() : "null") +
536 "Error: ItemInfo passed to checkItemInfo doesn't match original";
537 RuntimeException e = new RuntimeException(msg);
538 if (stackTrace != null) {
539 e.setStackTrace(stackTrace);
540 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800541 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700542 }
543 }
544
Michael Jurka816474f2012-06-25 14:49:02 -0700545 static void checkItemInfo(final ItemInfo item) {
546 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
547 final long itemId = item.id;
548 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700549 public void run() {
550 synchronized (sBgLock) {
551 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700552 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700553 }
554 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700555 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700556 }
557
Michael Jurkac9d95c52011-08-29 14:03:34 -0700558 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
559 final ItemInfo item, final String callingFunction) {
560 final long itemId = item.id;
561 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
562 final ContentResolver cr = context.getContentResolver();
563
Adam Cohen487f7dd2012-06-28 18:12:10 -0700564 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700565 Runnable r = new Runnable() {
566 public void run() {
567 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700568 updateItemArrays(item, itemId, stackTrace);
569 }
570 };
571 runOnWorkerThread(r);
572 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700573
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700574 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
575 final ArrayList<ItemInfo> items, final String callingFunction) {
576 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700577
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700578 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
579 Runnable r = new Runnable() {
580 public void run() {
581 ArrayList<ContentProviderOperation> ops =
582 new ArrayList<ContentProviderOperation>();
583 int count = items.size();
584 for (int i = 0; i < count; i++) {
585 ItemInfo item = items.get(i);
586 final long itemId = item.id;
587 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
588 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700589
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700590 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
591 updateItemArrays(item, itemId, stackTrace);
592
593 }
594 try {
595 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
596 } catch (Exception e) {
597 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700598 }
599 }
600 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700601 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700602 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700603
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700604 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
605 // Lock on mBgLock *after* the db operation
606 synchronized (sBgLock) {
607 checkItemInfoLocked(itemId, item, stackTrace);
608
609 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
610 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
611 // Item is in a folder, make sure this folder exists
612 if (!sBgFolders.containsKey(item.container)) {
613 // An items container is being set to a that of an item which is not in
614 // the list of Folders.
615 String msg = "item: " + item + " container being set to: " +
616 item.container + ", not in the list of folders";
617 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700618 }
619 }
620
621 // Items are added/removed from the corresponding FolderInfo elsewhere, such
622 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
623 // that are on the desktop, as appropriate
624 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800625 if (modelItem != null &&
626 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
627 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700628 switch (modelItem.itemType) {
629 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
630 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
631 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
632 if (!sBgWorkspaceItems.contains(modelItem)) {
633 sBgWorkspaceItems.add(modelItem);
634 }
635 break;
636 default:
637 break;
638 }
639 } else {
640 sBgWorkspaceItems.remove(modelItem);
641 }
642 }
643 }
644
Michael Jurkac7700af2013-05-14 20:17:58 +0200645 public void flushWorkerThread() {
646 mFlushingWorkerThread = true;
647 Runnable waiter = new Runnable() {
648 public void run() {
649 synchronized (this) {
650 notifyAll();
651 mFlushingWorkerThread = false;
652 }
653 }
654 };
655
656 synchronized(waiter) {
657 runOnWorkerThread(waiter);
658 if (mLoaderTask != null) {
659 synchronized(mLoaderTask) {
660 mLoaderTask.notify();
661 }
662 }
663 boolean success = false;
664 while (!success) {
665 try {
666 waiter.wait();
667 success = true;
668 } catch (InterruptedException e) {
669 }
670 }
671 }
672 }
673
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800674 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400675 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700676 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700677 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700678 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400679 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400680 item.cellX = cellX;
681 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700682
Winson Chung3d503fb2011-07-13 17:25:49 -0700683 // We store hotseat items in canonical form which is this orientation invariant position
684 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700685 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700686 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700687 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700688 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700689 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700690 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400691
692 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400693 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700694 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
695 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700696 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400697
Michael Jurkac9d95c52011-08-29 14:03:34 -0700698 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700699 }
700
701 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700702 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
703 * cellX, cellY have already been updated on the ItemInfos.
704 */
705 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
706 final long container, final int screen) {
707
708 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
709 int count = items.size();
710
711 for (int i = 0; i < count; i++) {
712 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700713 item.container = container;
714
715 // We store hotseat items in canonical form which is this orientation invariant position
716 // in the hotseat
717 if (context instanceof Launcher && screen < 0 &&
718 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700719 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700720 item.cellY);
721 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700722 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700723 }
724
725 final ContentValues values = new ContentValues();
726 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
727 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
728 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700729 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700730
731 contentValues.add(values);
732 }
733 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
734 }
735
736 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700737 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800738 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700739 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700740 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700741 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800742 item.cellX = cellX;
743 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700744 item.spanX = spanX;
745 item.spanY = spanY;
746
747 // We store hotseat items in canonical form which is this orientation invariant position
748 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700749 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700750 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700751 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700752 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700753 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700754 }
Adam Cohend4844c32011-02-18 19:25:06 -0800755
Adam Cohend4844c32011-02-18 19:25:06 -0800756 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800757 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700758 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
759 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
760 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
761 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800763
Michael Jurka816474f2012-06-25 14:49:02 -0700764 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700765 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700766
767 /**
768 * Update an item to the database in a specified container.
769 */
770 static void updateItemInDatabase(Context context, final ItemInfo item) {
771 final ContentValues values = new ContentValues();
772 item.onAddToDatabase(values);
773 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
774 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800775 }
776
777 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400778 * Returns true if the shortcuts already exists in the database.
779 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800780 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400781 static boolean shortcutExists(Context context, String title, Intent intent) {
782 final ContentResolver cr = context.getContentResolver();
783 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
784 new String[] { "title", "intent" }, "title=? and intent=?",
785 new String[] { title, intent.toUri(0) }, null);
786 boolean result = false;
787 try {
788 result = c.moveToFirst();
789 } finally {
790 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400792 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700793 }
794
Joe Onorato9c1289c2009-08-17 11:03:03 -0400795 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700796 * Returns an ItemInfo array containing all the items in the LauncherModel.
797 * The ItemInfo.id is not set through this function.
798 */
799 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
800 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
801 final ContentResolver cr = context.getContentResolver();
802 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
803 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
804 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
805 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
806
807 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
808 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
809 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
810 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
811 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
812 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
813 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
814
815 try {
816 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700817 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700818 item.cellX = c.getInt(cellXIndex);
819 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700820 item.spanX = Math.max(1, c.getInt(spanXIndex));
821 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700822 item.container = c.getInt(containerIndex);
823 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700825
826 items.add(item);
827 }
828 } catch (Exception e) {
829 items.clear();
830 } finally {
831 c.close();
832 }
833
834 return items;
835 }
836
837 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400838 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
839 */
840 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
841 final ContentResolver cr = context.getContentResolver();
842 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
843 "_id=? and (itemType=? or itemType=?)",
844 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700845 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700846
Joe Onorato9c1289c2009-08-17 11:03:03 -0400847 try {
848 if (c.moveToFirst()) {
849 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
850 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
851 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
852 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
853 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
854 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800855
Joe Onorato9c1289c2009-08-17 11:03:03 -0400856 FolderInfo folderInfo = null;
857 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700858 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
859 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400860 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700861 }
862
Joe Onorato9c1289c2009-08-17 11:03:03 -0400863 folderInfo.title = c.getString(titleIndex);
864 folderInfo.id = id;
865 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700866 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700867 folderInfo.cellX = c.getInt(cellXIndex);
868 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400869
870 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700871 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400872 } finally {
873 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700874 }
875
876 return null;
877 }
878
Joe Onorato9c1289c2009-08-17 11:03:03 -0400879 /**
880 * Add an item to the database in a specified container. Sets the container, screen, cellX and
881 * cellY fields of the item. Also assigns an ID to the item.
882 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700883 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700884 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886 item.cellX = cellX;
887 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700888 // We store hotseat items in canonical form which is this orientation invariant position
889 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700890 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700891 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700892 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700893 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700894 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700895 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400896
897 final ContentValues values = new ContentValues();
898 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400899 item.onAddToDatabase(values);
900
Michael Jurka414300a2013-08-27 15:42:35 +0200901 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700902 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700903 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700904
Michael Jurkac9d95c52011-08-29 14:03:34 -0700905 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700906 public void run() {
907 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
908 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400909
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700910 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700911 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700912 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700913 sBgItemsIdMap.put(item.id, item);
914 switch (item.itemType) {
915 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
916 sBgFolders.put(item.id, (FolderInfo) item);
917 // Fall through
918 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
919 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
920 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
921 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
922 sBgWorkspaceItems.add(item);
923 } else {
924 if (!sBgFolders.containsKey(item.container)) {
925 // Adding an item to a folder that doesn't exist.
926 String msg = "adding item: " + item + " to a folder that " +
927 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700928 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700929 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700930 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700931 break;
932 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
933 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
934 break;
935 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700936 }
937 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700938 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700939 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700940 }
941
Joe Onorato9c1289c2009-08-17 11:03:03 -0400942 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700943 * Creates a new unique child id, for a given cell span across all layouts.
944 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700945 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700946 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700947 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700948 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700949 }
950
Winson Chungaafa03c2010-06-11 17:34:16 -0700951 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700952 * Removes the specified item from the database
953 * @param context
954 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400955 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700956 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400957 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700958 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700959
Michael Jurka83df1882011-08-31 20:59:26 -0700960 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700961 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700962 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700963
964 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700965 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700966 switch (item.itemType) {
967 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
968 sBgFolders.remove(item.id);
969 for (ItemInfo info: sBgItemsIdMap.values()) {
970 if (info.container == item.id) {
971 // We are deleting a folder which still contains items that
972 // think they are contained by that folder.
973 String msg = "deleting a folder (" + item + ") which still " +
974 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700975 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700976 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700977 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700978 sBgWorkspaceItems.remove(item);
979 break;
980 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
981 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
982 sBgWorkspaceItems.remove(item);
983 break;
984 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
985 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
986 break;
987 }
988 sBgItemsIdMap.remove(item.id);
989 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700990 }
991 }
Michael Jurka83df1882011-08-31 20:59:26 -0700992 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700993 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994 }
995
996 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700997 * Update the order of the workspace screens in the database. The array list contains
998 * a list of screen ids in the order that they should appear.
999 */
Winson Chungc9168342013-06-26 14:54:55 -07001000 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001001 // Log to disk
1002 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1003 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1004
Winson Chung64359a52013-07-08 17:17:08 -07001005 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001006 final ContentResolver cr = context.getContentResolver();
1007 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1008
1009 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001010 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 while (iter.hasNext()) {
1012 long id = iter.next();
1013 if (id < 0) {
1014 iter.remove();
1015 }
1016 }
1017
1018 Runnable r = new Runnable() {
1019 @Override
1020 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001021 // Clear the table
1022 cr.delete(uri, null, null);
Winson Chung76828c82013-08-19 15:43:29 -07001023 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001024 ContentValues[] values = new ContentValues[count];
1025 for (int i = 0; i < count; i++) {
1026 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001027 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001028 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1029 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001030 values[i] = v;
1031 }
1032 cr.bulkInsert(uri, values);
Winson Chung9e6a0a22013-08-27 11:58:12 -07001033
Winson Chungba9c37f2013-08-30 14:11:37 -07001034 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001035 sBgWorkspaceScreens.clear();
1036 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001037 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001038 }
1039 };
1040 runOnWorkerThread(r);
1041 }
1042
1043 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001044 * Remove the contents of the specified folder from the database
1045 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001046 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001047 final ContentResolver cr = context.getContentResolver();
1048
Michael Jurkac9d95c52011-08-29 14:03:34 -07001049 Runnable r = new Runnable() {
1050 public void run() {
1051 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001052 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001053 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001054 sBgItemsIdMap.remove(info.id);
1055 sBgFolders.remove(info.id);
1056 sBgDbIconCache.remove(info);
1057 sBgWorkspaceItems.remove(info);
1058 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001059
Michael Jurkac9d95c52011-08-29 14:03:34 -07001060 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1061 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001062 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001063 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001064 for (ItemInfo childInfo : info.contents) {
1065 sBgItemsIdMap.remove(childInfo.id);
1066 sBgDbIconCache.remove(childInfo);
1067 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001068 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001069 }
1070 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001071 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001072 }
1073
1074 /**
1075 * Set this as the current Launcher activity object for the loader.
1076 */
1077 public void initialize(Callbacks callbacks) {
1078 synchronized (mLock) {
1079 mCallbacks = new WeakReference<Callbacks>(callbacks);
1080 }
1081 }
1082
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001083 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001084 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1085 * ACTION_PACKAGE_CHANGED.
1086 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001087 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001088 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001089 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001090
Joe Onorato36115782010-06-17 13:28:48 -04001091 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001092
Joe Onorato36115782010-06-17 13:28:48 -04001093 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1094 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1095 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1096 final String packageName = intent.getData().getSchemeSpecificPart();
1097 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001098
Joe Onorato36115782010-06-17 13:28:48 -04001099 int op = PackageUpdatedTask.OP_NONE;
1100
1101 if (packageName == null || packageName.length() == 0) {
1102 // they sent us a bad intent
1103 return;
1104 }
1105
1106 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1107 op = PackageUpdatedTask.OP_UPDATE;
1108 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1109 if (!replacing) {
1110 op = PackageUpdatedTask.OP_REMOVE;
1111 }
1112 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1113 // later, we will update the package at this time
1114 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1115 if (!replacing) {
1116 op = PackageUpdatedTask.OP_ADD;
1117 } else {
1118 op = PackageUpdatedTask.OP_UPDATE;
1119 }
1120 }
1121
1122 if (op != PackageUpdatedTask.OP_NONE) {
1123 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1124 }
1125
1126 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001127 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onoratocec58332010-10-07 14:37:40 -04001128 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Winson Chung3ee4a472014-01-06 15:53:37 -08001129 if (!replacing) {
1130 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1131 if (mAppsCanBeOnRemoveableStorage) {
1132 // Only rebind if we support removable storage. It catches the case where
1133 // apps on the external sd card need to be reloaded
1134 startLoaderFromBackground();
1135 }
1136 } else {
1137 // If we are replacing then just update the packages in the list
1138 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1139 packages));
1140 }
Joe Onorato36115782010-06-17 13:28:48 -04001141 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001142 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1143 if (!replacing) {
1144 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1145 enqueuePackageUpdated(new PackageUpdatedTask(
1146 PackageUpdatedTask.OP_UNAVAILABLE, packages));
1147 }
1148 // else, we are replacing the packages, so ignore this event and wait for
1149 // EXTERNAL_APPLICATIONS_AVAILABLE to update the packages at that time
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001150 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001151 // If we have changed locale we need to clear out the labels in all apps/workspace.
1152 forceReload();
1153 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1154 // Check if configuration change was an mcc/mnc change which would affect app resources
1155 // and we would need to clear out the labels in all apps/workspace. Same handling as
1156 // above for ACTION_LOCALE_CHANGED
1157 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001158 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001159 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001160 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001161 forceReload();
1162 }
1163 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001164 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001165 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1166 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001167 if (mCallbacks != null) {
1168 Callbacks callbacks = mCallbacks.get();
1169 if (callbacks != null) {
1170 callbacks.bindSearchablesChanged();
1171 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001172 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001173 }
1174 }
1175
Reena Lee93f824a2011-09-23 17:20:28 -07001176 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001177 resetLoadedState(true, true);
1178
Reena Lee93f824a2011-09-23 17:20:28 -07001179 // Do this here because if the launcher activity is running it will be restarted.
1180 // If it's not running startLoaderFromBackground will merely tell it that it needs
1181 // to reload.
1182 startLoaderFromBackground();
1183 }
1184
Winson Chungf0c6ae02012-03-21 16:10:31 -07001185 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1186 synchronized (mLock) {
1187 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1188 // mWorkspaceLoaded to true later
1189 stopLoaderLocked();
1190 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1191 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1192 }
1193 }
1194
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001195 /**
1196 * When the launcher is in the background, it's possible for it to miss paired
1197 * configuration changes. So whenever we trigger the loader from the background
1198 * tell the launcher that it needs to re-run the loader when it comes back instead
1199 * of doing it now.
1200 */
1201 public void startLoaderFromBackground() {
1202 boolean runLoader = false;
1203 if (mCallbacks != null) {
1204 Callbacks callbacks = mCallbacks.get();
1205 if (callbacks != null) {
1206 // Only actually run the loader if they're not paused.
1207 if (!callbacks.setLoadOnResume()) {
1208 runLoader = true;
1209 }
1210 }
1211 }
1212 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001213 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001214 }
Joe Onorato36115782010-06-17 13:28:48 -04001215 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001216
Reena Lee93f824a2011-09-23 17:20:28 -07001217 // If there is already a loader task running, tell it to stop.
1218 // returns true if isLaunching() was true on the old task
1219 private boolean stopLoaderLocked() {
1220 boolean isLaunching = false;
1221 LoaderTask oldTask = mLoaderTask;
1222 if (oldTask != null) {
1223 if (oldTask.isLaunching()) {
1224 isLaunching = true;
1225 }
1226 oldTask.stopLocked();
1227 }
1228 return isLaunching;
1229 }
1230
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001231 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001232 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1233 }
1234
1235 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001236 synchronized (mLock) {
1237 if (DEBUG_LOADERS) {
1238 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1239 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001240
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001241 // Clear any deferred bind-runnables from the synchronized load process
1242 // We must do this before any loading/binding is scheduled below.
1243 mDeferredBindRunnables.clear();
1244
Joe Onorato36115782010-06-17 13:28:48 -04001245 // Don't bother to start the thread if we know it's not going to do anything
1246 if (mCallbacks != null && mCallbacks.get() != null) {
1247 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001248 // also, don't downgrade isLaunching if we're already running
1249 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001250 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001251 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1252 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001253 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1254 } else {
1255 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1256 sWorker.post(mLoaderTask);
1257 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001258 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001259 }
1260 }
1261
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001262 void bindRemainingSynchronousPages() {
1263 // Post the remaining side pages to be loaded
1264 if (!mDeferredBindRunnables.isEmpty()) {
1265 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001266 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001267 }
1268 mDeferredBindRunnables.clear();
1269 }
1270 }
1271
Joe Onorato36115782010-06-17 13:28:48 -04001272 public void stopLoader() {
1273 synchronized (mLock) {
1274 if (mLoaderTask != null) {
1275 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001276 }
1277 }
Joe Onorato36115782010-06-17 13:28:48 -04001278 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001279
Winson Chung76828c82013-08-19 15:43:29 -07001280 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1281 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1282 final ContentResolver contentResolver = context.getContentResolver();
1283 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1284 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1285 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1286
1287 try {
1288 final int idIndex = sc.getColumnIndexOrThrow(
1289 LauncherSettings.WorkspaceScreens._ID);
1290 final int rankIndex = sc.getColumnIndexOrThrow(
1291 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1292 while (sc.moveToNext()) {
1293 try {
1294 long screenId = sc.getLong(idIndex);
1295 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001296 orderedScreens.put(rank, screenId);
1297 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001298 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001299 }
1300 }
1301 } finally {
1302 sc.close();
1303 }
Winson Chunga90303b2013-11-15 13:05:06 -08001304
1305 // Log to disk
1306 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1307 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1308 for (Integer i : orderedScreens.keySet()) {
1309 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1310 }
1311 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1312 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001313 return orderedScreens;
1314 }
1315
Michael Jurkac57b7a82011-08-09 22:02:20 -07001316 public boolean isAllAppsLoaded() {
1317 return mAllAppsLoaded;
1318 }
1319
Winson Chung36a62fe2012-05-06 18:04:42 -07001320 boolean isLoadingWorkspace() {
1321 synchronized (mLock) {
1322 if (mLoaderTask != null) {
1323 return mLoaderTask.isLoadingWorkspace();
1324 }
1325 }
1326 return false;
1327 }
1328
Joe Onorato36115782010-06-17 13:28:48 -04001329 /**
1330 * Runnable for the thread that loads the contents of the launcher:
1331 * - workspace icons
1332 * - widgets
1333 * - all apps icons
1334 */
1335 private class LoaderTask implements Runnable {
1336 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001337 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001338 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001339 private boolean mStopped;
1340 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001341 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001342
Winson Chungc3eecff2011-07-11 17:44:15 -07001343 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001344
Dan Sandlerd5024042014-01-09 15:01:33 -05001345 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001346 mContext = context;
1347 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001348 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001349 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001350 }
1351
Joe Onorato36115782010-06-17 13:28:48 -04001352 boolean isLaunching() {
1353 return mIsLaunching;
1354 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001355
Winson Chung36a62fe2012-05-06 18:04:42 -07001356 boolean isLoadingWorkspace() {
1357 return mIsLoadingAndBindingWorkspace;
1358 }
1359
Winson Chungc763c4e2013-07-19 13:49:06 -07001360 /** Returns whether this is an upgrade path */
1361 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001362 mIsLoadingAndBindingWorkspace = true;
1363
Joe Onorato36115782010-06-17 13:28:48 -04001364 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001365 if (DEBUG_LOADERS) {
1366 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001367 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001368
Winson Chungc763c4e2013-07-19 13:49:06 -07001369 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001370 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001371 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001372 synchronized (LoaderTask.this) {
1373 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001374 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001375 }
1376 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001377 }
1378 }
1379
Joe Onorato36115782010-06-17 13:28:48 -04001380 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001381 bindWorkspace(-1, isUpgradePath);
1382 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001383 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001384
Joe Onorato36115782010-06-17 13:28:48 -04001385 private void waitForIdle() {
1386 // Wait until the either we're stopped or the other threads are done.
1387 // This way we don't start loading all apps until the workspace has settled
1388 // down.
1389 synchronized (LoaderTask.this) {
1390 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001391
Joe Onorato36115782010-06-17 13:28:48 -04001392 mHandler.postIdle(new Runnable() {
1393 public void run() {
1394 synchronized (LoaderTask.this) {
1395 mLoadAndBindStepFinished = true;
1396 if (DEBUG_LOADERS) {
1397 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001398 }
Joe Onorato36115782010-06-17 13:28:48 -04001399 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001400 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001401 }
Joe Onorato36115782010-06-17 13:28:48 -04001402 });
1403
Michael Jurkac7700af2013-05-14 20:17:58 +02001404 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001405 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001406 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1407 // wait no longer than 1sec at a time
1408 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001409 } catch (InterruptedException ex) {
1410 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001411 }
1412 }
Joe Onorato36115782010-06-17 13:28:48 -04001413 if (DEBUG_LOADERS) {
1414 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001415 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001416 + "ms for previous step to finish binding");
1417 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001418 }
Joe Onorato36115782010-06-17 13:28:48 -04001419 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001420
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001421 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001422 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001423 // Ensure that we have a valid page index to load synchronously
1424 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1425 "valid page index");
1426 }
1427 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1428 // Ensure that we don't try and bind a specified page when the pages have not been
1429 // loaded already (we should load everything asynchronously in that case)
1430 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1431 }
1432 synchronized (mLock) {
1433 if (mIsLoaderTaskRunning) {
1434 // Ensure that we are never running the background loading at this point since
1435 // we also touch the background collections
1436 throw new RuntimeException("Error! Background loading is already running");
1437 }
1438 }
1439
1440 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1441 // data structures, we can't allow any other thread to touch that data, but because
1442 // this call is synchronous, we can get away with not locking).
1443
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001444 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001445 // operations from the previous activity. We need to ensure that all queued operations
1446 // are executed before any synchronous binding work is done.
1447 mHandler.flush();
1448
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001449 // Divide the set of loaded items into those that we are binding synchronously, and
1450 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001451 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001452 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1453 // arise from that.
1454 onlyBindAllApps();
1455 }
1456
Joe Onorato36115782010-06-17 13:28:48 -04001457 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001458 boolean isUpgrade = false;
1459
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001460 synchronized (mLock) {
1461 mIsLoaderTaskRunning = true;
1462 }
Joe Onorato36115782010-06-17 13:28:48 -04001463 // Optimize for end-user experience: if the Launcher is up and // running with the
1464 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1465 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001466 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001467 // Elevate priority when Home launches for the first time to avoid
1468 // starving at boot time. Staring at a blank home is not cool.
1469 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001470 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1471 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001472 android.os.Process.setThreadPriority(mIsLaunching
1473 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1474 }
Winson Chung64359a52013-07-08 17:17:08 -07001475 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001476 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001477
Joe Onorato36115782010-06-17 13:28:48 -04001478 if (mStopped) {
1479 break keep_running;
1480 }
1481
1482 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1483 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001484 synchronized (mLock) {
1485 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001486 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001487 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488 }
1489 }
Joe Onorato36115782010-06-17 13:28:48 -04001490 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001491
1492 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001493 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1494 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001495
1496 // Restore the default thread priority after we are done loading items
1497 synchronized (mLock) {
1498 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499 }
Joe Onorato36115782010-06-17 13:28:48 -04001500 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001501
Winson Chungaac01e12011-08-17 10:37:13 -07001502 // Update the saved icons if necessary
1503 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001504 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001505 for (Object key : sBgDbIconCache.keySet()) {
1506 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1507 }
1508 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001509 }
Winson Chungaac01e12011-08-17 10:37:13 -07001510
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001511 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001512 // Ensure that all the applications that are in the system are
1513 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001514 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001515 verifyApplications();
1516 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001517 }
1518
Joe Onorato36115782010-06-17 13:28:48 -04001519 // Clear out this reference, otherwise we end up holding it until all of the
1520 // callback runnables are done.
1521 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001522
Joe Onorato36115782010-06-17 13:28:48 -04001523 synchronized (mLock) {
1524 // If we are still the last one to be scheduled, remove ourselves.
1525 if (mLoaderTask == this) {
1526 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001527 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001528 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001529 }
Joe Onorato36115782010-06-17 13:28:48 -04001530 }
1531
1532 public void stopLocked() {
1533 synchronized (LoaderTask.this) {
1534 mStopped = true;
1535 this.notify();
1536 }
1537 }
1538
1539 /**
1540 * Gets the callbacks object. If we've been stopped, or if the launcher object
1541 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1542 * object that was around when the deferred message was scheduled, and if there's
1543 * a new Callbacks object around then also return null. This will save us from
1544 * calling onto it with data that will be ignored.
1545 */
1546 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1547 synchronized (mLock) {
1548 if (mStopped) {
1549 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001550 }
Joe Onorato36115782010-06-17 13:28:48 -04001551
1552 if (mCallbacks == null) {
1553 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001554 }
Joe Onorato36115782010-06-17 13:28:48 -04001555
1556 final Callbacks callbacks = mCallbacks.get();
1557 if (callbacks != oldCallbacks) {
1558 return null;
1559 }
1560 if (callbacks == null) {
1561 Log.w(TAG, "no mCallbacks");
1562 return null;
1563 }
1564
1565 return callbacks;
1566 }
1567 }
1568
Winson Chungc763c4e2013-07-19 13:49:06 -07001569 private void verifyApplications() {
1570 final Context context = mApp.getContext();
1571
1572 // Cross reference all the applications in our apps list with items in the workspace
1573 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001574 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001575 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001576 for (AppInfo app : mBgAllAppsList.data) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001577 tmpInfos = getItemInfoForComponentName(app.componentName);
1578 if (tmpInfos.isEmpty()) {
1579 // We are missing an application icon, so add this to the workspace
1580 added.add(app);
1581 // This is a rare event, so lets log it
1582 Log.e(TAG, "Missing Application on load: " + app);
1583 }
1584 }
1585 }
1586 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001587 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001588 }
1589 }
1590
Joe Onorato36115782010-06-17 13:28:48 -04001591 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001592 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001593 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001594 LauncherAppState app = LauncherAppState.getInstance();
1595 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001596 final int countX = (int) grid.numColumns;
1597 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001598
Adam Cohendcd297f2013-06-18 13:13:40 -07001599 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001600 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001601 // Return early if we detect that an item is under the hotseat button
1602 if (mCallbacks == null ||
1603 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001604 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001605 Log.e(TAG, "Error loading shortcut into hotseat " + item
1606 + " into position (" + item.screenId + ":" + item.cellX + ","
1607 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001608 return false;
1609 }
1610
Dan Sandler295ae182013-12-10 16:05:47 -05001611 final ItemInfo[][] hotseatItems =
1612 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1613
Adam Cohenae4409d2013-11-26 10:34:59 -08001614 if (item.screenId >= grid.numHotseatIcons) {
1615 Log.e(TAG, "Error loading shortcut " + item
1616 + " into hotseat position " + item.screenId
1617 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1618 + ")");
1619 return false;
1620 }
1621
Dan Sandler295ae182013-12-10 16:05:47 -05001622 if (hotseatItems != null) {
1623 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001624 Log.e(TAG, "Error loading shortcut into hotseat " + item
1625 + " into position (" + item.screenId + ":" + item.cellX + ","
1626 + item.cellY + ") occupied by "
1627 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1628 [(int) item.screenId][0]);
1629 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001630 } else {
1631 hotseatItems[(int) item.screenId][0] = item;
1632 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001633 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001634 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001635 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001636 items[(int) item.screenId][0] = item;
1637 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001638 return true;
1639 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001640 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1641 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001642 return true;
1643 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001644
Adam Cohendcd297f2013-06-18 13:13:40 -07001645 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001646 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001647 occupied.put(item.screenId, items);
1648 }
1649
Dan Sandler295ae182013-12-10 16:05:47 -05001650 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001651 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1652 item.cellX < 0 || item.cellY < 0 ||
1653 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1654 Log.e(TAG, "Error loading shortcut " + item
1655 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1656 + item.cellX + "," + item.cellY
1657 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1658 return false;
1659 }
1660
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001661 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001662 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1663 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001664 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001665 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001666 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001667 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001668 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001669 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001670 return false;
1671 }
1672 }
1673 }
1674 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1675 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001676 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001677 }
1678 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001679
Joe Onorato36115782010-06-17 13:28:48 -04001680 return true;
1681 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001682
Winson Chungba9c37f2013-08-30 14:11:37 -07001683 /** Clears all the sBg data structures */
1684 private void clearSBgDataStructures() {
1685 synchronized (sBgLock) {
1686 sBgWorkspaceItems.clear();
1687 sBgAppWidgets.clear();
1688 sBgFolders.clear();
1689 sBgItemsIdMap.clear();
1690 sBgDbIconCache.clear();
1691 sBgWorkspaceScreens.clear();
1692 }
1693 }
1694
Dan Sandlerd5024042014-01-09 15:01:33 -05001695 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001696 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001697 // Log to disk
1698 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1699
Joe Onorato36115782010-06-17 13:28:48 -04001700 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001701
Joe Onorato36115782010-06-17 13:28:48 -04001702 final Context context = mContext;
1703 final ContentResolver contentResolver = context.getContentResolver();
1704 final PackageManager manager = context.getPackageManager();
1705 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1706 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001707
Winson Chung892c74d2013-08-22 16:15:50 -07001708 LauncherAppState app = LauncherAppState.getInstance();
1709 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1710 int countX = (int) grid.numColumns;
1711 int countY = (int) grid.numRows;
1712
Dan Sandlerd5024042014-01-09 15:01:33 -05001713 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1714 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1715 LauncherAppState.getLauncherProvider().deleteDatabase();
1716 }
1717
1718 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1719 // append the user's Launcher2 shortcuts
1720 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1721 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1722 } else {
1723 // Make sure the default workspace is loaded
1724 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1725 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1726 }
Adam Cohene25af792013-06-06 23:08:25 -07001727
Winson Chungc763c4e2013-07-19 13:49:06 -07001728 // Check if we need to do any upgrade-path logic
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001729 // (Includes having just imported default favorites)
Michael Jurka414300a2013-08-27 15:42:35 +02001730 boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001731
Winson Chung9f9f00b2013-11-15 13:27:00 -08001732 // Log to disk
1733 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001734
Winson Chung2abf94d2012-07-18 18:16:38 -07001735 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001736 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001737
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001738 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001739 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001740 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001741 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001742
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001743 // +1 for the hotseat (it can be larger than the workspace)
1744 // Load workspace in reverse order to ensure that latest items are loaded first (and
1745 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001746 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001747
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001748 try {
1749 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1750 final int intentIndex = c.getColumnIndexOrThrow
1751 (LauncherSettings.Favorites.INTENT);
1752 final int titleIndex = c.getColumnIndexOrThrow
1753 (LauncherSettings.Favorites.TITLE);
1754 final int iconTypeIndex = c.getColumnIndexOrThrow(
1755 LauncherSettings.Favorites.ICON_TYPE);
1756 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1757 final int iconPackageIndex = c.getColumnIndexOrThrow(
1758 LauncherSettings.Favorites.ICON_PACKAGE);
1759 final int iconResourceIndex = c.getColumnIndexOrThrow(
1760 LauncherSettings.Favorites.ICON_RESOURCE);
1761 final int containerIndex = c.getColumnIndexOrThrow(
1762 LauncherSettings.Favorites.CONTAINER);
1763 final int itemTypeIndex = c.getColumnIndexOrThrow(
1764 LauncherSettings.Favorites.ITEM_TYPE);
1765 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1766 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001767 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1768 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001769 final int screenIndex = c.getColumnIndexOrThrow(
1770 LauncherSettings.Favorites.SCREEN);
1771 final int cellXIndex = c.getColumnIndexOrThrow
1772 (LauncherSettings.Favorites.CELLX);
1773 final int cellYIndex = c.getColumnIndexOrThrow
1774 (LauncherSettings.Favorites.CELLY);
1775 final int spanXIndex = c.getColumnIndexOrThrow
1776 (LauncherSettings.Favorites.SPANX);
1777 final int spanYIndex = c.getColumnIndexOrThrow(
1778 LauncherSettings.Favorites.SPANY);
1779 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1780 //final int displayModeIndex = c.getColumnIndexOrThrow(
1781 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001782
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001783 ShortcutInfo info;
1784 String intentDescription;
1785 LauncherAppWidgetInfo appWidgetInfo;
1786 int container;
1787 long id;
1788 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001789
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001790 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001791 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001792 try {
1793 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001794
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001795 switch (itemType) {
1796 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1797 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001798 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001799 intentDescription = c.getString(intentIndex);
1800 try {
1801 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001802 ComponentName cn = intent.getComponent();
Winson Chung68fd3c32013-08-30 16:38:00 -07001803 if (cn != null && !isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001804 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001805 // Log the invalid package, and remove it from the db
Winson Chunga0b7e862013-09-05 16:03:15 -07001806 Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
1807 itemsToRemove.add(id);
Winson Chungee055712013-07-30 14:46:24 -07001808 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001809 // If apps can be on external storage, then we just
1810 // leave them for the user to remove (maybe add
1811 // visual treatment to it)
Winson Chung933bae62013-08-29 11:42:30 -07001812 Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001813 }
1814 continue;
1815 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001816 } catch (URISyntaxException e) {
Winson Chung933bae62013-08-29 11:42:30 -07001817 Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001818 continue;
1819 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001820
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001821 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1822 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1823 titleIndex, mLabelCache);
1824 } else {
1825 info = getShortcutInfo(c, context, iconTypeIndex,
1826 iconPackageIndex, iconResourceIndex, iconIndex,
1827 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001828
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001829 // App shortcuts that used to be automatically added to Launcher
1830 // didn't always have the correct intent flags set, so do that
1831 // here
1832 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001833 intent.getCategories() != null &&
1834 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001835 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001836 intent.addFlags(
1837 Intent.FLAG_ACTIVITY_NEW_TASK |
1838 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1839 }
Michael Jurka96879562012-03-22 05:54:33 -07001840 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001841
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001842 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001843 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001844 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001845 container = c.getInt(containerIndex);
1846 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001847 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001848 info.cellX = c.getInt(cellXIndex);
1849 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001850 info.spanX = 1;
1851 info.spanY = 1;
Adam Cohenae4409d2013-11-26 10:34:59 -08001852
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001853 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001854 deleteOnInvalidPlacement.set(false);
1855 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
1856 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001857 itemsToRemove.add(id);
1858 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001859 break;
1860 }
1861
1862 switch (container) {
1863 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1864 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1865 sBgWorkspaceItems.add(info);
1866 break;
1867 default:
1868 // Item is in a user folder
1869 FolderInfo folderInfo =
1870 findOrMakeFolder(sBgFolders, container);
1871 folderInfo.add(info);
1872 break;
1873 }
1874 sBgItemsIdMap.put(info.id, info);
1875
1876 // now that we've loaded everthing re-save it with the
1877 // icon in case it disappears somehow.
1878 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001879 } else {
1880 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 }
1882 break;
1883
1884 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1885 id = c.getLong(idIndex);
1886 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1887
1888 folderInfo.title = c.getString(titleIndex);
1889 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001890 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001891 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001892 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001893 folderInfo.cellX = c.getInt(cellXIndex);
1894 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001895 folderInfo.spanX = 1;
1896 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001897
Daniel Sandler8802e962010-05-26 16:28:16 -04001898 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001899 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001900 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001901 deleteOnInvalidPlacement)) {
1902 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001903 itemsToRemove.add(id);
1904 }
Daniel Sandler8802e962010-05-26 16:28:16 -04001905 break;
1906 }
Winson Chung5f8afe62013-08-12 16:19:28 -07001907
Joe Onorato9c1289c2009-08-17 11:03:03 -04001908 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001909 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1910 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1911 sBgWorkspaceItems.add(folderInfo);
1912 break;
Joe Onorato36115782010-06-17 13:28:48 -04001913 }
Joe Onorato17a89222011-02-08 17:26:11 -08001914
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1916 sBgFolders.put(folderInfo.id, folderInfo);
1917 break;
1918
1919 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1920 // Read all Launcher-specific widget details
1921 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04001922 String savedProvider = c.getString(appWidgetProviderIndex);
1923
Joe Onorato36115782010-06-17 13:28:48 -04001924 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001925
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001926 final AppWidgetProviderInfo provider =
1927 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001928
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001929 if (!isSafeMode && (provider == null || provider.provider == null ||
1930 provider.provider.getPackageName() == null)) {
1931 String log = "Deleting widget that isn't installed anymore: id="
1932 + id + " appWidgetId=" + appWidgetId;
1933 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07001934 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001935 itemsToRemove.add(id);
1936 } else {
1937 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1938 provider.provider);
1939 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001940 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001941 appWidgetInfo.cellX = c.getInt(cellXIndex);
1942 appWidgetInfo.cellY = c.getInt(cellYIndex);
1943 appWidgetInfo.spanX = c.getInt(spanXIndex);
1944 appWidgetInfo.spanY = c.getInt(spanYIndex);
1945 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1946 appWidgetInfo.minSpanX = minSpan[0];
1947 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001948
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001949 container = c.getInt(containerIndex);
1950 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1951 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1952 Log.e(TAG, "Widget found where container != " +
1953 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1954 continue;
1955 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001956
Adam Cohene25af792013-06-06 23:08:25 -07001957 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001958 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001959 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001960 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001961 deleteOnInvalidPlacement)) {
1962 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001963 itemsToRemove.add(id);
1964 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001965 break;
1966 }
Chris Wrenc3919c02013-09-18 09:48:33 -04001967 String providerName = provider.provider.flattenToString();
1968 if (!providerName.equals(savedProvider)) {
1969 ContentValues values = new ContentValues();
1970 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
1971 providerName);
1972 String where = BaseColumns._ID + "= ?";
1973 String[] args = {Integer.toString(c.getInt(idIndex))};
1974 contentResolver.update(contentUri, values, where, args);
1975 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001976 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1977 sBgAppWidgets.add(appWidgetInfo);
1978 }
Joe Onorato36115782010-06-17 13:28:48 -04001979 break;
1980 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001981 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05001982 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001983 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001984 }
1985 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001986 if (c != null) {
1987 c.close();
1988 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001989 }
1990
Winson Chungba9c37f2013-08-30 14:11:37 -07001991 // Break early if we've stopped loading
1992 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001993 clearSBgDataStructures();
1994 return false;
1995 }
1996
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001997 if (itemsToRemove.size() > 0) {
1998 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07001999 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002000 // Remove dead items
2001 for (long id : itemsToRemove) {
2002 if (DEBUG_LOADERS) {
2003 Log.d(TAG, "Removed id = " + id);
2004 }
2005 // Don't notify content observers
2006 try {
2007 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2008 null, null);
2009 } catch (RemoteException e) {
2010 Log.w(TAG, "Could not remove id = " + id);
2011 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002012 }
2013 }
2014
Winson Chungc763c4e2013-07-19 13:49:06 -07002015 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002016 long maxScreenId = 0;
2017 // If we're importing we use the old screen order.
2018 for (ItemInfo item: sBgItemsIdMap.values()) {
2019 long screenId = item.screenId;
2020 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2021 !sBgWorkspaceScreens.contains(screenId)) {
2022 sBgWorkspaceScreens.add(screenId);
2023 if (screenId > maxScreenId) {
2024 maxScreenId = screenId;
2025 }
2026 }
2027 }
2028 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002029 // Log to disk
2030 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2031 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2032 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002033
Michael Jurka414300a2013-08-27 15:42:35 +02002034 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002035 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002036
2037 // Update the max item id after we load an old db
2038 long maxItemId = 0;
2039 // If we're importing we use the old screen order.
2040 for (ItemInfo item: sBgItemsIdMap.values()) {
2041 maxItemId = Math.max(maxItemId, item.id);
2042 }
Michael Jurka414300a2013-08-27 15:42:35 +02002043 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002045 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2046 for (Integer i : orderedScreens.keySet()) {
2047 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002048 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002049 // Log to disk
2050 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2051 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002052
2053 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002054 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002055 for (ItemInfo item: sBgItemsIdMap.values()) {
2056 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002057 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2058 unusedScreens.contains(screenId)) {
2059 unusedScreens.remove(screenId);
2060 }
2061 }
2062
2063 // If there are any empty screens remove them, and update.
2064 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002065 // Log to disk
2066 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2067 TextUtils.join(", ", unusedScreens), true);
2068
Winson Chung933bae62013-08-29 11:42:30 -07002069 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002070 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2071 }
2072 }
2073
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 if (DEBUG_LOADERS) {
2075 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2076 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002077 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002078 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002080
Daniel Sandler566da102013-06-25 23:43:45 -04002081 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002082 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002083 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002084 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 line += " | ";
2086 }
Winson Chung892c74d2013-08-22 16:15:50 -07002087 for (int x = 0; x < countX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002088 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 }
Joe Onorato36115782010-06-17 13:28:48 -04002090 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002092 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002093 }
Joe Onorato36115782010-06-17 13:28:48 -04002094 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002095 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002096 }
2097
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 /** Filters the set of items who are directly or indirectly (via another container) on the
2099 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002100 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002101 ArrayList<ItemInfo> allWorkspaceItems,
2102 ArrayList<ItemInfo> currentScreenItems,
2103 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002104 // Purge any null ItemInfos
2105 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2106 while (iter.hasNext()) {
2107 ItemInfo i = iter.next();
2108 if (i == null) {
2109 iter.remove();
2110 }
2111 }
2112
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002113 // Order the set of items by their containers first, this allows use to walk through the
2114 // list sequentially, build up a list of containers that are in the specified screen,
2115 // as well as all items in those containers.
2116 Set<Long> itemsOnScreen = new HashSet<Long>();
2117 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2118 @Override
2119 public int compare(ItemInfo lhs, ItemInfo rhs) {
2120 return (int) (lhs.container - rhs.container);
2121 }
2122 });
2123 for (ItemInfo info : allWorkspaceItems) {
2124 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002125 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 currentScreenItems.add(info);
2127 itemsOnScreen.add(info.id);
2128 } else {
2129 otherScreenItems.add(info);
2130 }
2131 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2132 currentScreenItems.add(info);
2133 itemsOnScreen.add(info.id);
2134 } else {
2135 if (itemsOnScreen.contains(info.container)) {
2136 currentScreenItems.add(info);
2137 itemsOnScreen.add(info.id);
2138 } else {
2139 otherScreenItems.add(info);
2140 }
2141 }
2142 }
2143 }
2144
2145 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002146 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 ArrayList<LauncherAppWidgetInfo> appWidgets,
2148 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2149 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002150
2151 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002152 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002153 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002154 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002155 currentScreenWidgets.add(widget);
2156 } else {
2157 otherScreenWidgets.add(widget);
2158 }
2159 }
2160 }
2161
2162 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002163 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002164 HashMap<Long, ItemInfo> itemsIdMap,
2165 HashMap<Long, FolderInfo> folders,
2166 HashMap<Long, FolderInfo> currentScreenFolders,
2167 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002168
2169 for (long id : folders.keySet()) {
2170 ItemInfo info = itemsIdMap.get(id);
2171 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002172 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002173 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002174 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002175 currentScreenFolders.put(id, folder);
2176 } else {
2177 otherScreenFolders.put(id, folder);
2178 }
2179 }
2180 }
2181
2182 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2183 * right) */
2184 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002185 final LauncherAppState app = LauncherAppState.getInstance();
2186 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 // XXX: review this
2188 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002189 @Override
2190 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002191 int cellCountX = (int) grid.numColumns;
2192 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002193 int screenOffset = cellCountX * cellCountY;
2194 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002195 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002196 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002197 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002198 rhs.cellY * cellCountX + rhs.cellX);
2199 return (int) (lr - rr);
2200 }
2201 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002202 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002203
Adam Cohendcd297f2013-06-18 13:13:40 -07002204 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2205 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002206 final Runnable r = new Runnable() {
2207 @Override
2208 public void run() {
2209 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2210 if (callbacks != null) {
2211 callbacks.bindScreens(orderedScreens);
2212 }
2213 }
2214 };
2215 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2216 }
2217
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2219 final ArrayList<ItemInfo> workspaceItems,
2220 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2221 final HashMap<Long, FolderInfo> folders,
2222 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002223
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002224 final boolean postOnMainThread = (deferredBindRunnables != null);
2225
2226 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002227 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002229 final int start = i;
2230 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002231 final Runnable r = new Runnable() {
2232 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002233 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002234 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002235 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002236 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2237 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002238 }
2239 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 };
2241 if (postOnMainThread) {
2242 deferredBindRunnables.add(r);
2243 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002244 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 }
Joe Onorato36115782010-06-17 13:28:48 -04002246 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247
2248 // Bind the folders
2249 if (!folders.isEmpty()) {
2250 final Runnable r = new Runnable() {
2251 public void run() {
2252 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2253 if (callbacks != null) {
2254 callbacks.bindFolders(folders);
2255 }
2256 }
2257 };
2258 if (postOnMainThread) {
2259 deferredBindRunnables.add(r);
2260 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002261 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 }
2263 }
2264
2265 // Bind the widgets, one at a time
2266 N = appWidgets.size();
2267 for (int i = 0; i < N; i++) {
2268 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2269 final Runnable r = new Runnable() {
2270 public void run() {
2271 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2272 if (callbacks != null) {
2273 callbacks.bindAppWidget(widget);
2274 }
2275 }
2276 };
2277 if (postOnMainThread) {
2278 deferredBindRunnables.add(r);
2279 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002280 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 }
2282 }
2283 }
2284
2285 /**
2286 * Binds all loaded data to actual views on the main thread.
2287 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002288 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 final long t = SystemClock.uptimeMillis();
2290 Runnable r;
2291
2292 // Don't use these two variables in any of the callback runnables.
2293 // Otherwise we hold a reference to them.
2294 final Callbacks oldCallbacks = mCallbacks.get();
2295 if (oldCallbacks == null) {
2296 // This launcher has exited and nobody bothered to tell us. Just bail.
2297 Log.w(TAG, "LoaderTask running with no launcher");
2298 return;
2299 }
2300
Winson Chung9b9fb962013-11-15 15:39:34 -08002301 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002302 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2303 ArrayList<LauncherAppWidgetInfo> appWidgets =
2304 new ArrayList<LauncherAppWidgetInfo>();
2305 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2306 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002307 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002308 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002309 workspaceItems.addAll(sBgWorkspaceItems);
2310 appWidgets.addAll(sBgAppWidgets);
2311 folders.putAll(sBgFolders);
2312 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002313 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002314 }
2315
Derek Prothro7aff3992013-12-10 14:00:37 -05002316 final boolean isLoadingSynchronously =
2317 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002318 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002319 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002320 if (currScreen >= orderedScreenIds.size()) {
2321 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002322 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002323 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002324 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002325 final long currentScreenId = currentScreen < 0
2326 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002327
2328 // Load all the items that are on the current page first (and in the process, unbind
2329 // all the existing workspace items before we call startBinding() below.
2330 unbindWorkspaceItemsOnMainThread();
2331
2332 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002333 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2334 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2335 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2336 new ArrayList<LauncherAppWidgetInfo>();
2337 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2338 new ArrayList<LauncherAppWidgetInfo>();
2339 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2340 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2341
Winson Chung9b9fb962013-11-15 15:39:34 -08002342 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002343 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002344 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002345 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002346 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002347 otherFolders);
2348 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2349 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2350
2351 // Tell the workspace that we're about to start binding items
2352 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002353 public void run() {
2354 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2355 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002356 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002357 }
2358 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002359 };
Winson Chung81b52252012-08-27 15:34:29 -07002360 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002361
Adam Cohendcd297f2013-06-18 13:13:40 -07002362 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2363
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002364 // Load items on the current page
2365 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2366 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002367 if (isLoadingSynchronously) {
2368 r = new Runnable() {
2369 public void run() {
2370 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002371 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002372 callbacks.onPageBoundSynchronously(currentScreen);
2373 }
2374 }
2375 };
Winson Chung81b52252012-08-27 15:34:29 -07002376 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002377 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002378
Winson Chung4a2afa32012-07-19 14:53:05 -07002379 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2380 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002381 mDeferredBindRunnables.clear();
2382 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002383 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002384
2385 // Tell the workspace that we're done binding items
2386 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002387 public void run() {
2388 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2389 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002390 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002391 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002392
Winson Chung98e030b2012-05-07 16:01:11 -07002393 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002394 if (DEBUG_LOADERS) {
2395 Log.d(TAG, "bound workspace in "
2396 + (SystemClock.uptimeMillis()-t) + "ms");
2397 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002398
2399 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002400 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002401 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002402 if (isLoadingSynchronously) {
2403 mDeferredBindRunnables.add(r);
2404 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002405 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002406 }
Joe Onorato36115782010-06-17 13:28:48 -04002407 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002408
Joe Onorato36115782010-06-17 13:28:48 -04002409 private void loadAndBindAllApps() {
2410 if (DEBUG_LOADERS) {
2411 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2412 }
2413 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002414 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002415 synchronized (LoaderTask.this) {
2416 if (mStopped) {
2417 return;
2418 }
2419 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002420 }
Joe Onorato36115782010-06-17 13:28:48 -04002421 } else {
2422 onlyBindAllApps();
2423 }
2424 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002425
Joe Onorato36115782010-06-17 13:28:48 -04002426 private void onlyBindAllApps() {
2427 final Callbacks oldCallbacks = mCallbacks.get();
2428 if (oldCallbacks == null) {
2429 // This launcher has exited and nobody bothered to tell us. Just bail.
2430 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2431 return;
2432 }
2433
2434 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002435 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002436 final ArrayList<AppInfo> list
2437 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002438 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002439 public void run() {
2440 final long t = SystemClock.uptimeMillis();
2441 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2442 if (callbacks != null) {
2443 callbacks.bindAllApplications(list);
2444 }
2445 if (DEBUG_LOADERS) {
2446 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2447 + (SystemClock.uptimeMillis()-t) + "ms");
2448 }
2449 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002450 };
2451 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002452 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002453 r.run();
2454 } else {
2455 mHandler.post(r);
2456 }
Joe Onorato36115782010-06-17 13:28:48 -04002457 }
2458
Winson Chung64359a52013-07-08 17:17:08 -07002459 private void loadAllApps() {
2460 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002461
Joe Onorato36115782010-06-17 13:28:48 -04002462 final Callbacks oldCallbacks = mCallbacks.get();
2463 if (oldCallbacks == null) {
2464 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002465 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002466 return;
2467 }
2468
Winson Chung64359a52013-07-08 17:17:08 -07002469 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002470 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2471 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2472
Winson Chung64359a52013-07-08 17:17:08 -07002473 // Clear the list of apps
2474 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002475
Winson Chung64359a52013-07-08 17:17:08 -07002476 // Query for the set of apps
2477 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2478 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2479 if (DEBUG_LOADERS) {
2480 Log.d(TAG, "queryIntentActivities took "
2481 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2482 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2483 }
2484 // Fail if we don't have any apps
2485 if (apps == null || apps.isEmpty()) {
2486 return;
2487 }
2488 // Sort the applications by name
2489 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2490 Collections.sort(apps,
2491 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2492 if (DEBUG_LOADERS) {
2493 Log.d(TAG, "sort took "
2494 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002495 }
2496
Winson Chung64359a52013-07-08 17:17:08 -07002497 // Create the ApplicationInfos
Winson Chung64359a52013-07-08 17:17:08 -07002498 for (int i = 0; i < apps.size(); i++) {
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002499 ResolveInfo app = apps.get(i);
Bjorn Bringert1307f632013-10-03 22:31:03 +01002500 // This builds the icon bitmaps.
2501 mBgAllAppsList.add(new AppInfo(packageManager, app,
2502 mIconCache, mLabelCache));
Winson Chung64359a52013-07-08 17:17:08 -07002503 }
2504
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002505 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002506 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2507 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002508
2509 // Post callback on main thread
2510 mHandler.post(new Runnable() {
2511 public void run() {
2512 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002513 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002514 if (callbacks != null) {
2515 callbacks.bindAllApplications(added);
2516 if (DEBUG_LOADERS) {
2517 Log.d(TAG, "bound " + added.size() + " apps in "
2518 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2519 }
2520 } else {
2521 Log.i(TAG, "not binding apps: no Launcher activity");
2522 }
2523 }
2524 });
2525
Joe Onorato36115782010-06-17 13:28:48 -04002526 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002527 Log.d(TAG, "Icons processed in "
2528 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002529 }
2530 }
2531
2532 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002533 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2535 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2536 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2537 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2538 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2539 }
Joe Onorato36115782010-06-17 13:28:48 -04002540 }
2541 }
2542
2543 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002544 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002545 }
2546
2547 private class PackageUpdatedTask implements Runnable {
2548 int mOp;
2549 String[] mPackages;
2550
2551 public static final int OP_NONE = 0;
2552 public static final int OP_ADD = 1;
2553 public static final int OP_UPDATE = 2;
2554 public static final int OP_REMOVE = 3; // uninstlled
2555 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2556
2557
2558 public PackageUpdatedTask(int op, String[] packages) {
2559 mOp = op;
2560 mPackages = packages;
2561 }
2562
2563 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002564 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002565
2566 final String[] packages = mPackages;
2567 final int N = packages.length;
2568 switch (mOp) {
2569 case OP_ADD:
2570 for (int i=0; i<N; i++) {
2571 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002572 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002573 }
2574 break;
2575 case OP_UPDATE:
2576 for (int i=0; i<N; i++) {
2577 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002578 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002579 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002580 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002581 }
2582 break;
2583 case OP_REMOVE:
2584 case OP_UNAVAILABLE:
2585 for (int i=0; i<N; i++) {
2586 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002587 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002588 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002589 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002590 }
2591 break;
2592 }
2593
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002594 ArrayList<AppInfo> added = null;
2595 ArrayList<AppInfo> modified = null;
2596 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002597
Adam Cohen487f7dd2012-06-28 18:12:10 -07002598 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002599 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002600 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002601 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002602 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002603 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002604 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002605 }
Winson Chung5d55f332012-07-16 20:45:03 -07002606 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002607 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002608 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002609 }
2610
Joe Onorato36115782010-06-17 13:28:48 -04002611 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2612 if (callbacks == null) {
2613 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2614 return;
2615 }
2616
2617 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002618 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002619 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002620 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002621 addAndBindAddedWorkspaceApps(context, addedInfos);
2622 } else {
2623 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002624 }
Joe Onorato36115782010-06-17 13:28:48 -04002625 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002626
Joe Onorato36115782010-06-17 13:28:48 -04002627 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002628 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002629
2630 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002631 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002632 ArrayList<ItemInfo> infos =
2633 getItemInfoForComponentName(a.componentName);
2634 for (ItemInfo i : infos) {
2635 if (isShortcutInfoUpdateable(i)) {
2636 ShortcutInfo info = (ShortcutInfo) i;
2637 info.title = a.title.toString();
2638 updateItemInDatabase(context, info);
2639 }
2640 }
2641 }
2642
Joe Onorato36115782010-06-17 13:28:48 -04002643 mHandler.post(new Runnable() {
2644 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002645 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2646 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002647 callbacks.bindAppsUpdated(modifiedFinal);
2648 }
2649 }
2650 });
2651 }
Winson Chung83892cc2013-05-01 16:53:33 -07002652
Winson Chungdf95eb12013-10-16 14:57:07 -07002653 final ArrayList<String> removedPackageNames =
2654 new ArrayList<String>();
2655 if (mOp == OP_REMOVE) {
2656 // Mark all packages in the broadcast to be removed
2657 removedPackageNames.addAll(Arrays.asList(packages));
2658 } else if (mOp == OP_UPDATE) {
2659 // Mark disabled packages in the broadcast to be removed
2660 final PackageManager pm = context.getPackageManager();
2661 for (int i=0; i<N; i++) {
2662 if (isPackageDisabled(pm, packages[i])) {
2663 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002664 }
2665 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002666 }
2667 // Remove all the components associated with this package
2668 for (String pn : removedPackageNames) {
2669 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2670 for (ItemInfo i : infos) {
2671 deleteItemFromDatabase(context, i);
2672 }
2673 }
2674 // Remove all the specific components
2675 for (AppInfo a : removedApps) {
2676 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName);
2677 for (ItemInfo i : infos) {
2678 deleteItemFromDatabase(context, i);
2679 }
2680 }
2681 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2682 // Remove any queued items from the install queue
2683 String spKey = LauncherAppState.getSharedPreferencesKey();
2684 SharedPreferences sp =
2685 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2686 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2687 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002688 mHandler.post(new Runnable() {
2689 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002690 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2691 if (callbacks == cb && cb != null) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002692 callbacks.bindComponentsRemoved(removedPackageNames, removedApps);
Joe Onorato36115782010-06-17 13:28:48 -04002693 }
2694 }
2695 });
Joe Onoratobe386092009-11-17 17:32:16 -08002696 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002697
Michael Jurkac402cd92013-05-20 15:49:32 +02002698 final ArrayList<Object> widgetsAndShortcuts =
2699 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002700 mHandler.post(new Runnable() {
2701 @Override
2702 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002703 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2704 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002705 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002706 }
2707 }
2708 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002709
2710 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002711 mHandler.post(new Runnable() {
2712 public void run() {
2713 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2714 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002715 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002716 }
2717 }
2718 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002719 }
2720 }
2721
Michael Jurkac402cd92013-05-20 15:49:32 +02002722 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2723 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2724 PackageManager packageManager = context.getPackageManager();
2725 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2726 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2727 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2728 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2729 Collections.sort(widgetsAndShortcuts,
2730 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2731 return widgetsAndShortcuts;
2732 }
2733
Adam Cohen556f6132014-01-15 15:18:08 -08002734 private static boolean isPackageDisabled(PackageManager pm, String packageName) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002735 try {
2736 PackageInfo pi = pm.getPackageInfo(packageName, 0);
2737 return !pi.applicationInfo.enabled;
2738 } catch (NameNotFoundException e) {
2739 // Fall through
2740 }
2741 return false;
2742 }
Adam Cohen556f6132014-01-15 15:18:08 -08002743
2744 public static boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002745 if (cn == null) {
2746 return false;
2747 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002748 if (isPackageDisabled(pm, cn.getPackageName())) {
2749 return false;
2750 }
Winson Chungee055712013-07-30 14:46:24 -07002751
2752 try {
Winson Chungba9c37f2013-08-30 14:11:37 -07002753 // Check the activity
Winson Chungdf95eb12013-10-16 14:57:07 -07002754 PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
Winson Chungee055712013-07-30 14:46:24 -07002755 return (pm.getActivityInfo(cn, 0) != null);
2756 } catch (NameNotFoundException e) {
2757 return false;
2758 }
2759 }
2760
Joe Onorato9c1289c2009-08-17 11:03:03 -04002761 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002762 * This is called from the code that adds shortcuts from the intent receiver. This
2763 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002764 */
Joe Onorato56d82912010-03-07 14:32:10 -05002765 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002766 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002767 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002768
Joe Onorato56d82912010-03-07 14:32:10 -05002769 /**
2770 * Make an ShortcutInfo object for a shortcut that is an application.
2771 *
2772 * If c is not null, then it will be used to fill in missing data like the title and icon.
2773 */
2774 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002775 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002776 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002777 final ShortcutInfo info = new ShortcutInfo();
Winson Chung68fd3c32013-08-30 16:38:00 -07002778 if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002779 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002780 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002781 } else {
2782 try {
2783 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2784 info.initFlagsAndFirstInstallTime(pi);
2785 } catch (NameNotFoundException e) {
2786 Log.d(TAG, "getPackInfo failed for package " +
2787 componentName.getPackageName());
2788 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002789 }
2790
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002791 // TODO: See if the PackageManager knows about this case. If it doesn't
2792 // then return null & delete this.
2793
Joe Onorato56d82912010-03-07 14:32:10 -05002794 // the resource -- This may implicitly give us back the fallback icon,
2795 // but don't worry about that. All we're doing with usingFallbackIcon is
2796 // to avoid saving lots of copies of that in the database, and most apps
2797 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002798
2799 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2800 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2801 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002802 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002803 ResolveInfo resolveInfo = null;
2804 ComponentName oldComponent = intent.getComponent();
2805 Intent newIntent = new Intent(intent.getAction(), null);
2806 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2807 newIntent.setPackage(oldComponent.getPackageName());
2808 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2809 for (ResolveInfo i : infos) {
2810 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2811 i.activityInfo.name);
2812 if (cn.equals(oldComponent)) {
2813 resolveInfo = i;
2814 }
2815 }
2816 if (resolveInfo == null) {
2817 resolveInfo = manager.resolveActivity(intent, 0);
2818 }
Joe Onorato56d82912010-03-07 14:32:10 -05002819 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002820 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002821 }
Joe Onorato56d82912010-03-07 14:32:10 -05002822 // the db
2823 if (icon == null) {
2824 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002825 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002826 }
2827 }
2828 // the fallback icon
2829 if (icon == null) {
2830 icon = getFallbackIcon();
2831 info.usingFallbackIcon = true;
2832 }
2833 info.setIcon(icon);
2834
2835 // from the resource
2836 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002837 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2838 if (labelCache != null && labelCache.containsKey(key)) {
2839 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002840 } else {
2841 info.title = resolveInfo.activityInfo.loadLabel(manager);
2842 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002843 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002844 }
2845 }
Joe Onorato56d82912010-03-07 14:32:10 -05002846 }
2847 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002848 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002849 if (c != null) {
2850 info.title = c.getString(titleIndex);
2851 }
2852 }
2853 // fall back to the class name of the activity
2854 if (info.title == null) {
2855 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002856 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002857 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2858 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002859 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002860
Winson Chung64359a52013-07-08 17:17:08 -07002861 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2862 ItemInfoFilter f) {
2863 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2864 for (ItemInfo i : infos) {
2865 if (i instanceof ShortcutInfo) {
2866 ShortcutInfo info = (ShortcutInfo) i;
2867 ComponentName cn = info.intent.getComponent();
2868 if (cn != null && f.filterItem(null, info, cn)) {
2869 filtered.add(info);
2870 }
2871 } else if (i instanceof FolderInfo) {
2872 FolderInfo info = (FolderInfo) i;
2873 for (ShortcutInfo s : info.contents) {
2874 ComponentName cn = s.intent.getComponent();
2875 if (cn != null && f.filterItem(info, s, cn)) {
2876 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002877 }
2878 }
Winson Chung64359a52013-07-08 17:17:08 -07002879 } else if (i instanceof LauncherAppWidgetInfo) {
2880 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2881 ComponentName cn = info.providerName;
2882 if (cn != null && f.filterItem(null, info, cn)) {
2883 filtered.add(info);
2884 }
Winson Chung8a435102012-08-30 17:16:53 -07002885 }
2886 }
Winson Chung64359a52013-07-08 17:17:08 -07002887 return new ArrayList<ItemInfo>(filtered);
2888 }
2889
2890 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
Winson Chung64359a52013-07-08 17:17:08 -07002891 ItemInfoFilter filter = new ItemInfoFilter() {
2892 @Override
2893 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2894 return cn.getPackageName().equals(pn);
2895 }
2896 };
2897 return filterItemInfos(sBgItemsIdMap.values(), filter);
2898 }
2899
2900 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
Winson Chung64359a52013-07-08 17:17:08 -07002901 ItemInfoFilter filter = new ItemInfoFilter() {
2902 @Override
2903 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2904 return cn.equals(cname);
2905 }
2906 };
2907 return filterItemInfos(sBgItemsIdMap.values(), filter);
2908 }
2909
2910 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2911 if (i instanceof ShortcutInfo) {
2912 ShortcutInfo info = (ShortcutInfo) i;
2913 // We need to check for ACTION_MAIN otherwise getComponent() might
2914 // return null for some shortcuts (for instance, for shortcuts to
2915 // web pages.)
2916 Intent intent = info.intent;
2917 ComponentName name = intent.getComponent();
2918 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2919 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2920 return true;
2921 }
2922 }
2923 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002924 }
2925
2926 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002927 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002928 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002929 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002930 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2931 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002932
Joe Onorato56d82912010-03-07 14:32:10 -05002933 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002934 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002935 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002936
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002937 // TODO: If there's an explicit component and we can't install that, delete it.
2938
Joe Onorato56d82912010-03-07 14:32:10 -05002939 info.title = c.getString(titleIndex);
2940
Joe Onorato9c1289c2009-08-17 11:03:03 -04002941 int iconType = c.getInt(iconTypeIndex);
2942 switch (iconType) {
2943 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2944 String packageName = c.getString(iconPackageIndex);
2945 String resourceName = c.getString(iconResourceIndex);
2946 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002947 info.customIcon = false;
2948 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002949 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002950 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002951 if (resources != null) {
2952 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002953 icon = Utilities.createIconBitmap(
2954 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002955 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002956 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002957 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002958 }
Joe Onorato56d82912010-03-07 14:32:10 -05002959 // the db
2960 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002961 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002962 }
2963 // the fallback icon
2964 if (icon == null) {
2965 icon = getFallbackIcon();
2966 info.usingFallbackIcon = true;
2967 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002968 break;
2969 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002970 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002971 if (icon == null) {
2972 icon = getFallbackIcon();
2973 info.customIcon = false;
2974 info.usingFallbackIcon = true;
2975 } else {
2976 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002977 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002978 break;
2979 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002980 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002981 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002982 info.customIcon = false;
2983 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002984 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002985 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002986 return info;
2987 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002988
Michael Jurka931dc972011-08-05 15:08:15 -07002989 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002990 @SuppressWarnings("all") // suppress dead code warning
2991 final boolean debug = false;
2992 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002993 Log.d(TAG, "getIconFromCursor app="
2994 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2995 }
2996 byte[] data = c.getBlob(iconIndex);
2997 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002998 return Utilities.createIconBitmap(
2999 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003000 } catch (Exception e) {
3001 return null;
3002 }
3003 }
3004
Winson Chung3d503fb2011-07-13 17:25:49 -07003005 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3006 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003007 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003008 if (info == null) {
3009 return null;
3010 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003011 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003012
3013 return info;
3014 }
3015
Winson Chunga9abd0e2010-10-27 17:18:37 -07003016 /**
Winson Chung55cef262010-10-28 14:14:18 -07003017 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3018 */
3019 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3020 ComponentName component) {
3021 List<AppWidgetProviderInfo> widgets =
3022 AppWidgetManager.getInstance(context).getInstalledProviders();
3023 for (AppWidgetProviderInfo info : widgets) {
3024 if (info.provider.equals(component)) {
3025 return info;
3026 }
3027 }
3028 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003029 }
3030
Winson Chung68846fd2010-10-29 11:00:27 -07003031 /**
3032 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3033 */
3034 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3035 final PackageManager packageManager = context.getPackageManager();
3036 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3037 new ArrayList<WidgetMimeTypeHandlerData>();
3038
3039 final Intent supportsIntent =
3040 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3041 supportsIntent.setType(mimeType);
3042
3043 // Create a set of widget configuration components that we can test against
3044 final List<AppWidgetProviderInfo> widgets =
3045 AppWidgetManager.getInstance(context).getInstalledProviders();
3046 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3047 new HashMap<ComponentName, AppWidgetProviderInfo>();
3048 for (AppWidgetProviderInfo info : widgets) {
3049 configurationComponentToWidget.put(info.configure, info);
3050 }
3051
3052 // Run through each of the intents that can handle this type of clip data, and cross
3053 // reference them with the components that are actual configuration components
3054 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3055 PackageManager.MATCH_DEFAULT_ONLY);
3056 for (ResolveInfo info : activities) {
3057 final ActivityInfo activityInfo = info.activityInfo;
3058 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3059 activityInfo.name);
3060 if (configurationComponentToWidget.containsKey(infoComponent)) {
3061 supportedConfigurationActivities.add(
3062 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3063 configurationComponentToWidget.get(infoComponent)));
3064 }
3065 }
3066 return supportedConfigurationActivities;
3067 }
3068
Winson Chunga9abd0e2010-10-27 17:18:37 -07003069 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003070 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3071 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3072 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3073
Adam Cohend9198822011-11-22 16:42:47 -08003074 if (intent == null) {
3075 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3076 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3077 return null;
3078 }
3079
Joe Onorato0589f0f2010-02-08 13:44:00 -08003080 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003081 boolean customIcon = false;
3082 ShortcutIconResource iconResource = null;
3083
3084 if (bitmap != null && bitmap instanceof Bitmap) {
3085 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003086 customIcon = true;
3087 } else {
3088 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3089 if (extra != null && extra instanceof ShortcutIconResource) {
3090 try {
3091 iconResource = (ShortcutIconResource) extra;
3092 final PackageManager packageManager = context.getPackageManager();
3093 Resources resources = packageManager.getResourcesForApplication(
3094 iconResource.packageName);
3095 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003096 icon = Utilities.createIconBitmap(
3097 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003098 } catch (Exception e) {
3099 Log.w(TAG, "Could not load shortcut icon: " + extra);
3100 }
3101 }
3102 }
3103
Michael Jurkac9d95c52011-08-29 14:03:34 -07003104 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003105
3106 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003107 if (fallbackIcon != null) {
3108 icon = fallbackIcon;
3109 } else {
3110 icon = getFallbackIcon();
3111 info.usingFallbackIcon = true;
3112 }
Joe Onorato56d82912010-03-07 14:32:10 -05003113 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003114 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003115
Joe Onorato0589f0f2010-02-08 13:44:00 -08003116 info.title = name;
3117 info.intent = intent;
3118 info.customIcon = customIcon;
3119 info.iconResource = iconResource;
3120
3121 return info;
3122 }
3123
Winson Chungaac01e12011-08-17 10:37:13 -07003124 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3125 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003126 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003127 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003128 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003129 }
Joe Onorato56d82912010-03-07 14:32:10 -05003130 // If this icon doesn't have a custom icon, check to see
3131 // what's stored in the DB, and if it doesn't match what
3132 // we're going to show, store what we are going to show back
3133 // into the DB. We do this so when we're loading, if the
3134 // package manager can't find an icon (for example because
3135 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003136 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003137 cache.put(info, c.getBlob(iconIndex));
3138 return true;
3139 }
3140 return false;
3141 }
3142 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3143 boolean needSave = false;
3144 try {
3145 if (data != null) {
3146 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3147 Bitmap loaded = info.getIcon(mIconCache);
3148 needSave = !saved.sameAs(loaded);
3149 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003150 needSave = true;
3151 }
Winson Chungaac01e12011-08-17 10:37:13 -07003152 } catch (Exception e) {
3153 needSave = true;
3154 }
3155 if (needSave) {
3156 Log.d(TAG, "going to save icon bitmap for info=" + info);
3157 // This is slower than is ideal, but this only happens once
3158 // or when the app is updated with a new icon.
3159 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003160 }
3161 }
3162
Joe Onorato9c1289c2009-08-17 11:03:03 -04003163 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003164 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003165 * or make a new one.
3166 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003167 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003168 // See if a placeholder was created for us already
3169 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003170 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003171 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003172 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003173 folders.put(id, folderInfo);
3174 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003175 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003176 }
3177
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003178 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003179 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003180 return new Comparator<AppInfo>() {
3181 public final int compare(AppInfo a, AppInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003182 int result = collator.compare(a.title.toString().trim(),
3183 b.title.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003184 if (result == 0) {
3185 result = a.componentName.compareTo(b.componentName);
3186 }
3187 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07003188 }
Winson Chung11904872012-09-17 16:58:46 -07003189 };
3190 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003191 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3192 = new Comparator<AppInfo>() {
3193 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003194 if (a.firstInstallTime < b.firstInstallTime) return 1;
3195 if (a.firstInstallTime > b.firstInstallTime) return -1;
3196 return 0;
3197 }
3198 };
Winson Chung11904872012-09-17 16:58:46 -07003199 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3200 final Collator collator = Collator.getInstance();
3201 return new Comparator<AppWidgetProviderInfo>() {
3202 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003203 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003204 }
3205 };
3206 }
Winson Chung5308f242011-08-18 12:12:41 -07003207 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3208 if (info.activityInfo != null) {
3209 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3210 } else {
3211 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3212 }
3213 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003214 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003215 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003216 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003217 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003218 ShortcutNameComparator(PackageManager pm) {
3219 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003220 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003221 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003222 }
3223 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3224 mPackageManager = pm;
3225 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003226 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003227 }
3228 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003229 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003230 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3231 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3232 if (mLabelCache.containsKey(keyA)) {
3233 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003234 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003235 labelA = a.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003236
Winson Chung5308f242011-08-18 12:12:41 -07003237 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003238 }
Winson Chung5308f242011-08-18 12:12:41 -07003239 if (mLabelCache.containsKey(keyB)) {
3240 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003241 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003242 labelB = b.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003243
Winson Chung5308f242011-08-18 12:12:41 -07003244 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003245 }
Winson Chung11904872012-09-17 16:58:46 -07003246 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003247 }
3248 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003249 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003250 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003251 private PackageManager mPackageManager;
3252 private HashMap<Object, String> mLabelCache;
3253 WidgetAndShortcutNameComparator(PackageManager pm) {
3254 mPackageManager = pm;
3255 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003256 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003257 }
3258 public final int compare(Object a, Object b) {
3259 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003260 if (mLabelCache.containsKey(a)) {
3261 labelA = mLabelCache.get(a);
3262 } else {
3263 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003264 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003265 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003266 mLabelCache.put(a, labelA);
3267 }
3268 if (mLabelCache.containsKey(b)) {
3269 labelB = mLabelCache.get(b);
3270 } else {
3271 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003272 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003273 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003274 mLabelCache.put(b, labelB);
3275 }
Winson Chung11904872012-09-17 16:58:46 -07003276 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003277 }
3278 };
Joe Onoratobe386092009-11-17 17:32:16 -08003279
3280 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003281 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003282 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3283 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3284 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3285 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003286 if (mLoaderTask != null) {
3287 mLoaderTask.dumpState();
3288 } else {
3289 Log.d(TAG, "mLoaderTask=null");
3290 }
Joe Onoratobe386092009-11-17 17:32:16 -08003291 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003292}