blob: 094d4b701b90a4038dd7e111d5c15278c56ebf41 [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>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001739 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001740 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001741 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001742 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001743
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001744 // +1 for the hotseat (it can be larger than the workspace)
1745 // Load workspace in reverse order to ensure that latest items are loaded first (and
1746 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001747 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001748
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001749 try {
1750 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1751 final int intentIndex = c.getColumnIndexOrThrow
1752 (LauncherSettings.Favorites.INTENT);
1753 final int titleIndex = c.getColumnIndexOrThrow
1754 (LauncherSettings.Favorites.TITLE);
1755 final int iconTypeIndex = c.getColumnIndexOrThrow(
1756 LauncherSettings.Favorites.ICON_TYPE);
1757 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1758 final int iconPackageIndex = c.getColumnIndexOrThrow(
1759 LauncherSettings.Favorites.ICON_PACKAGE);
1760 final int iconResourceIndex = c.getColumnIndexOrThrow(
1761 LauncherSettings.Favorites.ICON_RESOURCE);
1762 final int containerIndex = c.getColumnIndexOrThrow(
1763 LauncherSettings.Favorites.CONTAINER);
1764 final int itemTypeIndex = c.getColumnIndexOrThrow(
1765 LauncherSettings.Favorites.ITEM_TYPE);
1766 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1767 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001768 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1769 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001770 final int screenIndex = c.getColumnIndexOrThrow(
1771 LauncherSettings.Favorites.SCREEN);
1772 final int cellXIndex = c.getColumnIndexOrThrow
1773 (LauncherSettings.Favorites.CELLX);
1774 final int cellYIndex = c.getColumnIndexOrThrow
1775 (LauncherSettings.Favorites.CELLY);
1776 final int spanXIndex = c.getColumnIndexOrThrow
1777 (LauncherSettings.Favorites.SPANX);
1778 final int spanYIndex = c.getColumnIndexOrThrow(
1779 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001780 final int restoredIndex = c.getColumnIndexOrThrow(
1781 LauncherSettings.Favorites.RESTORED);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001782 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1783 //final int displayModeIndex = c.getColumnIndexOrThrow(
1784 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001785
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001786 ShortcutInfo info;
1787 String intentDescription;
1788 LauncherAppWidgetInfo appWidgetInfo;
1789 int container;
1790 long id;
1791 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001792
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001793 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001794 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001795 try {
1796 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001797 boolean restored = 0 != c.getInt(restoredIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001798
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001799 switch (itemType) {
1800 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1801 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001802 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001803 intentDescription = c.getString(intentIndex);
1804 try {
1805 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001806 ComponentName cn = intent.getComponent();
Winson Chung68fd3c32013-08-30 16:38:00 -07001807 if (cn != null && !isValidPackageComponent(manager, cn)) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001808 if (restored) {
1809 // might be installed later
1810 Launcher.addDumpLog(TAG,
1811 "package not yet restored: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001812 } else {
Chris Wrenf4d08112014-01-16 18:13:56 -05001813 if (!mAppsCanBeOnRemoveableStorage) {
1814 // Log the invalid package, and remove it
1815 Launcher.addDumpLog(TAG,
1816 "Invalid package removed: " + cn, true);
1817 itemsToRemove.add(id);
1818 } else {
1819 // If apps can be on external storage, then we just
1820 // leave them for the user to remove (maybe add
1821 // visual treatment to it)
1822 Launcher.addDumpLog(TAG,
1823 "Invalid package found: " + cn, true);
1824 }
1825 continue;
Winson Chungee055712013-07-30 14:46:24 -07001826 }
Chris Wrenf4d08112014-01-16 18:13:56 -05001827 } else if (restored) {
1828 // no special handling necessary for this restored item
1829 restoredRows.add(id);
1830 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07001831 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001832 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001833 Launcher.addDumpLog(TAG,
1834 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001835 continue;
1836 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001837
Chris Wrenf4d08112014-01-16 18:13:56 -05001838 if (restored) {
1839 Launcher.addDumpLog(TAG,
1840 "constructing info for partially restored package",
1841 true);
1842 info = getRestoredItemInfo(c, titleIndex);
1843 intent = getRestoredItemIntent(c, context, intent);
1844 } else if (itemType ==
1845 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001846 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1847 titleIndex, mLabelCache);
1848 } else {
1849 info = getShortcutInfo(c, context, iconTypeIndex,
1850 iconPackageIndex, iconResourceIndex, iconIndex,
1851 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001852
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001853 // App shortcuts that used to be automatically added to Launcher
1854 // didn't always have the correct intent flags set, so do that
1855 // here
1856 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001857 intent.getCategories() != null &&
1858 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001859 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001860 intent.addFlags(
1861 Intent.FLAG_ACTIVITY_NEW_TASK |
1862 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1863 }
Michael Jurka96879562012-03-22 05:54:33 -07001864 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001865
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001866 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001867 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001868 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001869 container = c.getInt(containerIndex);
1870 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001871 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001872 info.cellX = c.getInt(cellXIndex);
1873 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001874 info.spanX = 1;
1875 info.spanY = 1;
Adam Cohenae4409d2013-11-26 10:34:59 -08001876
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001877 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001878 deleteOnInvalidPlacement.set(false);
1879 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
1880 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001881 itemsToRemove.add(id);
1882 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 break;
1884 }
1885
1886 switch (container) {
1887 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1888 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1889 sBgWorkspaceItems.add(info);
1890 break;
1891 default:
1892 // Item is in a user folder
1893 FolderInfo folderInfo =
1894 findOrMakeFolder(sBgFolders, container);
1895 folderInfo.add(info);
1896 break;
1897 }
1898 sBgItemsIdMap.put(info.id, info);
1899
1900 // now that we've loaded everthing re-save it with the
1901 // icon in case it disappears somehow.
1902 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001903 } else {
1904 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 }
1906 break;
1907
1908 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1909 id = c.getLong(idIndex);
1910 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1911
1912 folderInfo.title = c.getString(titleIndex);
1913 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001914 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001916 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001917 folderInfo.cellX = c.getInt(cellXIndex);
1918 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001919 folderInfo.spanX = 1;
1920 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001921
Daniel Sandler8802e962010-05-26 16:28:16 -04001922 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001923 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001924 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001925 deleteOnInvalidPlacement)) {
1926 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001927 itemsToRemove.add(id);
1928 }
Daniel Sandler8802e962010-05-26 16:28:16 -04001929 break;
1930 }
Winson Chung5f8afe62013-08-12 16:19:28 -07001931
Joe Onorato9c1289c2009-08-17 11:03:03 -04001932 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001933 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1934 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1935 sBgWorkspaceItems.add(folderInfo);
1936 break;
Joe Onorato36115782010-06-17 13:28:48 -04001937 }
Joe Onorato17a89222011-02-08 17:26:11 -08001938
Chris Wrenf4d08112014-01-16 18:13:56 -05001939 if (restored) {
1940 // no special handling required for restored folders
1941 restoredRows.add(id);
1942 }
1943
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001944 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1945 sBgFolders.put(folderInfo.id, folderInfo);
1946 break;
1947
1948 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1949 // Read all Launcher-specific widget details
1950 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04001951 String savedProvider = c.getString(appWidgetProviderIndex);
1952
Joe Onorato36115782010-06-17 13:28:48 -04001953 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001954
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001955 final AppWidgetProviderInfo provider =
1956 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001957
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001958 if (!isSafeMode && (provider == null || provider.provider == null ||
1959 provider.provider.getPackageName() == null)) {
1960 String log = "Deleting widget that isn't installed anymore: id="
1961 + id + " appWidgetId=" + appWidgetId;
1962 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07001963 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 itemsToRemove.add(id);
1965 } else {
1966 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1967 provider.provider);
1968 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001969 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001970 appWidgetInfo.cellX = c.getInt(cellXIndex);
1971 appWidgetInfo.cellY = c.getInt(cellYIndex);
1972 appWidgetInfo.spanX = c.getInt(spanXIndex);
1973 appWidgetInfo.spanY = c.getInt(spanYIndex);
1974 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1975 appWidgetInfo.minSpanX = minSpan[0];
1976 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001977
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001978 container = c.getInt(containerIndex);
1979 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1980 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1981 Log.e(TAG, "Widget found where container != " +
1982 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1983 continue;
1984 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001985
Adam Cohene25af792013-06-06 23:08:25 -07001986 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001987 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001988 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001989 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001990 deleteOnInvalidPlacement)) {
1991 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001992 itemsToRemove.add(id);
1993 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001994 break;
1995 }
Chris Wrenc3919c02013-09-18 09:48:33 -04001996 String providerName = provider.provider.flattenToString();
1997 if (!providerName.equals(savedProvider)) {
1998 ContentValues values = new ContentValues();
1999 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2000 providerName);
2001 String where = BaseColumns._ID + "= ?";
2002 String[] args = {Integer.toString(c.getInt(idIndex))};
2003 contentResolver.update(contentUri, values, where, args);
2004 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002005 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2006 sBgAppWidgets.add(appWidgetInfo);
2007 }
Joe Onorato36115782010-06-17 13:28:48 -04002008 break;
2009 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002010 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002011 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002012 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002013 }
2014 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002015 if (c != null) {
2016 c.close();
2017 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002018 }
2019
Winson Chungba9c37f2013-08-30 14:11:37 -07002020 // Break early if we've stopped loading
2021 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002022 clearSBgDataStructures();
2023 return false;
2024 }
2025
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002026 if (itemsToRemove.size() > 0) {
2027 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07002028 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002029 // Remove dead items
2030 for (long id : itemsToRemove) {
2031 if (DEBUG_LOADERS) {
2032 Log.d(TAG, "Removed id = " + id);
2033 }
2034 // Don't notify content observers
2035 try {
2036 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2037 null, null);
2038 } catch (RemoteException e) {
2039 Log.w(TAG, "Could not remove id = " + id);
2040 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002041 }
2042 }
2043
Chris Wrenf4d08112014-01-16 18:13:56 -05002044 if (restoredRows.size() > 0) {
2045 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
2046 LauncherSettings.Favorites.CONTENT_URI);
2047 // Update restored items that no longer require special handling
2048 try {
2049 StringBuilder selectionBuilder = new StringBuilder();
2050 selectionBuilder.append(LauncherSettings.Favorites._ID);
2051 selectionBuilder.append(" IN (");
2052 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2053 selectionBuilder.append(")");
2054 ContentValues values = new ContentValues();
2055 values.put(LauncherSettings.Favorites.RESTORED, 0);
2056 updater.update(LauncherSettings.Favorites.CONTENT_URI,
2057 values, selectionBuilder.toString(), null);
2058 } catch (RemoteException e) {
2059 Log.w(TAG, "Could not update restored rows");
2060 }
2061 }
2062
Winson Chungc763c4e2013-07-19 13:49:06 -07002063 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002064 long maxScreenId = 0;
2065 // If we're importing we use the old screen order.
2066 for (ItemInfo item: sBgItemsIdMap.values()) {
2067 long screenId = item.screenId;
2068 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2069 !sBgWorkspaceScreens.contains(screenId)) {
2070 sBgWorkspaceScreens.add(screenId);
2071 if (screenId > maxScreenId) {
2072 maxScreenId = screenId;
2073 }
2074 }
2075 }
2076 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002077 // Log to disk
2078 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2079 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2080 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002081
Michael Jurka414300a2013-08-27 15:42:35 +02002082 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002083 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002084
2085 // Update the max item id after we load an old db
2086 long maxItemId = 0;
2087 // If we're importing we use the old screen order.
2088 for (ItemInfo item: sBgItemsIdMap.values()) {
2089 maxItemId = Math.max(maxItemId, item.id);
2090 }
Michael Jurka414300a2013-08-27 15:42:35 +02002091 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002092 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002093 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2094 for (Integer i : orderedScreens.keySet()) {
2095 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002096 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002097 // Log to disk
2098 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2099 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002100
2101 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002102 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002103 for (ItemInfo item: sBgItemsIdMap.values()) {
2104 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002105 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2106 unusedScreens.contains(screenId)) {
2107 unusedScreens.remove(screenId);
2108 }
2109 }
2110
2111 // If there are any empty screens remove them, and update.
2112 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002113 // Log to disk
2114 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2115 TextUtils.join(", ", unusedScreens), true);
2116
Winson Chung933bae62013-08-29 11:42:30 -07002117 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002118 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2119 }
2120 }
2121
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 if (DEBUG_LOADERS) {
2123 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2124 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002125 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002126 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002127 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002128
Daniel Sandler566da102013-06-25 23:43:45 -04002129 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002130 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002131 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002132 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002133 line += " | ";
2134 }
Winson Chung892c74d2013-08-22 16:15:50 -07002135 for (int x = 0; x < countX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002136 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 }
Joe Onorato36115782010-06-17 13:28:48 -04002138 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002139 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002140 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002141 }
Joe Onorato36115782010-06-17 13:28:48 -04002142 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002143 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002144 }
2145
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 /** Filters the set of items who are directly or indirectly (via another container) on the
2147 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002148 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 ArrayList<ItemInfo> allWorkspaceItems,
2150 ArrayList<ItemInfo> currentScreenItems,
2151 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002152 // Purge any null ItemInfos
2153 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2154 while (iter.hasNext()) {
2155 ItemInfo i = iter.next();
2156 if (i == null) {
2157 iter.remove();
2158 }
2159 }
2160
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002161 // Order the set of items by their containers first, this allows use to walk through the
2162 // list sequentially, build up a list of containers that are in the specified screen,
2163 // as well as all items in those containers.
2164 Set<Long> itemsOnScreen = new HashSet<Long>();
2165 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2166 @Override
2167 public int compare(ItemInfo lhs, ItemInfo rhs) {
2168 return (int) (lhs.container - rhs.container);
2169 }
2170 });
2171 for (ItemInfo info : allWorkspaceItems) {
2172 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002173 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002174 currentScreenItems.add(info);
2175 itemsOnScreen.add(info.id);
2176 } else {
2177 otherScreenItems.add(info);
2178 }
2179 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2180 currentScreenItems.add(info);
2181 itemsOnScreen.add(info.id);
2182 } else {
2183 if (itemsOnScreen.contains(info.container)) {
2184 currentScreenItems.add(info);
2185 itemsOnScreen.add(info.id);
2186 } else {
2187 otherScreenItems.add(info);
2188 }
2189 }
2190 }
2191 }
2192
2193 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002194 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002195 ArrayList<LauncherAppWidgetInfo> appWidgets,
2196 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2197 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002198
2199 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002200 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002201 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002202 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002203 currentScreenWidgets.add(widget);
2204 } else {
2205 otherScreenWidgets.add(widget);
2206 }
2207 }
2208 }
2209
2210 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002211 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002212 HashMap<Long, ItemInfo> itemsIdMap,
2213 HashMap<Long, FolderInfo> folders,
2214 HashMap<Long, FolderInfo> currentScreenFolders,
2215 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216
2217 for (long id : folders.keySet()) {
2218 ItemInfo info = itemsIdMap.get(id);
2219 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002220 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002221 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002222 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223 currentScreenFolders.put(id, folder);
2224 } else {
2225 otherScreenFolders.put(id, folder);
2226 }
2227 }
2228 }
2229
2230 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2231 * right) */
2232 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002233 final LauncherAppState app = LauncherAppState.getInstance();
2234 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002235 // XXX: review this
2236 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002237 @Override
2238 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002239 int cellCountX = (int) grid.numColumns;
2240 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002241 int screenOffset = cellCountX * cellCountY;
2242 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002243 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002244 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002245 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002246 rhs.cellY * cellCountX + rhs.cellX);
2247 return (int) (lr - rr);
2248 }
2249 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002250 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002251
Adam Cohendcd297f2013-06-18 13:13:40 -07002252 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2253 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002254 final Runnable r = new Runnable() {
2255 @Override
2256 public void run() {
2257 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2258 if (callbacks != null) {
2259 callbacks.bindScreens(orderedScreens);
2260 }
2261 }
2262 };
2263 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2264 }
2265
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002266 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2267 final ArrayList<ItemInfo> workspaceItems,
2268 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2269 final HashMap<Long, FolderInfo> folders,
2270 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002271
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002272 final boolean postOnMainThread = (deferredBindRunnables != null);
2273
2274 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002275 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002277 final int start = i;
2278 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002279 final Runnable r = new Runnable() {
2280 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002281 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002282 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002283 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002284 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2285 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002286 }
2287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 };
2289 if (postOnMainThread) {
2290 deferredBindRunnables.add(r);
2291 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002292 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 }
Joe Onorato36115782010-06-17 13:28:48 -04002294 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002295
2296 // Bind the folders
2297 if (!folders.isEmpty()) {
2298 final Runnable r = new Runnable() {
2299 public void run() {
2300 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2301 if (callbacks != null) {
2302 callbacks.bindFolders(folders);
2303 }
2304 }
2305 };
2306 if (postOnMainThread) {
2307 deferredBindRunnables.add(r);
2308 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002309 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002310 }
2311 }
2312
2313 // Bind the widgets, one at a time
2314 N = appWidgets.size();
2315 for (int i = 0; i < N; i++) {
2316 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2317 final Runnable r = new Runnable() {
2318 public void run() {
2319 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2320 if (callbacks != null) {
2321 callbacks.bindAppWidget(widget);
2322 }
2323 }
2324 };
2325 if (postOnMainThread) {
2326 deferredBindRunnables.add(r);
2327 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002328 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002329 }
2330 }
2331 }
2332
2333 /**
2334 * Binds all loaded data to actual views on the main thread.
2335 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002336 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 final long t = SystemClock.uptimeMillis();
2338 Runnable r;
2339
2340 // Don't use these two variables in any of the callback runnables.
2341 // Otherwise we hold a reference to them.
2342 final Callbacks oldCallbacks = mCallbacks.get();
2343 if (oldCallbacks == null) {
2344 // This launcher has exited and nobody bothered to tell us. Just bail.
2345 Log.w(TAG, "LoaderTask running with no launcher");
2346 return;
2347 }
2348
Winson Chung9b9fb962013-11-15 15:39:34 -08002349 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002350 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2351 ArrayList<LauncherAppWidgetInfo> appWidgets =
2352 new ArrayList<LauncherAppWidgetInfo>();
2353 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2354 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002356 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 workspaceItems.addAll(sBgWorkspaceItems);
2358 appWidgets.addAll(sBgAppWidgets);
2359 folders.putAll(sBgFolders);
2360 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002361 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 }
2363
Derek Prothro7aff3992013-12-10 14:00:37 -05002364 final boolean isLoadingSynchronously =
2365 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002366 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002367 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002368 if (currScreen >= orderedScreenIds.size()) {
2369 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002370 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002371 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002372 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002373 final long currentScreenId = currentScreen < 0
2374 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002375
2376 // Load all the items that are on the current page first (and in the process, unbind
2377 // all the existing workspace items before we call startBinding() below.
2378 unbindWorkspaceItemsOnMainThread();
2379
2380 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002381 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2382 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2383 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2384 new ArrayList<LauncherAppWidgetInfo>();
2385 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2386 new ArrayList<LauncherAppWidgetInfo>();
2387 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2388 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2389
Winson Chung9b9fb962013-11-15 15:39:34 -08002390 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002391 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002392 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002393 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002394 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002395 otherFolders);
2396 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2397 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2398
2399 // Tell the workspace that we're about to start binding items
2400 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002401 public void run() {
2402 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2403 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002404 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002405 }
2406 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002407 };
Winson Chung81b52252012-08-27 15:34:29 -07002408 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002409
Adam Cohendcd297f2013-06-18 13:13:40 -07002410 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2411
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002412 // Load items on the current page
2413 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2414 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002415 if (isLoadingSynchronously) {
2416 r = new Runnable() {
2417 public void run() {
2418 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002419 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002420 callbacks.onPageBoundSynchronously(currentScreen);
2421 }
2422 }
2423 };
Winson Chung81b52252012-08-27 15:34:29 -07002424 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002425 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002426
Winson Chung4a2afa32012-07-19 14:53:05 -07002427 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2428 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 mDeferredBindRunnables.clear();
2430 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002431 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432
2433 // Tell the workspace that we're done binding items
2434 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002435 public void run() {
2436 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2437 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002438 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002439 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440
Winson Chung98e030b2012-05-07 16:01:11 -07002441 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002442 if (DEBUG_LOADERS) {
2443 Log.d(TAG, "bound workspace in "
2444 + (SystemClock.uptimeMillis()-t) + "ms");
2445 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002446
2447 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002448 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002449 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002450 if (isLoadingSynchronously) {
2451 mDeferredBindRunnables.add(r);
2452 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002453 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002454 }
Joe Onorato36115782010-06-17 13:28:48 -04002455 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002456
Joe Onorato36115782010-06-17 13:28:48 -04002457 private void loadAndBindAllApps() {
2458 if (DEBUG_LOADERS) {
2459 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2460 }
2461 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002462 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002463 synchronized (LoaderTask.this) {
2464 if (mStopped) {
2465 return;
2466 }
2467 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002468 }
Joe Onorato36115782010-06-17 13:28:48 -04002469 } else {
2470 onlyBindAllApps();
2471 }
2472 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002473
Joe Onorato36115782010-06-17 13:28:48 -04002474 private void onlyBindAllApps() {
2475 final Callbacks oldCallbacks = mCallbacks.get();
2476 if (oldCallbacks == null) {
2477 // This launcher has exited and nobody bothered to tell us. Just bail.
2478 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2479 return;
2480 }
2481
2482 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002483 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002484 final ArrayList<AppInfo> list
2485 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002486 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002487 public void run() {
2488 final long t = SystemClock.uptimeMillis();
2489 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2490 if (callbacks != null) {
2491 callbacks.bindAllApplications(list);
2492 }
2493 if (DEBUG_LOADERS) {
2494 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2495 + (SystemClock.uptimeMillis()-t) + "ms");
2496 }
2497 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002498 };
2499 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002500 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002501 r.run();
2502 } else {
2503 mHandler.post(r);
2504 }
Joe Onorato36115782010-06-17 13:28:48 -04002505 }
2506
Winson Chung64359a52013-07-08 17:17:08 -07002507 private void loadAllApps() {
2508 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002509
Joe Onorato36115782010-06-17 13:28:48 -04002510 final Callbacks oldCallbacks = mCallbacks.get();
2511 if (oldCallbacks == null) {
2512 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002513 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002514 return;
2515 }
2516
Winson Chung64359a52013-07-08 17:17:08 -07002517 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002518 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2519 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2520
Winson Chung64359a52013-07-08 17:17:08 -07002521 // Clear the list of apps
2522 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002523
Winson Chung64359a52013-07-08 17:17:08 -07002524 // Query for the set of apps
2525 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2526 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2527 if (DEBUG_LOADERS) {
2528 Log.d(TAG, "queryIntentActivities took "
2529 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2530 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2531 }
2532 // Fail if we don't have any apps
2533 if (apps == null || apps.isEmpty()) {
2534 return;
2535 }
2536 // Sort the applications by name
2537 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2538 Collections.sort(apps,
2539 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2540 if (DEBUG_LOADERS) {
2541 Log.d(TAG, "sort took "
2542 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002543 }
2544
Winson Chung64359a52013-07-08 17:17:08 -07002545 // Create the ApplicationInfos
Winson Chung64359a52013-07-08 17:17:08 -07002546 for (int i = 0; i < apps.size(); i++) {
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002547 ResolveInfo app = apps.get(i);
Bjorn Bringert1307f632013-10-03 22:31:03 +01002548 // This builds the icon bitmaps.
2549 mBgAllAppsList.add(new AppInfo(packageManager, app,
2550 mIconCache, mLabelCache));
Winson Chung64359a52013-07-08 17:17:08 -07002551 }
2552
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002553 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002554 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2555 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002556
2557 // Post callback on main thread
2558 mHandler.post(new Runnable() {
2559 public void run() {
2560 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002561 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002562 if (callbacks != null) {
2563 callbacks.bindAllApplications(added);
2564 if (DEBUG_LOADERS) {
2565 Log.d(TAG, "bound " + added.size() + " apps in "
2566 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2567 }
2568 } else {
2569 Log.i(TAG, "not binding apps: no Launcher activity");
2570 }
2571 }
2572 });
2573
Joe Onorato36115782010-06-17 13:28:48 -04002574 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002575 Log.d(TAG, "Icons processed in "
2576 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002577 }
2578 }
2579
2580 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002581 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002582 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2583 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2584 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2585 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2586 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2587 }
Joe Onorato36115782010-06-17 13:28:48 -04002588 }
2589 }
2590
2591 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002592 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002593 }
2594
2595 private class PackageUpdatedTask implements Runnable {
2596 int mOp;
2597 String[] mPackages;
2598
2599 public static final int OP_NONE = 0;
2600 public static final int OP_ADD = 1;
2601 public static final int OP_UPDATE = 2;
2602 public static final int OP_REMOVE = 3; // uninstlled
2603 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2604
2605
2606 public PackageUpdatedTask(int op, String[] packages) {
2607 mOp = op;
2608 mPackages = packages;
2609 }
2610
2611 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002612 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002613
2614 final String[] packages = mPackages;
2615 final int N = packages.length;
2616 switch (mOp) {
2617 case OP_ADD:
2618 for (int i=0; i<N; i++) {
2619 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002620 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002621 }
2622 break;
2623 case OP_UPDATE:
2624 for (int i=0; i<N; i++) {
2625 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002626 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002627 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002628 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002629 }
2630 break;
2631 case OP_REMOVE:
2632 case OP_UNAVAILABLE:
2633 for (int i=0; i<N; i++) {
2634 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002635 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002636 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002637 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002638 }
2639 break;
2640 }
2641
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002642 ArrayList<AppInfo> added = null;
2643 ArrayList<AppInfo> modified = null;
2644 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002645
Adam Cohen487f7dd2012-06-28 18:12:10 -07002646 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002647 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002648 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002649 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002650 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002651 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002652 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002653 }
Winson Chung5d55f332012-07-16 20:45:03 -07002654 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002655 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002656 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002657 }
2658
Joe Onorato36115782010-06-17 13:28:48 -04002659 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2660 if (callbacks == null) {
2661 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2662 return;
2663 }
2664
2665 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002666 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08002667 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002668 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08002669 addAndBindAddedWorkspaceApps(context, addedInfos);
2670 } else {
2671 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07002672 }
Joe Onorato36115782010-06-17 13:28:48 -04002673 }
Adam Cohen76a47a12014-02-05 11:47:43 -08002674
Joe Onorato36115782010-06-17 13:28:48 -04002675 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002676 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002677
2678 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002679 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002680 ArrayList<ItemInfo> infos =
2681 getItemInfoForComponentName(a.componentName);
2682 for (ItemInfo i : infos) {
2683 if (isShortcutInfoUpdateable(i)) {
2684 ShortcutInfo info = (ShortcutInfo) i;
2685 info.title = a.title.toString();
2686 updateItemInDatabase(context, info);
2687 }
2688 }
2689 }
2690
Joe Onorato36115782010-06-17 13:28:48 -04002691 mHandler.post(new Runnable() {
2692 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002693 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2694 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002695 callbacks.bindAppsUpdated(modifiedFinal);
2696 }
2697 }
2698 });
2699 }
Winson Chung83892cc2013-05-01 16:53:33 -07002700
Winson Chungdf95eb12013-10-16 14:57:07 -07002701 final ArrayList<String> removedPackageNames =
2702 new ArrayList<String>();
2703 if (mOp == OP_REMOVE) {
2704 // Mark all packages in the broadcast to be removed
2705 removedPackageNames.addAll(Arrays.asList(packages));
2706 } else if (mOp == OP_UPDATE) {
2707 // Mark disabled packages in the broadcast to be removed
2708 final PackageManager pm = context.getPackageManager();
2709 for (int i=0; i<N; i++) {
2710 if (isPackageDisabled(pm, packages[i])) {
2711 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002712 }
2713 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002714 }
2715 // Remove all the components associated with this package
2716 for (String pn : removedPackageNames) {
2717 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2718 for (ItemInfo i : infos) {
2719 deleteItemFromDatabase(context, i);
2720 }
2721 }
2722 // Remove all the specific components
2723 for (AppInfo a : removedApps) {
2724 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName);
2725 for (ItemInfo i : infos) {
2726 deleteItemFromDatabase(context, i);
2727 }
2728 }
2729 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2730 // Remove any queued items from the install queue
2731 String spKey = LauncherAppState.getSharedPreferencesKey();
2732 SharedPreferences sp =
2733 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2734 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2735 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002736 mHandler.post(new Runnable() {
2737 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002738 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2739 if (callbacks == cb && cb != null) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002740 callbacks.bindComponentsRemoved(removedPackageNames, removedApps);
Joe Onorato36115782010-06-17 13:28:48 -04002741 }
2742 }
2743 });
Joe Onoratobe386092009-11-17 17:32:16 -08002744 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002745
Michael Jurkac402cd92013-05-20 15:49:32 +02002746 final ArrayList<Object> widgetsAndShortcuts =
2747 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002748 mHandler.post(new Runnable() {
2749 @Override
2750 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002751 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2752 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002753 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002754 }
2755 }
2756 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002757
2758 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002759 mHandler.post(new Runnable() {
2760 public void run() {
2761 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2762 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002763 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002764 }
2765 }
2766 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002767 }
2768 }
2769
Michael Jurkac402cd92013-05-20 15:49:32 +02002770 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2771 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2772 PackageManager packageManager = context.getPackageManager();
2773 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2774 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2775 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2776 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2777 Collections.sort(widgetsAndShortcuts,
2778 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2779 return widgetsAndShortcuts;
2780 }
2781
Adam Cohen556f6132014-01-15 15:18:08 -08002782 private static boolean isPackageDisabled(PackageManager pm, String packageName) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002783 try {
2784 PackageInfo pi = pm.getPackageInfo(packageName, 0);
2785 return !pi.applicationInfo.enabled;
2786 } catch (NameNotFoundException e) {
2787 // Fall through
2788 }
2789 return false;
2790 }
Adam Cohen556f6132014-01-15 15:18:08 -08002791
2792 public static boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002793 if (cn == null) {
2794 return false;
2795 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002796 if (isPackageDisabled(pm, cn.getPackageName())) {
2797 return false;
2798 }
Winson Chungee055712013-07-30 14:46:24 -07002799
2800 try {
Winson Chungba9c37f2013-08-30 14:11:37 -07002801 // Check the activity
Winson Chungdf95eb12013-10-16 14:57:07 -07002802 PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
Winson Chungee055712013-07-30 14:46:24 -07002803 return (pm.getActivityInfo(cn, 0) != null);
2804 } catch (NameNotFoundException e) {
2805 return false;
2806 }
2807 }
2808
Joe Onorato9c1289c2009-08-17 11:03:03 -04002809 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05002810 * Make an ShortcutInfo object for a restored application or shortcut item that points
2811 * to a package that is not yet installed on the system.
2812 */
2813 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex) {
2814 final ShortcutInfo info = new ShortcutInfo();
2815 info.usingFallbackIcon = true;
2816 info.setIcon(getFallbackIcon());
2817 if (cursor != null) {
2818 info.title = cursor.getString(titleIndex);
2819 } else {
2820 info.title = "";
2821 }
2822 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
2823 return info;
2824 }
2825
2826 /**
2827 * Make an Intent object for a restored application or shortcut item that points
2828 * to the market page for the item.
2829 */
2830 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
2831 ComponentName componentName = intent.getComponent();
2832 Intent marketIntent = new Intent(Intent.ACTION_VIEW);
2833 Uri marketUri = new Uri.Builder()
2834 .scheme("market")
2835 .authority("details")
2836 .appendQueryParameter("id", componentName.getPackageName())
2837 .build();
2838 Log.d(TAG, "manufactured intent uri: " + marketUri.toString());
2839 marketIntent.setData(marketUri);
2840 return marketIntent;
2841 }
2842
2843 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002844 * This is called from the code that adds shortcuts from the intent receiver. This
2845 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002846 */
Joe Onorato56d82912010-03-07 14:32:10 -05002847 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002848 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002849 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002850
Joe Onorato56d82912010-03-07 14:32:10 -05002851 /**
2852 * Make an ShortcutInfo object for a shortcut that is an application.
2853 *
2854 * If c is not null, then it will be used to fill in missing data like the title and icon.
2855 */
2856 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002857 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002858 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002859 final ShortcutInfo info = new ShortcutInfo();
Winson Chung68fd3c32013-08-30 16:38:00 -07002860 if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002861 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002862 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002863 } else {
2864 try {
2865 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2866 info.initFlagsAndFirstInstallTime(pi);
2867 } catch (NameNotFoundException e) {
2868 Log.d(TAG, "getPackInfo failed for package " +
2869 componentName.getPackageName());
2870 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002871 }
2872
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002873 // TODO: See if the PackageManager knows about this case. If it doesn't
2874 // then return null & delete this.
2875
Joe Onorato56d82912010-03-07 14:32:10 -05002876 // the resource -- This may implicitly give us back the fallback icon,
2877 // but don't worry about that. All we're doing with usingFallbackIcon is
2878 // to avoid saving lots of copies of that in the database, and most apps
2879 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002880
2881 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2882 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2883 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002884 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002885 ResolveInfo resolveInfo = null;
2886 ComponentName oldComponent = intent.getComponent();
2887 Intent newIntent = new Intent(intent.getAction(), null);
2888 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2889 newIntent.setPackage(oldComponent.getPackageName());
2890 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2891 for (ResolveInfo i : infos) {
2892 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2893 i.activityInfo.name);
2894 if (cn.equals(oldComponent)) {
2895 resolveInfo = i;
2896 }
2897 }
2898 if (resolveInfo == null) {
2899 resolveInfo = manager.resolveActivity(intent, 0);
2900 }
Joe Onorato56d82912010-03-07 14:32:10 -05002901 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002902 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002903 }
Joe Onorato56d82912010-03-07 14:32:10 -05002904 // the db
2905 if (icon == null) {
2906 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002907 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002908 }
2909 }
2910 // the fallback icon
2911 if (icon == null) {
2912 icon = getFallbackIcon();
2913 info.usingFallbackIcon = true;
2914 }
2915 info.setIcon(icon);
2916
2917 // from the resource
2918 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002919 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2920 if (labelCache != null && labelCache.containsKey(key)) {
2921 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002922 } else {
2923 info.title = resolveInfo.activityInfo.loadLabel(manager);
2924 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002925 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002926 }
2927 }
Joe Onorato56d82912010-03-07 14:32:10 -05002928 }
2929 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002930 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002931 if (c != null) {
2932 info.title = c.getString(titleIndex);
2933 }
2934 }
2935 // fall back to the class name of the activity
2936 if (info.title == null) {
2937 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002938 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002939 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2940 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002941 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002942
Winson Chung64359a52013-07-08 17:17:08 -07002943 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2944 ItemInfoFilter f) {
2945 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2946 for (ItemInfo i : infos) {
2947 if (i instanceof ShortcutInfo) {
2948 ShortcutInfo info = (ShortcutInfo) i;
2949 ComponentName cn = info.intent.getComponent();
2950 if (cn != null && f.filterItem(null, info, cn)) {
2951 filtered.add(info);
2952 }
2953 } else if (i instanceof FolderInfo) {
2954 FolderInfo info = (FolderInfo) i;
2955 for (ShortcutInfo s : info.contents) {
2956 ComponentName cn = s.intent.getComponent();
2957 if (cn != null && f.filterItem(info, s, cn)) {
2958 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002959 }
2960 }
Winson Chung64359a52013-07-08 17:17:08 -07002961 } else if (i instanceof LauncherAppWidgetInfo) {
2962 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2963 ComponentName cn = info.providerName;
2964 if (cn != null && f.filterItem(null, info, cn)) {
2965 filtered.add(info);
2966 }
Winson Chung8a435102012-08-30 17:16:53 -07002967 }
2968 }
Winson Chung64359a52013-07-08 17:17:08 -07002969 return new ArrayList<ItemInfo>(filtered);
2970 }
2971
2972 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
Winson Chung64359a52013-07-08 17:17:08 -07002973 ItemInfoFilter filter = new ItemInfoFilter() {
2974 @Override
2975 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2976 return cn.getPackageName().equals(pn);
2977 }
2978 };
2979 return filterItemInfos(sBgItemsIdMap.values(), filter);
2980 }
2981
2982 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
Winson Chung64359a52013-07-08 17:17:08 -07002983 ItemInfoFilter filter = new ItemInfoFilter() {
2984 @Override
2985 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2986 return cn.equals(cname);
2987 }
2988 };
2989 return filterItemInfos(sBgItemsIdMap.values(), filter);
2990 }
2991
2992 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2993 if (i instanceof ShortcutInfo) {
2994 ShortcutInfo info = (ShortcutInfo) i;
2995 // We need to check for ACTION_MAIN otherwise getComponent() might
2996 // return null for some shortcuts (for instance, for shortcuts to
2997 // web pages.)
2998 Intent intent = info.intent;
2999 ComponentName name = intent.getComponent();
3000 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
3001 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
3002 return true;
3003 }
3004 }
3005 return false;
Winson Chung8a435102012-08-30 17:16:53 -07003006 }
3007
3008 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003009 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003010 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003011 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003012 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3013 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003014
Joe Onorato56d82912010-03-07 14:32:10 -05003015 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003016 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003017 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003018
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003019 // TODO: If there's an explicit component and we can't install that, delete it.
3020
Joe Onorato56d82912010-03-07 14:32:10 -05003021 info.title = c.getString(titleIndex);
3022
Joe Onorato9c1289c2009-08-17 11:03:03 -04003023 int iconType = c.getInt(iconTypeIndex);
3024 switch (iconType) {
3025 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3026 String packageName = c.getString(iconPackageIndex);
3027 String resourceName = c.getString(iconResourceIndex);
3028 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05003029 info.customIcon = false;
3030 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003031 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003032 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05003033 if (resources != null) {
3034 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003035 icon = Utilities.createIconBitmap(
3036 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003037 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003038 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05003039 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003040 }
Joe Onorato56d82912010-03-07 14:32:10 -05003041 // the db
3042 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003043 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003044 }
3045 // the fallback icon
3046 if (icon == null) {
3047 icon = getFallbackIcon();
3048 info.usingFallbackIcon = true;
3049 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003050 break;
3051 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003052 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003053 if (icon == null) {
3054 icon = getFallbackIcon();
3055 info.customIcon = false;
3056 info.usingFallbackIcon = true;
3057 } else {
3058 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003059 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003060 break;
3061 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08003062 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05003063 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003064 info.customIcon = false;
3065 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003066 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003067 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003068 return info;
3069 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003070
Michael Jurka931dc972011-08-05 15:08:15 -07003071 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003072 @SuppressWarnings("all") // suppress dead code warning
3073 final boolean debug = false;
3074 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003075 Log.d(TAG, "getIconFromCursor app="
3076 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3077 }
3078 byte[] data = c.getBlob(iconIndex);
3079 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003080 return Utilities.createIconBitmap(
3081 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003082 } catch (Exception e) {
3083 return null;
3084 }
3085 }
3086
Winson Chung3d503fb2011-07-13 17:25:49 -07003087 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
3088 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003089 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08003090 if (info == null) {
3091 return null;
3092 }
Winson Chung3d503fb2011-07-13 17:25:49 -07003093 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003094
3095 return info;
3096 }
3097
Winson Chunga9abd0e2010-10-27 17:18:37 -07003098 /**
Winson Chung55cef262010-10-28 14:14:18 -07003099 * Attempts to find an AppWidgetProviderInfo that matches the given component.
3100 */
3101 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
3102 ComponentName component) {
3103 List<AppWidgetProviderInfo> widgets =
3104 AppWidgetManager.getInstance(context).getInstalledProviders();
3105 for (AppWidgetProviderInfo info : widgets) {
3106 if (info.provider.equals(component)) {
3107 return info;
3108 }
3109 }
3110 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003111 }
3112
Winson Chung68846fd2010-10-29 11:00:27 -07003113 /**
3114 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3115 */
3116 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3117 final PackageManager packageManager = context.getPackageManager();
3118 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3119 new ArrayList<WidgetMimeTypeHandlerData>();
3120
3121 final Intent supportsIntent =
3122 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3123 supportsIntent.setType(mimeType);
3124
3125 // Create a set of widget configuration components that we can test against
3126 final List<AppWidgetProviderInfo> widgets =
3127 AppWidgetManager.getInstance(context).getInstalledProviders();
3128 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3129 new HashMap<ComponentName, AppWidgetProviderInfo>();
3130 for (AppWidgetProviderInfo info : widgets) {
3131 configurationComponentToWidget.put(info.configure, info);
3132 }
3133
3134 // Run through each of the intents that can handle this type of clip data, and cross
3135 // reference them with the components that are actual configuration components
3136 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3137 PackageManager.MATCH_DEFAULT_ONLY);
3138 for (ResolveInfo info : activities) {
3139 final ActivityInfo activityInfo = info.activityInfo;
3140 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3141 activityInfo.name);
3142 if (configurationComponentToWidget.containsKey(infoComponent)) {
3143 supportedConfigurationActivities.add(
3144 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3145 configurationComponentToWidget.get(infoComponent)));
3146 }
3147 }
3148 return supportedConfigurationActivities;
3149 }
3150
Winson Chunga9abd0e2010-10-27 17:18:37 -07003151 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003152 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3153 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3154 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3155
Adam Cohend9198822011-11-22 16:42:47 -08003156 if (intent == null) {
3157 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3158 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3159 return null;
3160 }
3161
Joe Onorato0589f0f2010-02-08 13:44:00 -08003162 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003163 boolean customIcon = false;
3164 ShortcutIconResource iconResource = null;
3165
3166 if (bitmap != null && bitmap instanceof Bitmap) {
3167 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003168 customIcon = true;
3169 } else {
3170 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3171 if (extra != null && extra instanceof ShortcutIconResource) {
3172 try {
3173 iconResource = (ShortcutIconResource) extra;
3174 final PackageManager packageManager = context.getPackageManager();
3175 Resources resources = packageManager.getResourcesForApplication(
3176 iconResource.packageName);
3177 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003178 icon = Utilities.createIconBitmap(
3179 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003180 } catch (Exception e) {
3181 Log.w(TAG, "Could not load shortcut icon: " + extra);
3182 }
3183 }
3184 }
3185
Michael Jurkac9d95c52011-08-29 14:03:34 -07003186 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003187
3188 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003189 if (fallbackIcon != null) {
3190 icon = fallbackIcon;
3191 } else {
3192 icon = getFallbackIcon();
3193 info.usingFallbackIcon = true;
3194 }
Joe Onorato56d82912010-03-07 14:32:10 -05003195 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003196 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003197
Joe Onorato0589f0f2010-02-08 13:44:00 -08003198 info.title = name;
3199 info.intent = intent;
3200 info.customIcon = customIcon;
3201 info.iconResource = iconResource;
3202
3203 return info;
3204 }
3205
Winson Chungaac01e12011-08-17 10:37:13 -07003206 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3207 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003208 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003209 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003210 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003211 }
Joe Onorato56d82912010-03-07 14:32:10 -05003212 // If this icon doesn't have a custom icon, check to see
3213 // what's stored in the DB, and if it doesn't match what
3214 // we're going to show, store what we are going to show back
3215 // into the DB. We do this so when we're loading, if the
3216 // package manager can't find an icon (for example because
3217 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003218 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003219 cache.put(info, c.getBlob(iconIndex));
3220 return true;
3221 }
3222 return false;
3223 }
3224 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3225 boolean needSave = false;
3226 try {
3227 if (data != null) {
3228 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3229 Bitmap loaded = info.getIcon(mIconCache);
3230 needSave = !saved.sameAs(loaded);
3231 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003232 needSave = true;
3233 }
Winson Chungaac01e12011-08-17 10:37:13 -07003234 } catch (Exception e) {
3235 needSave = true;
3236 }
3237 if (needSave) {
3238 Log.d(TAG, "going to save icon bitmap for info=" + info);
3239 // This is slower than is ideal, but this only happens once
3240 // or when the app is updated with a new icon.
3241 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003242 }
3243 }
3244
Joe Onorato9c1289c2009-08-17 11:03:03 -04003245 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003246 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003247 * or make a new one.
3248 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003249 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003250 // See if a placeholder was created for us already
3251 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003252 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003253 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003254 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003255 folders.put(id, folderInfo);
3256 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003257 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003258 }
3259
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003260 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003261 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003262 return new Comparator<AppInfo>() {
3263 public final int compare(AppInfo a, AppInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003264 int result = collator.compare(a.title.toString().trim(),
3265 b.title.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003266 if (result == 0) {
3267 result = a.componentName.compareTo(b.componentName);
3268 }
3269 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07003270 }
Winson Chung11904872012-09-17 16:58:46 -07003271 };
3272 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003273 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3274 = new Comparator<AppInfo>() {
3275 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003276 if (a.firstInstallTime < b.firstInstallTime) return 1;
3277 if (a.firstInstallTime > b.firstInstallTime) return -1;
3278 return 0;
3279 }
3280 };
Winson Chung11904872012-09-17 16:58:46 -07003281 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3282 final Collator collator = Collator.getInstance();
3283 return new Comparator<AppWidgetProviderInfo>() {
3284 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003285 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003286 }
3287 };
3288 }
Winson Chung5308f242011-08-18 12:12:41 -07003289 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3290 if (info.activityInfo != null) {
3291 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3292 } else {
3293 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3294 }
3295 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003296 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003297 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003298 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003299 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003300 ShortcutNameComparator(PackageManager pm) {
3301 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003302 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003303 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003304 }
3305 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3306 mPackageManager = pm;
3307 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003308 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003309 }
3310 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003311 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003312 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3313 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3314 if (mLabelCache.containsKey(keyA)) {
3315 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003316 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003317 labelA = a.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003318
Winson Chung5308f242011-08-18 12:12:41 -07003319 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003320 }
Winson Chung5308f242011-08-18 12:12:41 -07003321 if (mLabelCache.containsKey(keyB)) {
3322 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003323 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003324 labelB = b.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003325
Winson Chung5308f242011-08-18 12:12:41 -07003326 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003327 }
Winson Chung11904872012-09-17 16:58:46 -07003328 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003329 }
3330 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003331 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003332 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003333 private PackageManager mPackageManager;
3334 private HashMap<Object, String> mLabelCache;
3335 WidgetAndShortcutNameComparator(PackageManager pm) {
3336 mPackageManager = pm;
3337 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003338 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003339 }
3340 public final int compare(Object a, Object b) {
3341 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003342 if (mLabelCache.containsKey(a)) {
3343 labelA = mLabelCache.get(a);
3344 } else {
3345 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003346 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003347 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003348 mLabelCache.put(a, labelA);
3349 }
3350 if (mLabelCache.containsKey(b)) {
3351 labelB = mLabelCache.get(b);
3352 } else {
3353 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003354 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003355 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003356 mLabelCache.put(b, labelB);
3357 }
Winson Chung11904872012-09-17 16:58:46 -07003358 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003359 }
3360 };
Joe Onoratobe386092009-11-17 17:32:16 -08003361
3362 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003363 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003364 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3365 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3366 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3367 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003368 if (mLoaderTask != null) {
3369 mLoaderTask.dumpState();
3370 } else {
3371 Log.d(TAG, "mLoaderTask=null");
3372 }
Joe Onoratobe386092009-11-17 17:32:16 -08003373 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003374}