blob: 4478e9bbd3a5a2ca27503634bffe0309dac0d778 [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
Winson Chung94d67682013-09-25 16:29:40 -0700295 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps,
296 final ArrayList<AppInfo> allAppsApps) {
Winson Chung997a9232013-07-24 15:33:46 -0700297 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung94d67682013-09-25 16:29:40 -0700298 addAndBindAddedApps(context, workspaceApps, cb, allAppsApps);
Winson Chung997a9232013-07-24 15:33:46 -0700299 }
Winson Chung94d67682013-09-25 16:29:40 -0700300 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps,
Winson Chungfe9d96a2013-11-14 11:30:05 -0800301 final Callbacks callbacks, final ArrayList<AppInfo> allAppsApps) {
302 if (workspaceApps == null || allAppsApps == null) {
303 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
304 }
Winson Chung94d67682013-09-25 16:29:40 -0700305 if (workspaceApps.isEmpty() && allAppsApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700306 return;
Winson Chung997a9232013-07-24 15:33:46 -0700307 }
Winson Chung64359a52013-07-08 17:17:08 -0700308 // Process the newly added applications and add them to the database first
309 Runnable r = new Runnable() {
310 public void run() {
311 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
312 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
313
Winson Chung76828c82013-08-19 15:43:29 -0700314 // Get the list of workspace screens. We need to append to this list and
315 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
316 // called.
317 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
318 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
319 for (Integer i : orderedScreens.keySet()) {
320 long screenId = orderedScreens.get(i);
321 workspaceScreens.add(screenId);
322 }
323
Winson Chung64359a52013-07-08 17:17:08 -0700324 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700325 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700326 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700327 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700328 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700329 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700330
331 // Short-circuit this logic if the icon exists somewhere on the workspace
332 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
333 continue;
334 }
335
Winson Chung87412982013-10-03 18:34:14 -0700336 // Add this icon to the db, creating a new page if necessary. If there
337 // is only the empty page then we just add items to the first page.
338 // Otherwise, we add them to the next pages.
339 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700340 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700341 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700342 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200343 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700344
345 // If we can't find a valid position, then just add a new screen.
346 // This takes time so we need to re-queue the add until the new
347 // page is added. Create as many screens as necessary to satisfy
348 // the startSearchPageIndex.
349 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700350 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700351 while (numPagesToAdd > 0) {
352 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700353 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700354 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700355 addedWorkspaceScreensFinal.add(screenId);
356 numPagesToAdd--;
357 }
Winson Chung76828c82013-08-19 15:43:29 -0700358
Winson Chung64359a52013-07-08 17:17:08 -0700359 // Find the coordinate again
360 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700361 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700362 }
363 if (coords == null) {
364 throw new RuntimeException("Coordinates should not be null");
365 }
366
Winson Chung997a9232013-07-24 15:33:46 -0700367 ShortcutInfo shortcutInfo;
368 if (a instanceof ShortcutInfo) {
369 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200370 } else if (a instanceof AppInfo) {
371 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700372 } else {
373 throw new RuntimeException("Unexpected info type");
374 }
Winson Chung94d67682013-09-25 16:29:40 -0700375
Winson Chung64359a52013-07-08 17:17:08 -0700376 // Add the shortcut to the db
377 addItemToDatabase(context, shortcutInfo,
378 LauncherSettings.Favorites.CONTAINER_DESKTOP,
379 coords.first, coords.second[0], coords.second[1], false);
380 // Save the ShortcutInfo for binding in the workspace
381 addedShortcutsFinal.add(shortcutInfo);
382 }
383 }
384
Winson Chung76828c82013-08-19 15:43:29 -0700385 // Update the workspace screens
386 updateWorkspaceScreenOrder(context, workspaceScreens);
387
Winson Chung94d67682013-09-25 16:29:40 -0700388 if (!addedShortcutsFinal.isEmpty() || !allAppsApps.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700389 runOnMainThread(new Runnable() {
390 public void run() {
391 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
392 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700393 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
394 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700395 if (!addedShortcutsFinal.isEmpty()) {
396 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
397 long lastScreenId = info.screenId;
398 for (ItemInfo i : addedShortcutsFinal) {
399 if (i.screenId == lastScreenId) {
400 addAnimated.add(i);
401 } else {
402 addNotAnimated.add(i);
403 }
Winson Chung997a9232013-07-24 15:33:46 -0700404 }
405 }
Winson Chungd64d1762013-08-20 14:37:16 -0700406 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Winson Chung94d67682013-09-25 16:29:40 -0700407 addNotAnimated, addAnimated, allAppsApps);
Winson Chung997a9232013-07-24 15:33:46 -0700408 }
Winson Chung64359a52013-07-08 17:17:08 -0700409 }
Winson Chung997a9232013-07-24 15:33:46 -0700410 });
411 }
Winson Chung64359a52013-07-08 17:17:08 -0700412 }
413 };
414 runOnWorkerThread(r);
415 }
416
Joe Onorato56d82912010-03-07 14:32:10 -0500417 public Bitmap getFallbackIcon() {
Winson Chung5801ef02013-10-16 13:46:28 -0700418 if (mDefaultIcon == null) {
419 final Context context = LauncherAppState.getInstance().getContext();
420 mDefaultIcon = Utilities.createIconBitmap(
421 mIconCache.getFullResDefaultActivityIcon(), context);
422 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800423 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400424 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425
Winson Chung81b52252012-08-27 15:34:29 -0700426 public void unbindItemInfosAndClearQueuedBindRunnables() {
427 if (sWorkerThread.getThreadId() == Process.myTid()) {
428 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
429 "main thread");
430 }
431
432 // Clear any deferred bind runnables
433 mDeferredBindRunnables.clear();
434 // Remove any queued bind runnables
435 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
436 // Unbind all the workspace items
437 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700438 }
439
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700440 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700441 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700442 // Ensure that we don't use the same workspace items data structure on the main thread
443 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700444 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
445 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700446 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700447 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
448 tmpAppWidgets.addAll(sBgAppWidgets);
449 }
450 Runnable r = new Runnable() {
451 @Override
452 public void run() {
453 for (ItemInfo item : tmpWorkspaceItems) {
454 item.unbind();
455 }
456 for (ItemInfo item : tmpAppWidgets) {
457 item.unbind();
458 }
459 }
460 };
461 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700462 }
463
Joe Onorato9c1289c2009-08-17 11:03:03 -0400464 /**
465 * Adds an item to the DB if it was not created previously, or move it to a new
466 * <container, screen, cellX, cellY>
467 */
468 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700469 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400470 if (item.container == ItemInfo.NO_ID) {
471 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700472 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400473 } else {
474 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700475 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800476 }
477 }
478
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700479 static void checkItemInfoLocked(
480 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
481 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
482 if (modelItem != null && item != modelItem) {
483 // check all the data is consistent
484 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
485 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
486 ShortcutInfo shortcut = (ShortcutInfo) item;
487 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
488 modelShortcut.intent.filterEquals(shortcut.intent) &&
489 modelShortcut.id == shortcut.id &&
490 modelShortcut.itemType == shortcut.itemType &&
491 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700492 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700493 modelShortcut.cellX == shortcut.cellX &&
494 modelShortcut.cellY == shortcut.cellY &&
495 modelShortcut.spanX == shortcut.spanX &&
496 modelShortcut.spanY == shortcut.spanY &&
497 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
498 (modelShortcut.dropPos != null &&
499 shortcut.dropPos != null &&
500 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
501 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
502 // For all intents and purposes, this is the same object
503 return;
504 }
505 }
506
507 // the modelItem needs to match up perfectly with item if our model is
508 // to be consistent with the database-- for now, just require
509 // modelItem == item or the equality check above
510 String msg = "item: " + ((item != null) ? item.toString() : "null") +
511 "modelItem: " +
512 ((modelItem != null) ? modelItem.toString() : "null") +
513 "Error: ItemInfo passed to checkItemInfo doesn't match original";
514 RuntimeException e = new RuntimeException(msg);
515 if (stackTrace != null) {
516 e.setStackTrace(stackTrace);
517 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800518 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700519 }
520 }
521
Michael Jurka816474f2012-06-25 14:49:02 -0700522 static void checkItemInfo(final ItemInfo item) {
523 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
524 final long itemId = item.id;
525 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700526 public void run() {
527 synchronized (sBgLock) {
528 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700529 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700530 }
531 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700532 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700533 }
534
Michael Jurkac9d95c52011-08-29 14:03:34 -0700535 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
536 final ItemInfo item, final String callingFunction) {
537 final long itemId = item.id;
538 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
539 final ContentResolver cr = context.getContentResolver();
540
Adam Cohen487f7dd2012-06-28 18:12:10 -0700541 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700542 Runnable r = new Runnable() {
543 public void run() {
544 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700545 updateItemArrays(item, itemId, stackTrace);
546 }
547 };
548 runOnWorkerThread(r);
549 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700550
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700551 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
552 final ArrayList<ItemInfo> items, final String callingFunction) {
553 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700554
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700555 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
556 Runnable r = new Runnable() {
557 public void run() {
558 ArrayList<ContentProviderOperation> ops =
559 new ArrayList<ContentProviderOperation>();
560 int count = items.size();
561 for (int i = 0; i < count; i++) {
562 ItemInfo item = items.get(i);
563 final long itemId = item.id;
564 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
565 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700566
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700567 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
568 updateItemArrays(item, itemId, stackTrace);
569
570 }
571 try {
572 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
573 } catch (Exception e) {
574 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700575 }
576 }
577 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700578 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700579 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700580
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700581 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
582 // Lock on mBgLock *after* the db operation
583 synchronized (sBgLock) {
584 checkItemInfoLocked(itemId, item, stackTrace);
585
586 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
587 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
588 // Item is in a folder, make sure this folder exists
589 if (!sBgFolders.containsKey(item.container)) {
590 // An items container is being set to a that of an item which is not in
591 // the list of Folders.
592 String msg = "item: " + item + " container being set to: " +
593 item.container + ", not in the list of folders";
594 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700595 }
596 }
597
598 // Items are added/removed from the corresponding FolderInfo elsewhere, such
599 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
600 // that are on the desktop, as appropriate
601 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800602 if (modelItem != null &&
603 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
604 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700605 switch (modelItem.itemType) {
606 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
607 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
608 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
609 if (!sBgWorkspaceItems.contains(modelItem)) {
610 sBgWorkspaceItems.add(modelItem);
611 }
612 break;
613 default:
614 break;
615 }
616 } else {
617 sBgWorkspaceItems.remove(modelItem);
618 }
619 }
620 }
621
Michael Jurkac7700af2013-05-14 20:17:58 +0200622 public void flushWorkerThread() {
623 mFlushingWorkerThread = true;
624 Runnable waiter = new Runnable() {
625 public void run() {
626 synchronized (this) {
627 notifyAll();
628 mFlushingWorkerThread = false;
629 }
630 }
631 };
632
633 synchronized(waiter) {
634 runOnWorkerThread(waiter);
635 if (mLoaderTask != null) {
636 synchronized(mLoaderTask) {
637 mLoaderTask.notify();
638 }
639 }
640 boolean success = false;
641 while (!success) {
642 try {
643 waiter.wait();
644 success = true;
645 } catch (InterruptedException e) {
646 }
647 }
648 }
649 }
650
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400652 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700653 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700654 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700655 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400656 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400657 item.cellX = cellX;
658 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700659
Winson Chung3d503fb2011-07-13 17:25:49 -0700660 // We store hotseat items in canonical form which is this orientation invariant position
661 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700662 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700663 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700664 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700665 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700666 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700667 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400668
669 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400670 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700671 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
672 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400674
Michael Jurkac9d95c52011-08-29 14:03:34 -0700675 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700676 }
677
678 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700679 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
680 * cellX, cellY have already been updated on the ItemInfos.
681 */
682 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
683 final long container, final int screen) {
684
685 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
686 int count = items.size();
687
688 for (int i = 0; i < count; i++) {
689 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700690 item.container = container;
691
692 // We store hotseat items in canonical form which is this orientation invariant position
693 // in the hotseat
694 if (context instanceof Launcher && screen < 0 &&
695 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700696 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700697 item.cellY);
698 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700699 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700700 }
701
702 final ContentValues values = new ContentValues();
703 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
704 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
705 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700706 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700707
708 contentValues.add(values);
709 }
710 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
711 }
712
713 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700714 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800715 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700716 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700717 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700718 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800719 item.cellX = cellX;
720 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700721 item.spanX = spanX;
722 item.spanY = spanY;
723
724 // We store hotseat items in canonical form which is this orientation invariant position
725 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700726 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700727 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700728 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700729 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700730 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700731 }
Adam Cohend4844c32011-02-18 19:25:06 -0800732
Adam Cohend4844c32011-02-18 19:25:06 -0800733 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800734 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700735 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
736 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
737 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
738 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700739 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800740
Michael Jurka816474f2012-06-25 14:49:02 -0700741 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700742 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700743
744 /**
745 * Update an item to the database in a specified container.
746 */
747 static void updateItemInDatabase(Context context, final ItemInfo item) {
748 final ContentValues values = new ContentValues();
749 item.onAddToDatabase(values);
750 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
751 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800752 }
753
754 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 * Returns true if the shortcuts already exists in the database.
756 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400758 static boolean shortcutExists(Context context, String title, Intent intent) {
759 final ContentResolver cr = context.getContentResolver();
760 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
761 new String[] { "title", "intent" }, "title=? and intent=?",
762 new String[] { title, intent.toUri(0) }, null);
763 boolean result = false;
764 try {
765 result = c.moveToFirst();
766 } finally {
767 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800768 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400769 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700770 }
771
Joe Onorato9c1289c2009-08-17 11:03:03 -0400772 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700773 * Returns an ItemInfo array containing all the items in the LauncherModel.
774 * The ItemInfo.id is not set through this function.
775 */
776 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
777 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
778 final ContentResolver cr = context.getContentResolver();
779 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
780 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
781 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
782 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
783
784 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
785 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
786 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
787 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
788 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
789 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
790 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
791
792 try {
793 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700794 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700795 item.cellX = c.getInt(cellXIndex);
796 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700797 item.spanX = Math.max(1, c.getInt(spanXIndex));
798 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700799 item.container = c.getInt(containerIndex);
800 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700801 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700802
803 items.add(item);
804 }
805 } catch (Exception e) {
806 items.clear();
807 } finally {
808 c.close();
809 }
810
811 return items;
812 }
813
814 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400815 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
816 */
817 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
818 final ContentResolver cr = context.getContentResolver();
819 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
820 "_id=? and (itemType=? or itemType=?)",
821 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700822 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700823
Joe Onorato9c1289c2009-08-17 11:03:03 -0400824 try {
825 if (c.moveToFirst()) {
826 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
827 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
828 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
829 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
830 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
831 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800832
Joe Onorato9c1289c2009-08-17 11:03:03 -0400833 FolderInfo folderInfo = null;
834 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700835 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
836 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400837 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700838 }
839
Joe Onorato9c1289c2009-08-17 11:03:03 -0400840 folderInfo.title = c.getString(titleIndex);
841 folderInfo.id = id;
842 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700843 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700844 folderInfo.cellX = c.getInt(cellXIndex);
845 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400846
847 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700848 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400849 } finally {
850 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700851 }
852
853 return null;
854 }
855
Joe Onorato9c1289c2009-08-17 11:03:03 -0400856 /**
857 * Add an item to the database in a specified container. Sets the container, screen, cellX and
858 * cellY fields of the item. Also assigns an ID to the item.
859 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700860 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700861 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400862 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400863 item.cellX = cellX;
864 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700865 // We store hotseat items in canonical form which is this orientation invariant position
866 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700867 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700868 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700869 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700870 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700871 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700872 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400873
874 final ContentValues values = new ContentValues();
875 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400876 item.onAddToDatabase(values);
877
Michael Jurka414300a2013-08-27 15:42:35 +0200878 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700879 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700880 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700881
Michael Jurkac9d95c52011-08-29 14:03:34 -0700882 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700883 public void run() {
884 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
885 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700887 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700888 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700889 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700890 sBgItemsIdMap.put(item.id, item);
891 switch (item.itemType) {
892 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
893 sBgFolders.put(item.id, (FolderInfo) item);
894 // Fall through
895 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
896 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
897 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
898 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
899 sBgWorkspaceItems.add(item);
900 } else {
901 if (!sBgFolders.containsKey(item.container)) {
902 // Adding an item to a folder that doesn't exist.
903 String msg = "adding item: " + item + " to a folder that " +
904 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700905 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700906 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700907 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700908 break;
909 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
910 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
911 break;
912 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700913 }
914 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700915 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700916 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700917 }
918
Joe Onorato9c1289c2009-08-17 11:03:03 -0400919 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700920 * Creates a new unique child id, for a given cell span across all layouts.
921 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700922 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700923 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700924 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700925 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700926 }
927
Winson Chungaafa03c2010-06-11 17:34:16 -0700928 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700929 * Removes the specified item from the database
930 * @param context
931 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400932 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700933 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400934 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700935 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700936
Michael Jurka83df1882011-08-31 20:59:26 -0700937 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700938 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700939 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700940
941 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700942 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700943 switch (item.itemType) {
944 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
945 sBgFolders.remove(item.id);
946 for (ItemInfo info: sBgItemsIdMap.values()) {
947 if (info.container == item.id) {
948 // We are deleting a folder which still contains items that
949 // think they are contained by that folder.
950 String msg = "deleting a folder (" + item + ") which still " +
951 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700952 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700953 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700954 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700955 sBgWorkspaceItems.remove(item);
956 break;
957 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
958 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
959 sBgWorkspaceItems.remove(item);
960 break;
961 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
962 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
963 break;
964 }
965 sBgItemsIdMap.remove(item.id);
966 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700967 }
968 }
Michael Jurka83df1882011-08-31 20:59:26 -0700969 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700970 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 }
972
973 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700974 * Update the order of the workspace screens in the database. The array list contains
975 * a list of screen ids in the order that they should appear.
976 */
Winson Chungc9168342013-06-26 14:54:55 -0700977 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -0800978 // Log to disk
979 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
980 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
981
Winson Chung64359a52013-07-08 17:17:08 -0700982 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 final ContentResolver cr = context.getContentResolver();
984 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
985
986 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700987 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 while (iter.hasNext()) {
989 long id = iter.next();
990 if (id < 0) {
991 iter.remove();
992 }
993 }
994
995 Runnable r = new Runnable() {
996 @Override
997 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 // Clear the table
999 cr.delete(uri, null, null);
Winson Chung76828c82013-08-19 15:43:29 -07001000 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 ContentValues[] values = new ContentValues[count];
1002 for (int i = 0; i < count; i++) {
1003 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001004 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1006 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 values[i] = v;
1008 }
1009 cr.bulkInsert(uri, values);
Winson Chung9e6a0a22013-08-27 11:58:12 -07001010
Winson Chungba9c37f2013-08-30 14:11:37 -07001011 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001012 sBgWorkspaceScreens.clear();
1013 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001014 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001015 }
1016 };
1017 runOnWorkerThread(r);
1018 }
1019
1020 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001021 * Remove the contents of the specified folder from the database
1022 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001023 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001024 final ContentResolver cr = context.getContentResolver();
1025
Michael Jurkac9d95c52011-08-29 14:03:34 -07001026 Runnable r = new Runnable() {
1027 public void run() {
1028 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001029 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001030 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001031 sBgItemsIdMap.remove(info.id);
1032 sBgFolders.remove(info.id);
1033 sBgDbIconCache.remove(info);
1034 sBgWorkspaceItems.remove(info);
1035 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036
Michael Jurkac9d95c52011-08-29 14:03:34 -07001037 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1038 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001040 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 for (ItemInfo childInfo : info.contents) {
1042 sBgItemsIdMap.remove(childInfo.id);
1043 sBgDbIconCache.remove(childInfo);
1044 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001045 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001046 }
1047 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001048 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001049 }
1050
1051 /**
1052 * Set this as the current Launcher activity object for the loader.
1053 */
1054 public void initialize(Callbacks callbacks) {
1055 synchronized (mLock) {
1056 mCallbacks = new WeakReference<Callbacks>(callbacks);
1057 }
1058 }
1059
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001060 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001061 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1062 * ACTION_PACKAGE_CHANGED.
1063 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001064 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001065 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001066 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001067
Joe Onorato36115782010-06-17 13:28:48 -04001068 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001069
Joe Onorato36115782010-06-17 13:28:48 -04001070 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1071 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1072 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1073 final String packageName = intent.getData().getSchemeSpecificPart();
1074 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001075
Joe Onorato36115782010-06-17 13:28:48 -04001076 int op = PackageUpdatedTask.OP_NONE;
1077
1078 if (packageName == null || packageName.length() == 0) {
1079 // they sent us a bad intent
1080 return;
1081 }
1082
1083 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1084 op = PackageUpdatedTask.OP_UPDATE;
1085 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1086 if (!replacing) {
1087 op = PackageUpdatedTask.OP_REMOVE;
1088 }
1089 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1090 // later, we will update the package at this time
1091 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1092 if (!replacing) {
1093 op = PackageUpdatedTask.OP_ADD;
1094 } else {
1095 op = PackageUpdatedTask.OP_UPDATE;
1096 }
1097 }
1098
1099 if (op != PackageUpdatedTask.OP_NONE) {
1100 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1101 }
1102
1103 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001104 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onoratocec58332010-10-07 14:37:40 -04001105 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Winson Chung3ee4a472014-01-06 15:53:37 -08001106 if (!replacing) {
1107 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1108 if (mAppsCanBeOnRemoveableStorage) {
1109 // Only rebind if we support removable storage. It catches the case where
1110 // apps on the external sd card need to be reloaded
1111 startLoaderFromBackground();
1112 }
1113 } else {
1114 // If we are replacing then just update the packages in the list
1115 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1116 packages));
1117 }
Joe Onorato36115782010-06-17 13:28:48 -04001118 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001119 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1120 if (!replacing) {
1121 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1122 enqueuePackageUpdated(new PackageUpdatedTask(
1123 PackageUpdatedTask.OP_UNAVAILABLE, packages));
1124 }
1125 // else, we are replacing the packages, so ignore this event and wait for
1126 // EXTERNAL_APPLICATIONS_AVAILABLE to update the packages at that time
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001127 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001128 // If we have changed locale we need to clear out the labels in all apps/workspace.
1129 forceReload();
1130 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1131 // Check if configuration change was an mcc/mnc change which would affect app resources
1132 // and we would need to clear out the labels in all apps/workspace. Same handling as
1133 // above for ACTION_LOCALE_CHANGED
1134 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001135 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001136 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001137 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001138 forceReload();
1139 }
1140 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001141 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001142 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1143 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001144 if (mCallbacks != null) {
1145 Callbacks callbacks = mCallbacks.get();
1146 if (callbacks != null) {
1147 callbacks.bindSearchablesChanged();
1148 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001149 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001150 }
1151 }
1152
Reena Lee93f824a2011-09-23 17:20:28 -07001153 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001154 resetLoadedState(true, true);
1155
Reena Lee93f824a2011-09-23 17:20:28 -07001156 // Do this here because if the launcher activity is running it will be restarted.
1157 // If it's not running startLoaderFromBackground will merely tell it that it needs
1158 // to reload.
1159 startLoaderFromBackground();
1160 }
1161
Winson Chungf0c6ae02012-03-21 16:10:31 -07001162 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1163 synchronized (mLock) {
1164 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1165 // mWorkspaceLoaded to true later
1166 stopLoaderLocked();
1167 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1168 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1169 }
1170 }
1171
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001172 /**
1173 * When the launcher is in the background, it's possible for it to miss paired
1174 * configuration changes. So whenever we trigger the loader from the background
1175 * tell the launcher that it needs to re-run the loader when it comes back instead
1176 * of doing it now.
1177 */
1178 public void startLoaderFromBackground() {
1179 boolean runLoader = false;
1180 if (mCallbacks != null) {
1181 Callbacks callbacks = mCallbacks.get();
1182 if (callbacks != null) {
1183 // Only actually run the loader if they're not paused.
1184 if (!callbacks.setLoadOnResume()) {
1185 runLoader = true;
1186 }
1187 }
1188 }
1189 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001190 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001191 }
Joe Onorato36115782010-06-17 13:28:48 -04001192 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001193
Reena Lee93f824a2011-09-23 17:20:28 -07001194 // If there is already a loader task running, tell it to stop.
1195 // returns true if isLaunching() was true on the old task
1196 private boolean stopLoaderLocked() {
1197 boolean isLaunching = false;
1198 LoaderTask oldTask = mLoaderTask;
1199 if (oldTask != null) {
1200 if (oldTask.isLaunching()) {
1201 isLaunching = true;
1202 }
1203 oldTask.stopLocked();
1204 }
1205 return isLaunching;
1206 }
1207
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001209 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1210 }
1211
1212 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001213 synchronized (mLock) {
1214 if (DEBUG_LOADERS) {
1215 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1216 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001217
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 // Clear any deferred bind-runnables from the synchronized load process
1219 // We must do this before any loading/binding is scheduled below.
1220 mDeferredBindRunnables.clear();
1221
Joe Onorato36115782010-06-17 13:28:48 -04001222 // Don't bother to start the thread if we know it's not going to do anything
1223 if (mCallbacks != null && mCallbacks.get() != null) {
1224 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001225 // also, don't downgrade isLaunching if we're already running
1226 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001227 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001228 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1229 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001230 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1231 } else {
1232 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1233 sWorker.post(mLoaderTask);
1234 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001235 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001236 }
1237 }
1238
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001239 void bindRemainingSynchronousPages() {
1240 // Post the remaining side pages to be loaded
1241 if (!mDeferredBindRunnables.isEmpty()) {
1242 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001243 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001244 }
1245 mDeferredBindRunnables.clear();
1246 }
1247 }
1248
Joe Onorato36115782010-06-17 13:28:48 -04001249 public void stopLoader() {
1250 synchronized (mLock) {
1251 if (mLoaderTask != null) {
1252 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001253 }
1254 }
Joe Onorato36115782010-06-17 13:28:48 -04001255 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001256
Winson Chung76828c82013-08-19 15:43:29 -07001257 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1258 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1259 final ContentResolver contentResolver = context.getContentResolver();
1260 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1261 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1262 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1263
1264 try {
1265 final int idIndex = sc.getColumnIndexOrThrow(
1266 LauncherSettings.WorkspaceScreens._ID);
1267 final int rankIndex = sc.getColumnIndexOrThrow(
1268 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1269 while (sc.moveToNext()) {
1270 try {
1271 long screenId = sc.getLong(idIndex);
1272 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001273 orderedScreens.put(rank, screenId);
1274 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001275 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001276 }
1277 }
1278 } finally {
1279 sc.close();
1280 }
Winson Chunga90303b2013-11-15 13:05:06 -08001281
1282 // Log to disk
1283 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1284 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1285 for (Integer i : orderedScreens.keySet()) {
1286 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1287 }
1288 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1289 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001290 return orderedScreens;
1291 }
1292
Michael Jurkac57b7a82011-08-09 22:02:20 -07001293 public boolean isAllAppsLoaded() {
1294 return mAllAppsLoaded;
1295 }
1296
Winson Chung36a62fe2012-05-06 18:04:42 -07001297 boolean isLoadingWorkspace() {
1298 synchronized (mLock) {
1299 if (mLoaderTask != null) {
1300 return mLoaderTask.isLoadingWorkspace();
1301 }
1302 }
1303 return false;
1304 }
1305
Joe Onorato36115782010-06-17 13:28:48 -04001306 /**
1307 * Runnable for the thread that loads the contents of the launcher:
1308 * - workspace icons
1309 * - widgets
1310 * - all apps icons
1311 */
1312 private class LoaderTask implements Runnable {
1313 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001314 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001315 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001316 private boolean mStopped;
1317 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001318 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001319
Winson Chungc3eecff2011-07-11 17:44:15 -07001320 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001321
Dan Sandlerd5024042014-01-09 15:01:33 -05001322 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001323 mContext = context;
1324 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001325 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001326 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001327 }
1328
Joe Onorato36115782010-06-17 13:28:48 -04001329 boolean isLaunching() {
1330 return mIsLaunching;
1331 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001332
Winson Chung36a62fe2012-05-06 18:04:42 -07001333 boolean isLoadingWorkspace() {
1334 return mIsLoadingAndBindingWorkspace;
1335 }
1336
Winson Chungc763c4e2013-07-19 13:49:06 -07001337 /** Returns whether this is an upgrade path */
1338 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001339 mIsLoadingAndBindingWorkspace = true;
1340
Joe Onorato36115782010-06-17 13:28:48 -04001341 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001342 if (DEBUG_LOADERS) {
1343 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001344 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001345
Winson Chungc763c4e2013-07-19 13:49:06 -07001346 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001347 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001348 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001349 synchronized (LoaderTask.this) {
1350 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001351 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001352 }
1353 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001354 }
1355 }
1356
Joe Onorato36115782010-06-17 13:28:48 -04001357 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001358 bindWorkspace(-1, isUpgradePath);
1359 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001360 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001361
Joe Onorato36115782010-06-17 13:28:48 -04001362 private void waitForIdle() {
1363 // Wait until the either we're stopped or the other threads are done.
1364 // This way we don't start loading all apps until the workspace has settled
1365 // down.
1366 synchronized (LoaderTask.this) {
1367 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001368
Joe Onorato36115782010-06-17 13:28:48 -04001369 mHandler.postIdle(new Runnable() {
1370 public void run() {
1371 synchronized (LoaderTask.this) {
1372 mLoadAndBindStepFinished = true;
1373 if (DEBUG_LOADERS) {
1374 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001375 }
Joe Onorato36115782010-06-17 13:28:48 -04001376 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001377 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001378 }
Joe Onorato36115782010-06-17 13:28:48 -04001379 });
1380
Michael Jurkac7700af2013-05-14 20:17:58 +02001381 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001382 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001383 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1384 // wait no longer than 1sec at a time
1385 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001386 } catch (InterruptedException ex) {
1387 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001388 }
1389 }
Joe Onorato36115782010-06-17 13:28:48 -04001390 if (DEBUG_LOADERS) {
1391 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001392 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001393 + "ms for previous step to finish binding");
1394 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001395 }
Joe Onorato36115782010-06-17 13:28:48 -04001396 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001397
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001398 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001399 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001400 // Ensure that we have a valid page index to load synchronously
1401 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1402 "valid page index");
1403 }
1404 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1405 // Ensure that we don't try and bind a specified page when the pages have not been
1406 // loaded already (we should load everything asynchronously in that case)
1407 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1408 }
1409 synchronized (mLock) {
1410 if (mIsLoaderTaskRunning) {
1411 // Ensure that we are never running the background loading at this point since
1412 // we also touch the background collections
1413 throw new RuntimeException("Error! Background loading is already running");
1414 }
1415 }
1416
1417 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1418 // data structures, we can't allow any other thread to touch that data, but because
1419 // this call is synchronous, we can get away with not locking).
1420
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001421 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001422 // operations from the previous activity. We need to ensure that all queued operations
1423 // are executed before any synchronous binding work is done.
1424 mHandler.flush();
1425
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001426 // Divide the set of loaded items into those that we are binding synchronously, and
1427 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001428 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001429 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1430 // arise from that.
1431 onlyBindAllApps();
1432 }
1433
Joe Onorato36115782010-06-17 13:28:48 -04001434 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001435 boolean isUpgrade = false;
1436
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001437 synchronized (mLock) {
1438 mIsLoaderTaskRunning = true;
1439 }
Joe Onorato36115782010-06-17 13:28:48 -04001440 // Optimize for end-user experience: if the Launcher is up and // running with the
1441 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1442 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001443 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001444 // Elevate priority when Home launches for the first time to avoid
1445 // starving at boot time. Staring at a blank home is not cool.
1446 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001447 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1448 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001449 android.os.Process.setThreadPriority(mIsLaunching
1450 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1451 }
Winson Chung64359a52013-07-08 17:17:08 -07001452 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001453 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001454
Joe Onorato36115782010-06-17 13:28:48 -04001455 if (mStopped) {
1456 break keep_running;
1457 }
1458
1459 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1460 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001461 synchronized (mLock) {
1462 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001463 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001464 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1465 }
1466 }
Joe Onorato36115782010-06-17 13:28:48 -04001467 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001468
1469 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001470 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1471 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001472
1473 // Restore the default thread priority after we are done loading items
1474 synchronized (mLock) {
1475 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476 }
Joe Onorato36115782010-06-17 13:28:48 -04001477 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001478
Winson Chungaac01e12011-08-17 10:37:13 -07001479 // Update the saved icons if necessary
1480 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001481 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001482 for (Object key : sBgDbIconCache.keySet()) {
1483 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1484 }
1485 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001486 }
Winson Chungaac01e12011-08-17 10:37:13 -07001487
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001488 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001489 // Ensure that all the applications that are in the system are
1490 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001491 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001492 verifyApplications();
1493 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001494 }
1495
Joe Onorato36115782010-06-17 13:28:48 -04001496 // Clear out this reference, otherwise we end up holding it until all of the
1497 // callback runnables are done.
1498 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001499
Joe Onorato36115782010-06-17 13:28:48 -04001500 synchronized (mLock) {
1501 // If we are still the last one to be scheduled, remove ourselves.
1502 if (mLoaderTask == this) {
1503 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001504 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001505 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001506 }
Joe Onorato36115782010-06-17 13:28:48 -04001507 }
1508
1509 public void stopLocked() {
1510 synchronized (LoaderTask.this) {
1511 mStopped = true;
1512 this.notify();
1513 }
1514 }
1515
1516 /**
1517 * Gets the callbacks object. If we've been stopped, or if the launcher object
1518 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1519 * object that was around when the deferred message was scheduled, and if there's
1520 * a new Callbacks object around then also return null. This will save us from
1521 * calling onto it with data that will be ignored.
1522 */
1523 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1524 synchronized (mLock) {
1525 if (mStopped) {
1526 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001527 }
Joe Onorato36115782010-06-17 13:28:48 -04001528
1529 if (mCallbacks == null) {
1530 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001531 }
Joe Onorato36115782010-06-17 13:28:48 -04001532
1533 final Callbacks callbacks = mCallbacks.get();
1534 if (callbacks != oldCallbacks) {
1535 return null;
1536 }
1537 if (callbacks == null) {
1538 Log.w(TAG, "no mCallbacks");
1539 return null;
1540 }
1541
1542 return callbacks;
1543 }
1544 }
1545
Winson Chungc763c4e2013-07-19 13:49:06 -07001546 private void verifyApplications() {
1547 final Context context = mApp.getContext();
1548
1549 // Cross reference all the applications in our apps list with items in the workspace
1550 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001551 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001552 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001553 for (AppInfo app : mBgAllAppsList.data) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001554 tmpInfos = getItemInfoForComponentName(app.componentName);
1555 if (tmpInfos.isEmpty()) {
1556 // We are missing an application icon, so add this to the workspace
1557 added.add(app);
1558 // This is a rare event, so lets log it
1559 Log.e(TAG, "Missing Application on load: " + app);
1560 }
1561 }
1562 }
1563 if (!added.isEmpty()) {
1564 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chungfe9d96a2013-11-14 11:30:05 -08001565 addAndBindAddedApps(context, added, cb, new ArrayList<AppInfo>());
Winson Chungc763c4e2013-07-19 13:49:06 -07001566 }
1567 }
1568
Joe Onorato36115782010-06-17 13:28:48 -04001569 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001570 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001571 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001572 LauncherAppState app = LauncherAppState.getInstance();
1573 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001574 final int countX = (int) grid.numColumns;
1575 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001576
Adam Cohendcd297f2013-06-18 13:13:40 -07001577 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001578 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001579 // Return early if we detect that an item is under the hotseat button
1580 if (mCallbacks == null ||
1581 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001582 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001583 Log.e(TAG, "Error loading shortcut into hotseat " + item
1584 + " into position (" + item.screenId + ":" + item.cellX + ","
1585 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001586 return false;
1587 }
1588
Dan Sandler295ae182013-12-10 16:05:47 -05001589 final ItemInfo[][] hotseatItems =
1590 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1591
Adam Cohenae4409d2013-11-26 10:34:59 -08001592 if (item.screenId >= grid.numHotseatIcons) {
1593 Log.e(TAG, "Error loading shortcut " + item
1594 + " into hotseat position " + item.screenId
1595 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1596 + ")");
1597 return false;
1598 }
1599
Dan Sandler295ae182013-12-10 16:05:47 -05001600 if (hotseatItems != null) {
1601 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001602 Log.e(TAG, "Error loading shortcut into hotseat " + item
1603 + " into position (" + item.screenId + ":" + item.cellX + ","
1604 + item.cellY + ") occupied by "
1605 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1606 [(int) item.screenId][0]);
1607 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001608 } else {
1609 hotseatItems[(int) item.screenId][0] = item;
1610 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001611 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001612 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001613 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001614 items[(int) item.screenId][0] = item;
1615 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001616 return true;
1617 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001618 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1619 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001620 return true;
1621 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001622
Adam Cohendcd297f2013-06-18 13:13:40 -07001623 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001624 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001625 occupied.put(item.screenId, items);
1626 }
1627
Dan Sandler295ae182013-12-10 16:05:47 -05001628 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001629 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1630 item.cellX < 0 || item.cellY < 0 ||
1631 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1632 Log.e(TAG, "Error loading shortcut " + item
1633 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1634 + item.cellX + "," + item.cellY
1635 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1636 return false;
1637 }
1638
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001639 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001640 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1641 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001642 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001643 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001644 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001645 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001646 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001647 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001648 return false;
1649 }
1650 }
1651 }
1652 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1653 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001654 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001655 }
1656 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001657
Joe Onorato36115782010-06-17 13:28:48 -04001658 return true;
1659 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001660
Winson Chungba9c37f2013-08-30 14:11:37 -07001661 /** Clears all the sBg data structures */
1662 private void clearSBgDataStructures() {
1663 synchronized (sBgLock) {
1664 sBgWorkspaceItems.clear();
1665 sBgAppWidgets.clear();
1666 sBgFolders.clear();
1667 sBgItemsIdMap.clear();
1668 sBgDbIconCache.clear();
1669 sBgWorkspaceScreens.clear();
1670 }
1671 }
1672
Dan Sandlerd5024042014-01-09 15:01:33 -05001673 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001674 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001675 // Log to disk
1676 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1677
Joe Onorato36115782010-06-17 13:28:48 -04001678 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001679
Joe Onorato36115782010-06-17 13:28:48 -04001680 final Context context = mContext;
1681 final ContentResolver contentResolver = context.getContentResolver();
1682 final PackageManager manager = context.getPackageManager();
1683 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1684 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001685
Winson Chung892c74d2013-08-22 16:15:50 -07001686 LauncherAppState app = LauncherAppState.getInstance();
1687 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1688 int countX = (int) grid.numColumns;
1689 int countY = (int) grid.numRows;
1690
Dan Sandlerd5024042014-01-09 15:01:33 -05001691 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1692 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1693 LauncherAppState.getLauncherProvider().deleteDatabase();
1694 }
1695
1696 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1697 // append the user's Launcher2 shortcuts
1698 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1699 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1700 } else {
1701 // Make sure the default workspace is loaded
1702 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
1703 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
1704 }
Adam Cohene25af792013-06-06 23:08:25 -07001705
Winson Chungc763c4e2013-07-19 13:49:06 -07001706 // Check if we need to do any upgrade-path logic
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001707 // (Includes having just imported default favorites)
Michael Jurka414300a2013-08-27 15:42:35 +02001708 boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001709
Winson Chung9f9f00b2013-11-15 13:27:00 -08001710 // Log to disk
1711 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001712
Winson Chung2abf94d2012-07-18 18:16:38 -07001713 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001714 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001715
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001716 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001717 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001718 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001719 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001720
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001721 // +1 for the hotseat (it can be larger than the workspace)
1722 // Load workspace in reverse order to ensure that latest items are loaded first (and
1723 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001724 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001725
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001726 try {
1727 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1728 final int intentIndex = c.getColumnIndexOrThrow
1729 (LauncherSettings.Favorites.INTENT);
1730 final int titleIndex = c.getColumnIndexOrThrow
1731 (LauncherSettings.Favorites.TITLE);
1732 final int iconTypeIndex = c.getColumnIndexOrThrow(
1733 LauncherSettings.Favorites.ICON_TYPE);
1734 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1735 final int iconPackageIndex = c.getColumnIndexOrThrow(
1736 LauncherSettings.Favorites.ICON_PACKAGE);
1737 final int iconResourceIndex = c.getColumnIndexOrThrow(
1738 LauncherSettings.Favorites.ICON_RESOURCE);
1739 final int containerIndex = c.getColumnIndexOrThrow(
1740 LauncherSettings.Favorites.CONTAINER);
1741 final int itemTypeIndex = c.getColumnIndexOrThrow(
1742 LauncherSettings.Favorites.ITEM_TYPE);
1743 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1744 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001745 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1746 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001747 final int screenIndex = c.getColumnIndexOrThrow(
1748 LauncherSettings.Favorites.SCREEN);
1749 final int cellXIndex = c.getColumnIndexOrThrow
1750 (LauncherSettings.Favorites.CELLX);
1751 final int cellYIndex = c.getColumnIndexOrThrow
1752 (LauncherSettings.Favorites.CELLY);
1753 final int spanXIndex = c.getColumnIndexOrThrow
1754 (LauncherSettings.Favorites.SPANX);
1755 final int spanYIndex = c.getColumnIndexOrThrow(
1756 LauncherSettings.Favorites.SPANY);
1757 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1758 //final int displayModeIndex = c.getColumnIndexOrThrow(
1759 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001760
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001761 ShortcutInfo info;
1762 String intentDescription;
1763 LauncherAppWidgetInfo appWidgetInfo;
1764 int container;
1765 long id;
1766 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001767
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001768 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001769 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001770 try {
1771 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001772
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001773 switch (itemType) {
1774 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1775 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001776 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001777 intentDescription = c.getString(intentIndex);
1778 try {
1779 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001780 ComponentName cn = intent.getComponent();
Winson Chung68fd3c32013-08-30 16:38:00 -07001781 if (cn != null && !isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001782 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001783 // Log the invalid package, and remove it from the db
Winson Chunga0b7e862013-09-05 16:03:15 -07001784 Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
1785 itemsToRemove.add(id);
Winson Chungee055712013-07-30 14:46:24 -07001786 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001787 // If apps can be on external storage, then we just
1788 // leave them for the user to remove (maybe add
1789 // visual treatment to it)
Winson Chung933bae62013-08-29 11:42:30 -07001790 Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001791 }
1792 continue;
1793 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001794 } catch (URISyntaxException e) {
Winson Chung933bae62013-08-29 11:42:30 -07001795 Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001796 continue;
1797 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001798
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001799 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1800 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1801 titleIndex, mLabelCache);
1802 } else {
1803 info = getShortcutInfo(c, context, iconTypeIndex,
1804 iconPackageIndex, iconResourceIndex, iconIndex,
1805 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001806
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001807 // App shortcuts that used to be automatically added to Launcher
1808 // didn't always have the correct intent flags set, so do that
1809 // here
1810 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001811 intent.getCategories() != null &&
1812 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001813 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001814 intent.addFlags(
1815 Intent.FLAG_ACTIVITY_NEW_TASK |
1816 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1817 }
Michael Jurka96879562012-03-22 05:54:33 -07001818 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001819
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001820 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001821 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001822 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001823 container = c.getInt(containerIndex);
1824 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001825 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001826 info.cellX = c.getInt(cellXIndex);
1827 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001828 info.spanX = 1;
1829 info.spanY = 1;
Adam Cohenae4409d2013-11-26 10:34:59 -08001830
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001831 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001832 deleteOnInvalidPlacement.set(false);
1833 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
1834 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001835 itemsToRemove.add(id);
1836 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001837 break;
1838 }
1839
1840 switch (container) {
1841 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1842 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1843 sBgWorkspaceItems.add(info);
1844 break;
1845 default:
1846 // Item is in a user folder
1847 FolderInfo folderInfo =
1848 findOrMakeFolder(sBgFolders, container);
1849 folderInfo.add(info);
1850 break;
1851 }
1852 sBgItemsIdMap.put(info.id, info);
1853
1854 // now that we've loaded everthing re-save it with the
1855 // icon in case it disappears somehow.
1856 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001857 } else {
1858 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001859 }
1860 break;
1861
1862 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1863 id = c.getLong(idIndex);
1864 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1865
1866 folderInfo.title = c.getString(titleIndex);
1867 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001868 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001869 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001870 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 folderInfo.cellX = c.getInt(cellXIndex);
1872 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001873 folderInfo.spanX = 1;
1874 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001875
Daniel Sandler8802e962010-05-26 16:28:16 -04001876 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001877 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001878 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001879 deleteOnInvalidPlacement)) {
1880 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001881 itemsToRemove.add(id);
1882 }
Daniel Sandler8802e962010-05-26 16:28:16 -04001883 break;
1884 }
Winson Chung5f8afe62013-08-12 16:19:28 -07001885
Joe Onorato9c1289c2009-08-17 11:03:03 -04001886 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1888 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1889 sBgWorkspaceItems.add(folderInfo);
1890 break;
Joe Onorato36115782010-06-17 13:28:48 -04001891 }
Joe Onorato17a89222011-02-08 17:26:11 -08001892
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001893 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1894 sBgFolders.put(folderInfo.id, folderInfo);
1895 break;
1896
1897 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1898 // Read all Launcher-specific widget details
1899 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04001900 String savedProvider = c.getString(appWidgetProviderIndex);
1901
Joe Onorato36115782010-06-17 13:28:48 -04001902 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001903
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001904 final AppWidgetProviderInfo provider =
1905 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001906
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001907 if (!isSafeMode && (provider == null || provider.provider == null ||
1908 provider.provider.getPackageName() == null)) {
1909 String log = "Deleting widget that isn't installed anymore: id="
1910 + id + " appWidgetId=" + appWidgetId;
1911 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07001912 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001913 itemsToRemove.add(id);
1914 } else {
1915 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1916 provider.provider);
1917 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001918 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001919 appWidgetInfo.cellX = c.getInt(cellXIndex);
1920 appWidgetInfo.cellY = c.getInt(cellYIndex);
1921 appWidgetInfo.spanX = c.getInt(spanXIndex);
1922 appWidgetInfo.spanY = c.getInt(spanYIndex);
1923 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1924 appWidgetInfo.minSpanX = minSpan[0];
1925 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001926
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001927 container = c.getInt(containerIndex);
1928 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1929 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1930 Log.e(TAG, "Widget found where container != " +
1931 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1932 continue;
1933 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001934
Adam Cohene25af792013-06-06 23:08:25 -07001935 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001936 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001937 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001938 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001939 deleteOnInvalidPlacement)) {
1940 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001941 itemsToRemove.add(id);
1942 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 break;
1944 }
Chris Wrenc3919c02013-09-18 09:48:33 -04001945 String providerName = provider.provider.flattenToString();
1946 if (!providerName.equals(savedProvider)) {
1947 ContentValues values = new ContentValues();
1948 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
1949 providerName);
1950 String where = BaseColumns._ID + "= ?";
1951 String[] args = {Integer.toString(c.getInt(idIndex))};
1952 contentResolver.update(contentUri, values, where, args);
1953 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001954 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1955 sBgAppWidgets.add(appWidgetInfo);
1956 }
Joe Onorato36115782010-06-17 13:28:48 -04001957 break;
1958 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001959 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05001960 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001961 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001962 }
1963 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001964 if (c != null) {
1965 c.close();
1966 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001967 }
1968
Winson Chungba9c37f2013-08-30 14:11:37 -07001969 // Break early if we've stopped loading
1970 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001971 clearSBgDataStructures();
1972 return false;
1973 }
1974
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001975 if (itemsToRemove.size() > 0) {
1976 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07001977 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001978 // Remove dead items
1979 for (long id : itemsToRemove) {
1980 if (DEBUG_LOADERS) {
1981 Log.d(TAG, "Removed id = " + id);
1982 }
1983 // Don't notify content observers
1984 try {
1985 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1986 null, null);
1987 } catch (RemoteException e) {
1988 Log.w(TAG, "Could not remove id = " + id);
1989 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001990 }
1991 }
1992
Winson Chungc763c4e2013-07-19 13:49:06 -07001993 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001994 long maxScreenId = 0;
1995 // If we're importing we use the old screen order.
1996 for (ItemInfo item: sBgItemsIdMap.values()) {
1997 long screenId = item.screenId;
1998 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1999 !sBgWorkspaceScreens.contains(screenId)) {
2000 sBgWorkspaceScreens.add(screenId);
2001 if (screenId > maxScreenId) {
2002 maxScreenId = screenId;
2003 }
2004 }
2005 }
2006 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002007 // Log to disk
2008 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2009 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2010 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002011
Michael Jurka414300a2013-08-27 15:42:35 +02002012 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002013 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002014
2015 // Update the max item id after we load an old db
2016 long maxItemId = 0;
2017 // If we're importing we use the old screen order.
2018 for (ItemInfo item: sBgItemsIdMap.values()) {
2019 maxItemId = Math.max(maxItemId, item.id);
2020 }
Michael Jurka414300a2013-08-27 15:42:35 +02002021 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002022 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002023 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2024 for (Integer i : orderedScreens.keySet()) {
2025 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002026 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002027 // Log to disk
2028 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2029 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002030
2031 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002032 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002033 for (ItemInfo item: sBgItemsIdMap.values()) {
2034 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002035 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2036 unusedScreens.contains(screenId)) {
2037 unusedScreens.remove(screenId);
2038 }
2039 }
2040
2041 // If there are any empty screens remove them, and update.
2042 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002043 // Log to disk
2044 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2045 TextUtils.join(", ", unusedScreens), true);
2046
Winson Chung933bae62013-08-29 11:42:30 -07002047 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002048 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2049 }
2050 }
2051
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002052 if (DEBUG_LOADERS) {
2053 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2054 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002055 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002056 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002058
Daniel Sandler566da102013-06-25 23:43:45 -04002059 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002060 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002061 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002062 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002063 line += " | ";
2064 }
Winson Chung892c74d2013-08-22 16:15:50 -07002065 for (int x = 0; x < countX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002066 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002067 }
Joe Onorato36115782010-06-17 13:28:48 -04002068 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002070 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002071 }
Joe Onorato36115782010-06-17 13:28:48 -04002072 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002073 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002074 }
2075
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 /** Filters the set of items who are directly or indirectly (via another container) on the
2077 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002078 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 ArrayList<ItemInfo> allWorkspaceItems,
2080 ArrayList<ItemInfo> currentScreenItems,
2081 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002082 // Purge any null ItemInfos
2083 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2084 while (iter.hasNext()) {
2085 ItemInfo i = iter.next();
2086 if (i == null) {
2087 iter.remove();
2088 }
2089 }
2090
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 // Order the set of items by their containers first, this allows use to walk through the
2092 // list sequentially, build up a list of containers that are in the specified screen,
2093 // as well as all items in those containers.
2094 Set<Long> itemsOnScreen = new HashSet<Long>();
2095 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2096 @Override
2097 public int compare(ItemInfo lhs, ItemInfo rhs) {
2098 return (int) (lhs.container - rhs.container);
2099 }
2100 });
2101 for (ItemInfo info : allWorkspaceItems) {
2102 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002103 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002104 currentScreenItems.add(info);
2105 itemsOnScreen.add(info.id);
2106 } else {
2107 otherScreenItems.add(info);
2108 }
2109 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2110 currentScreenItems.add(info);
2111 itemsOnScreen.add(info.id);
2112 } else {
2113 if (itemsOnScreen.contains(info.container)) {
2114 currentScreenItems.add(info);
2115 itemsOnScreen.add(info.id);
2116 } else {
2117 otherScreenItems.add(info);
2118 }
2119 }
2120 }
2121 }
2122
2123 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002124 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002125 ArrayList<LauncherAppWidgetInfo> appWidgets,
2126 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2127 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002128
2129 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002130 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002132 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002133 currentScreenWidgets.add(widget);
2134 } else {
2135 otherScreenWidgets.add(widget);
2136 }
2137 }
2138 }
2139
2140 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002141 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 HashMap<Long, ItemInfo> itemsIdMap,
2143 HashMap<Long, FolderInfo> folders,
2144 HashMap<Long, FolderInfo> currentScreenFolders,
2145 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146
2147 for (long id : folders.keySet()) {
2148 ItemInfo info = itemsIdMap.get(id);
2149 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002150 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002152 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002153 currentScreenFolders.put(id, folder);
2154 } else {
2155 otherScreenFolders.put(id, folder);
2156 }
2157 }
2158 }
2159
2160 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2161 * right) */
2162 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002163 final LauncherAppState app = LauncherAppState.getInstance();
2164 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002165 // XXX: review this
2166 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002167 @Override
2168 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002169 int cellCountX = (int) grid.numColumns;
2170 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002171 int screenOffset = cellCountX * cellCountY;
2172 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002173 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002174 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002175 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002176 rhs.cellY * cellCountX + rhs.cellX);
2177 return (int) (lr - rr);
2178 }
2179 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002180 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002181
Adam Cohendcd297f2013-06-18 13:13:40 -07002182 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2183 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002184 final Runnable r = new Runnable() {
2185 @Override
2186 public void run() {
2187 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2188 if (callbacks != null) {
2189 callbacks.bindScreens(orderedScreens);
2190 }
2191 }
2192 };
2193 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2194 }
2195
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002196 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2197 final ArrayList<ItemInfo> workspaceItems,
2198 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2199 final HashMap<Long, FolderInfo> folders,
2200 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002201
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002202 final boolean postOnMainThread = (deferredBindRunnables != null);
2203
2204 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002205 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002206 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002207 final int start = i;
2208 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002209 final Runnable r = new Runnable() {
2210 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002211 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002212 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002213 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002214 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2215 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002216 }
2217 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218 };
2219 if (postOnMainThread) {
2220 deferredBindRunnables.add(r);
2221 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002222 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223 }
Joe Onorato36115782010-06-17 13:28:48 -04002224 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002225
2226 // Bind the folders
2227 if (!folders.isEmpty()) {
2228 final Runnable r = new Runnable() {
2229 public void run() {
2230 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2231 if (callbacks != null) {
2232 callbacks.bindFolders(folders);
2233 }
2234 }
2235 };
2236 if (postOnMainThread) {
2237 deferredBindRunnables.add(r);
2238 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002239 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 }
2241 }
2242
2243 // Bind the widgets, one at a time
2244 N = appWidgets.size();
2245 for (int i = 0; i < N; i++) {
2246 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2247 final Runnable r = new Runnable() {
2248 public void run() {
2249 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2250 if (callbacks != null) {
2251 callbacks.bindAppWidget(widget);
2252 }
2253 }
2254 };
2255 if (postOnMainThread) {
2256 deferredBindRunnables.add(r);
2257 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002258 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002259 }
2260 }
2261 }
2262
2263 /**
2264 * Binds all loaded data to actual views on the main thread.
2265 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002266 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002267 final long t = SystemClock.uptimeMillis();
2268 Runnable r;
2269
2270 // Don't use these two variables in any of the callback runnables.
2271 // Otherwise we hold a reference to them.
2272 final Callbacks oldCallbacks = mCallbacks.get();
2273 if (oldCallbacks == null) {
2274 // This launcher has exited and nobody bothered to tell us. Just bail.
2275 Log.w(TAG, "LoaderTask running with no launcher");
2276 return;
2277 }
2278
Winson Chung9b9fb962013-11-15 15:39:34 -08002279 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2281 ArrayList<LauncherAppWidgetInfo> appWidgets =
2282 new ArrayList<LauncherAppWidgetInfo>();
2283 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2284 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002285 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002286 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 workspaceItems.addAll(sBgWorkspaceItems);
2288 appWidgets.addAll(sBgAppWidgets);
2289 folders.putAll(sBgFolders);
2290 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002291 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002292 }
2293
Derek Prothro7aff3992013-12-10 14:00:37 -05002294 final boolean isLoadingSynchronously =
2295 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002296 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002297 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002298 if (currScreen >= orderedScreenIds.size()) {
2299 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002300 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002301 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002302 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002303 final long currentScreenId = currentScreen < 0
2304 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002305
2306 // Load all the items that are on the current page first (and in the process, unbind
2307 // all the existing workspace items before we call startBinding() below.
2308 unbindWorkspaceItemsOnMainThread();
2309
2310 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002311 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2312 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2313 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2314 new ArrayList<LauncherAppWidgetInfo>();
2315 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2316 new ArrayList<LauncherAppWidgetInfo>();
2317 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2318 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2319
Winson Chung9b9fb962013-11-15 15:39:34 -08002320 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002321 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002322 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002323 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002324 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002325 otherFolders);
2326 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2327 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2328
2329 // Tell the workspace that we're about to start binding items
2330 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002331 public void run() {
2332 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2333 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002334 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002335 }
2336 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 };
Winson Chung81b52252012-08-27 15:34:29 -07002338 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002339
Adam Cohendcd297f2013-06-18 13:13:40 -07002340 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2341
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002342 // Load items on the current page
2343 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2344 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002345 if (isLoadingSynchronously) {
2346 r = new Runnable() {
2347 public void run() {
2348 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002349 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002350 callbacks.onPageBoundSynchronously(currentScreen);
2351 }
2352 }
2353 };
Winson Chung81b52252012-08-27 15:34:29 -07002354 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002355 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002356
Winson Chung4a2afa32012-07-19 14:53:05 -07002357 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2358 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002359 mDeferredBindRunnables.clear();
2360 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002361 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362
2363 // Tell the workspace that we're done binding items
2364 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002365 public void run() {
2366 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2367 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002368 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002369 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002370
Winson Chung98e030b2012-05-07 16:01:11 -07002371 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002372 if (DEBUG_LOADERS) {
2373 Log.d(TAG, "bound workspace in "
2374 + (SystemClock.uptimeMillis()-t) + "ms");
2375 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002376
2377 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002378 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002380 if (isLoadingSynchronously) {
2381 mDeferredBindRunnables.add(r);
2382 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002383 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002384 }
Joe Onorato36115782010-06-17 13:28:48 -04002385 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002386
Joe Onorato36115782010-06-17 13:28:48 -04002387 private void loadAndBindAllApps() {
2388 if (DEBUG_LOADERS) {
2389 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2390 }
2391 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002392 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002393 synchronized (LoaderTask.this) {
2394 if (mStopped) {
2395 return;
2396 }
2397 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002398 }
Joe Onorato36115782010-06-17 13:28:48 -04002399 } else {
2400 onlyBindAllApps();
2401 }
2402 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002403
Joe Onorato36115782010-06-17 13:28:48 -04002404 private void onlyBindAllApps() {
2405 final Callbacks oldCallbacks = mCallbacks.get();
2406 if (oldCallbacks == null) {
2407 // This launcher has exited and nobody bothered to tell us. Just bail.
2408 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2409 return;
2410 }
2411
2412 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002413 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002414 final ArrayList<AppInfo> list
2415 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002416 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002417 public void run() {
2418 final long t = SystemClock.uptimeMillis();
2419 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2420 if (callbacks != null) {
2421 callbacks.bindAllApplications(list);
2422 }
2423 if (DEBUG_LOADERS) {
2424 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2425 + (SystemClock.uptimeMillis()-t) + "ms");
2426 }
2427 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002428 };
2429 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002430 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002431 r.run();
2432 } else {
2433 mHandler.post(r);
2434 }
Joe Onorato36115782010-06-17 13:28:48 -04002435 }
2436
Winson Chung64359a52013-07-08 17:17:08 -07002437 private void loadAllApps() {
2438 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002439
Joe Onorato36115782010-06-17 13:28:48 -04002440 final Callbacks oldCallbacks = mCallbacks.get();
2441 if (oldCallbacks == null) {
2442 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002443 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002444 return;
2445 }
2446
Winson Chung64359a52013-07-08 17:17:08 -07002447 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002448 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2449 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2450
Winson Chung64359a52013-07-08 17:17:08 -07002451 // Clear the list of apps
2452 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002453
Winson Chung64359a52013-07-08 17:17:08 -07002454 // Query for the set of apps
2455 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2456 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2457 if (DEBUG_LOADERS) {
2458 Log.d(TAG, "queryIntentActivities took "
2459 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2460 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2461 }
2462 // Fail if we don't have any apps
2463 if (apps == null || apps.isEmpty()) {
2464 return;
2465 }
2466 // Sort the applications by name
2467 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2468 Collections.sort(apps,
2469 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2470 if (DEBUG_LOADERS) {
2471 Log.d(TAG, "sort took "
2472 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002473 }
2474
Winson Chung64359a52013-07-08 17:17:08 -07002475 // Create the ApplicationInfos
Winson Chung64359a52013-07-08 17:17:08 -07002476 for (int i = 0; i < apps.size(); i++) {
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002477 ResolveInfo app = apps.get(i);
Bjorn Bringert1307f632013-10-03 22:31:03 +01002478 // This builds the icon bitmaps.
2479 mBgAllAppsList.add(new AppInfo(packageManager, app,
2480 mIconCache, mLabelCache));
Winson Chung64359a52013-07-08 17:17:08 -07002481 }
2482
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002483 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002484 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2485 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002486
2487 // Post callback on main thread
2488 mHandler.post(new Runnable() {
2489 public void run() {
2490 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002491 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002492 if (callbacks != null) {
2493 callbacks.bindAllApplications(added);
2494 if (DEBUG_LOADERS) {
2495 Log.d(TAG, "bound " + added.size() + " apps in "
2496 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2497 }
2498 } else {
2499 Log.i(TAG, "not binding apps: no Launcher activity");
2500 }
2501 }
2502 });
2503
Joe Onorato36115782010-06-17 13:28:48 -04002504 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002505 Log.d(TAG, "Icons processed in "
2506 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002507 }
2508 }
2509
2510 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002511 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002512 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2513 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2514 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2515 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2516 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2517 }
Joe Onorato36115782010-06-17 13:28:48 -04002518 }
2519 }
2520
2521 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002522 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002523 }
2524
2525 private class PackageUpdatedTask implements Runnable {
2526 int mOp;
2527 String[] mPackages;
2528
2529 public static final int OP_NONE = 0;
2530 public static final int OP_ADD = 1;
2531 public static final int OP_UPDATE = 2;
2532 public static final int OP_REMOVE = 3; // uninstlled
2533 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2534
2535
2536 public PackageUpdatedTask(int op, String[] packages) {
2537 mOp = op;
2538 mPackages = packages;
2539 }
2540
2541 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002542 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002543
2544 final String[] packages = mPackages;
2545 final int N = packages.length;
2546 switch (mOp) {
2547 case OP_ADD:
2548 for (int i=0; i<N; i++) {
2549 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002550 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002551 }
2552 break;
2553 case OP_UPDATE:
2554 for (int i=0; i<N; i++) {
2555 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002556 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002557 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002558 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002559 }
2560 break;
2561 case OP_REMOVE:
2562 case OP_UNAVAILABLE:
2563 for (int i=0; i<N; i++) {
2564 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002565 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002566 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002567 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002568 }
2569 break;
2570 }
2571
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002572 ArrayList<AppInfo> added = null;
2573 ArrayList<AppInfo> modified = null;
2574 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002575
Adam Cohen487f7dd2012-06-28 18:12:10 -07002576 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002577 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002578 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002579 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002580 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002581 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002582 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002583 }
Winson Chung5d55f332012-07-16 20:45:03 -07002584 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002585 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002586 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002587 }
2588
Joe Onorato36115782010-06-17 13:28:48 -04002589 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2590 if (callbacks == null) {
2591 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2592 return;
2593 }
2594
2595 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002596 // Ensure that we add all the workspace applications to the db
2597 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08002598 if (!LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07002599 addAndBindAddedApps(context, new ArrayList<ItemInfo>(), cb, added);
2600 } else {
2601 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
2602 addAndBindAddedApps(context, addedInfos, cb, added);
2603 }
Joe Onorato36115782010-06-17 13:28:48 -04002604 }
2605 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002606 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002607
2608 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002609 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002610 ArrayList<ItemInfo> infos =
2611 getItemInfoForComponentName(a.componentName);
2612 for (ItemInfo i : infos) {
2613 if (isShortcutInfoUpdateable(i)) {
2614 ShortcutInfo info = (ShortcutInfo) i;
2615 info.title = a.title.toString();
2616 updateItemInDatabase(context, info);
2617 }
2618 }
2619 }
2620
Joe Onorato36115782010-06-17 13:28:48 -04002621 mHandler.post(new Runnable() {
2622 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002623 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2624 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002625 callbacks.bindAppsUpdated(modifiedFinal);
2626 }
2627 }
2628 });
2629 }
Winson Chung83892cc2013-05-01 16:53:33 -07002630
Winson Chungdf95eb12013-10-16 14:57:07 -07002631 final ArrayList<String> removedPackageNames =
2632 new ArrayList<String>();
2633 if (mOp == OP_REMOVE) {
2634 // Mark all packages in the broadcast to be removed
2635 removedPackageNames.addAll(Arrays.asList(packages));
2636 } else if (mOp == OP_UPDATE) {
2637 // Mark disabled packages in the broadcast to be removed
2638 final PackageManager pm = context.getPackageManager();
2639 for (int i=0; i<N; i++) {
2640 if (isPackageDisabled(pm, packages[i])) {
2641 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002642 }
2643 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002644 }
2645 // Remove all the components associated with this package
2646 for (String pn : removedPackageNames) {
2647 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2648 for (ItemInfo i : infos) {
2649 deleteItemFromDatabase(context, i);
2650 }
2651 }
2652 // Remove all the specific components
2653 for (AppInfo a : removedApps) {
2654 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName);
2655 for (ItemInfo i : infos) {
2656 deleteItemFromDatabase(context, i);
2657 }
2658 }
2659 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2660 // Remove any queued items from the install queue
2661 String spKey = LauncherAppState.getSharedPreferencesKey();
2662 SharedPreferences sp =
2663 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2664 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2665 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002666 mHandler.post(new Runnable() {
2667 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002668 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2669 if (callbacks == cb && cb != null) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002670 callbacks.bindComponentsRemoved(removedPackageNames, removedApps);
Joe Onorato36115782010-06-17 13:28:48 -04002671 }
2672 }
2673 });
Joe Onoratobe386092009-11-17 17:32:16 -08002674 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002675
Michael Jurkac402cd92013-05-20 15:49:32 +02002676 final ArrayList<Object> widgetsAndShortcuts =
2677 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002678 mHandler.post(new Runnable() {
2679 @Override
2680 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002681 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2682 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002683 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002684 }
2685 }
2686 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002687
2688 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002689 mHandler.post(new Runnable() {
2690 public void run() {
2691 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2692 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002693 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002694 }
2695 }
2696 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002697 }
2698 }
2699
Michael Jurkac402cd92013-05-20 15:49:32 +02002700 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2701 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2702 PackageManager packageManager = context.getPackageManager();
2703 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2704 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2705 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2706 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2707 Collections.sort(widgetsAndShortcuts,
2708 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2709 return widgetsAndShortcuts;
2710 }
2711
Winson Chungdf95eb12013-10-16 14:57:07 -07002712 private boolean isPackageDisabled(PackageManager pm, String packageName) {
2713 try {
2714 PackageInfo pi = pm.getPackageInfo(packageName, 0);
2715 return !pi.applicationInfo.enabled;
2716 } catch (NameNotFoundException e) {
2717 // Fall through
2718 }
2719 return false;
2720 }
Winson Chung1323b482013-08-05 12:41:55 -07002721 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002722 if (cn == null) {
2723 return false;
2724 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002725 if (isPackageDisabled(pm, cn.getPackageName())) {
2726 return false;
2727 }
Winson Chungee055712013-07-30 14:46:24 -07002728
2729 try {
Winson Chungba9c37f2013-08-30 14:11:37 -07002730 // Check the activity
Winson Chungdf95eb12013-10-16 14:57:07 -07002731 PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
Winson Chungee055712013-07-30 14:46:24 -07002732 return (pm.getActivityInfo(cn, 0) != null);
2733 } catch (NameNotFoundException e) {
2734 return false;
2735 }
2736 }
2737
Joe Onorato9c1289c2009-08-17 11:03:03 -04002738 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002739 * This is called from the code that adds shortcuts from the intent receiver. This
2740 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002741 */
Joe Onorato56d82912010-03-07 14:32:10 -05002742 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002743 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002744 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002745
Joe Onorato56d82912010-03-07 14:32:10 -05002746 /**
2747 * Make an ShortcutInfo object for a shortcut that is an application.
2748 *
2749 * If c is not null, then it will be used to fill in missing data like the title and icon.
2750 */
2751 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002752 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002753 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002754 final ShortcutInfo info = new ShortcutInfo();
Winson Chung68fd3c32013-08-30 16:38:00 -07002755 if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002756 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002757 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002758 } else {
2759 try {
2760 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2761 info.initFlagsAndFirstInstallTime(pi);
2762 } catch (NameNotFoundException e) {
2763 Log.d(TAG, "getPackInfo failed for package " +
2764 componentName.getPackageName());
2765 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002766 }
2767
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002768 // TODO: See if the PackageManager knows about this case. If it doesn't
2769 // then return null & delete this.
2770
Joe Onorato56d82912010-03-07 14:32:10 -05002771 // the resource -- This may implicitly give us back the fallback icon,
2772 // but don't worry about that. All we're doing with usingFallbackIcon is
2773 // to avoid saving lots of copies of that in the database, and most apps
2774 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002775
2776 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2777 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2778 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002779 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002780 ResolveInfo resolveInfo = null;
2781 ComponentName oldComponent = intent.getComponent();
2782 Intent newIntent = new Intent(intent.getAction(), null);
2783 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2784 newIntent.setPackage(oldComponent.getPackageName());
2785 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2786 for (ResolveInfo i : infos) {
2787 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2788 i.activityInfo.name);
2789 if (cn.equals(oldComponent)) {
2790 resolveInfo = i;
2791 }
2792 }
2793 if (resolveInfo == null) {
2794 resolveInfo = manager.resolveActivity(intent, 0);
2795 }
Joe Onorato56d82912010-03-07 14:32:10 -05002796 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002797 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002798 }
Joe Onorato56d82912010-03-07 14:32:10 -05002799 // the db
2800 if (icon == null) {
2801 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002802 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002803 }
2804 }
2805 // the fallback icon
2806 if (icon == null) {
2807 icon = getFallbackIcon();
2808 info.usingFallbackIcon = true;
2809 }
2810 info.setIcon(icon);
2811
2812 // from the resource
2813 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002814 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2815 if (labelCache != null && labelCache.containsKey(key)) {
2816 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002817 } else {
2818 info.title = resolveInfo.activityInfo.loadLabel(manager);
2819 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002820 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002821 }
2822 }
Joe Onorato56d82912010-03-07 14:32:10 -05002823 }
2824 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002825 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002826 if (c != null) {
2827 info.title = c.getString(titleIndex);
2828 }
2829 }
2830 // fall back to the class name of the activity
2831 if (info.title == null) {
2832 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002833 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002834 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2835 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002836 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002837
Winson Chung64359a52013-07-08 17:17:08 -07002838 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2839 ItemInfoFilter f) {
2840 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2841 for (ItemInfo i : infos) {
2842 if (i instanceof ShortcutInfo) {
2843 ShortcutInfo info = (ShortcutInfo) i;
2844 ComponentName cn = info.intent.getComponent();
2845 if (cn != null && f.filterItem(null, info, cn)) {
2846 filtered.add(info);
2847 }
2848 } else if (i instanceof FolderInfo) {
2849 FolderInfo info = (FolderInfo) i;
2850 for (ShortcutInfo s : info.contents) {
2851 ComponentName cn = s.intent.getComponent();
2852 if (cn != null && f.filterItem(info, s, cn)) {
2853 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002854 }
2855 }
Winson Chung64359a52013-07-08 17:17:08 -07002856 } else if (i instanceof LauncherAppWidgetInfo) {
2857 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2858 ComponentName cn = info.providerName;
2859 if (cn != null && f.filterItem(null, info, cn)) {
2860 filtered.add(info);
2861 }
Winson Chung8a435102012-08-30 17:16:53 -07002862 }
2863 }
Winson Chung64359a52013-07-08 17:17:08 -07002864 return new ArrayList<ItemInfo>(filtered);
2865 }
2866
2867 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
Winson Chung64359a52013-07-08 17:17:08 -07002868 ItemInfoFilter filter = new ItemInfoFilter() {
2869 @Override
2870 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2871 return cn.getPackageName().equals(pn);
2872 }
2873 };
2874 return filterItemInfos(sBgItemsIdMap.values(), filter);
2875 }
2876
2877 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
Winson Chung64359a52013-07-08 17:17:08 -07002878 ItemInfoFilter filter = new ItemInfoFilter() {
2879 @Override
2880 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2881 return cn.equals(cname);
2882 }
2883 };
2884 return filterItemInfos(sBgItemsIdMap.values(), filter);
2885 }
2886
2887 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2888 if (i instanceof ShortcutInfo) {
2889 ShortcutInfo info = (ShortcutInfo) i;
2890 // We need to check for ACTION_MAIN otherwise getComponent() might
2891 // return null for some shortcuts (for instance, for shortcuts to
2892 // web pages.)
2893 Intent intent = info.intent;
2894 ComponentName name = intent.getComponent();
2895 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2896 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2897 return true;
2898 }
2899 }
2900 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002901 }
2902
2903 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002904 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002905 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002906 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002907 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2908 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002909
Joe Onorato56d82912010-03-07 14:32:10 -05002910 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002911 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002912 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002913
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002914 // TODO: If there's an explicit component and we can't install that, delete it.
2915
Joe Onorato56d82912010-03-07 14:32:10 -05002916 info.title = c.getString(titleIndex);
2917
Joe Onorato9c1289c2009-08-17 11:03:03 -04002918 int iconType = c.getInt(iconTypeIndex);
2919 switch (iconType) {
2920 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2921 String packageName = c.getString(iconPackageIndex);
2922 String resourceName = c.getString(iconResourceIndex);
2923 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002924 info.customIcon = false;
2925 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002926 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002927 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002928 if (resources != null) {
2929 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002930 icon = Utilities.createIconBitmap(
2931 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002932 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002933 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002934 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002935 }
Joe Onorato56d82912010-03-07 14:32:10 -05002936 // the db
2937 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002938 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002939 }
2940 // the fallback icon
2941 if (icon == null) {
2942 icon = getFallbackIcon();
2943 info.usingFallbackIcon = true;
2944 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002945 break;
2946 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002947 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002948 if (icon == null) {
2949 icon = getFallbackIcon();
2950 info.customIcon = false;
2951 info.usingFallbackIcon = true;
2952 } else {
2953 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002954 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002955 break;
2956 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002957 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002958 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002959 info.customIcon = false;
2960 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002961 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002962 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002963 return info;
2964 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002965
Michael Jurka931dc972011-08-05 15:08:15 -07002966 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002967 @SuppressWarnings("all") // suppress dead code warning
2968 final boolean debug = false;
2969 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002970 Log.d(TAG, "getIconFromCursor app="
2971 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2972 }
2973 byte[] data = c.getBlob(iconIndex);
2974 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002975 return Utilities.createIconBitmap(
2976 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002977 } catch (Exception e) {
2978 return null;
2979 }
2980 }
2981
Winson Chung3d503fb2011-07-13 17:25:49 -07002982 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2983 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002984 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002985 if (info == null) {
2986 return null;
2987 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002988 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002989
2990 return info;
2991 }
2992
Winson Chunga9abd0e2010-10-27 17:18:37 -07002993 /**
Winson Chung55cef262010-10-28 14:14:18 -07002994 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2995 */
2996 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2997 ComponentName component) {
2998 List<AppWidgetProviderInfo> widgets =
2999 AppWidgetManager.getInstance(context).getInstalledProviders();
3000 for (AppWidgetProviderInfo info : widgets) {
3001 if (info.provider.equals(component)) {
3002 return info;
3003 }
3004 }
3005 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07003006 }
3007
Winson Chung68846fd2010-10-29 11:00:27 -07003008 /**
3009 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
3010 */
3011 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
3012 final PackageManager packageManager = context.getPackageManager();
3013 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
3014 new ArrayList<WidgetMimeTypeHandlerData>();
3015
3016 final Intent supportsIntent =
3017 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
3018 supportsIntent.setType(mimeType);
3019
3020 // Create a set of widget configuration components that we can test against
3021 final List<AppWidgetProviderInfo> widgets =
3022 AppWidgetManager.getInstance(context).getInstalledProviders();
3023 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3024 new HashMap<ComponentName, AppWidgetProviderInfo>();
3025 for (AppWidgetProviderInfo info : widgets) {
3026 configurationComponentToWidget.put(info.configure, info);
3027 }
3028
3029 // Run through each of the intents that can handle this type of clip data, and cross
3030 // reference them with the components that are actual configuration components
3031 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3032 PackageManager.MATCH_DEFAULT_ONLY);
3033 for (ResolveInfo info : activities) {
3034 final ActivityInfo activityInfo = info.activityInfo;
3035 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3036 activityInfo.name);
3037 if (configurationComponentToWidget.containsKey(infoComponent)) {
3038 supportedConfigurationActivities.add(
3039 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3040 configurationComponentToWidget.get(infoComponent)));
3041 }
3042 }
3043 return supportedConfigurationActivities;
3044 }
3045
Winson Chunga9abd0e2010-10-27 17:18:37 -07003046 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003047 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3048 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3049 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3050
Adam Cohend9198822011-11-22 16:42:47 -08003051 if (intent == null) {
3052 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3053 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3054 return null;
3055 }
3056
Joe Onorato0589f0f2010-02-08 13:44:00 -08003057 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003058 boolean customIcon = false;
3059 ShortcutIconResource iconResource = null;
3060
3061 if (bitmap != null && bitmap instanceof Bitmap) {
3062 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003063 customIcon = true;
3064 } else {
3065 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3066 if (extra != null && extra instanceof ShortcutIconResource) {
3067 try {
3068 iconResource = (ShortcutIconResource) extra;
3069 final PackageManager packageManager = context.getPackageManager();
3070 Resources resources = packageManager.getResourcesForApplication(
3071 iconResource.packageName);
3072 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003073 icon = Utilities.createIconBitmap(
3074 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003075 } catch (Exception e) {
3076 Log.w(TAG, "Could not load shortcut icon: " + extra);
3077 }
3078 }
3079 }
3080
Michael Jurkac9d95c52011-08-29 14:03:34 -07003081 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003082
3083 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003084 if (fallbackIcon != null) {
3085 icon = fallbackIcon;
3086 } else {
3087 icon = getFallbackIcon();
3088 info.usingFallbackIcon = true;
3089 }
Joe Onorato56d82912010-03-07 14:32:10 -05003090 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003091 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003092
Joe Onorato0589f0f2010-02-08 13:44:00 -08003093 info.title = name;
3094 info.intent = intent;
3095 info.customIcon = customIcon;
3096 info.iconResource = iconResource;
3097
3098 return info;
3099 }
3100
Winson Chungaac01e12011-08-17 10:37:13 -07003101 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3102 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003103 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003104 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003105 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003106 }
Joe Onorato56d82912010-03-07 14:32:10 -05003107 // If this icon doesn't have a custom icon, check to see
3108 // what's stored in the DB, and if it doesn't match what
3109 // we're going to show, store what we are going to show back
3110 // into the DB. We do this so when we're loading, if the
3111 // package manager can't find an icon (for example because
3112 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003113 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003114 cache.put(info, c.getBlob(iconIndex));
3115 return true;
3116 }
3117 return false;
3118 }
3119 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3120 boolean needSave = false;
3121 try {
3122 if (data != null) {
3123 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3124 Bitmap loaded = info.getIcon(mIconCache);
3125 needSave = !saved.sameAs(loaded);
3126 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003127 needSave = true;
3128 }
Winson Chungaac01e12011-08-17 10:37:13 -07003129 } catch (Exception e) {
3130 needSave = true;
3131 }
3132 if (needSave) {
3133 Log.d(TAG, "going to save icon bitmap for info=" + info);
3134 // This is slower than is ideal, but this only happens once
3135 // or when the app is updated with a new icon.
3136 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003137 }
3138 }
3139
Joe Onorato9c1289c2009-08-17 11:03:03 -04003140 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003141 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003142 * or make a new one.
3143 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003144 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003145 // See if a placeholder was created for us already
3146 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003147 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003148 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003149 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003150 folders.put(id, folderInfo);
3151 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003152 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003153 }
3154
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003155 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003156 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003157 return new Comparator<AppInfo>() {
3158 public final int compare(AppInfo a, AppInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003159 int result = collator.compare(a.title.toString().trim(),
3160 b.title.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003161 if (result == 0) {
3162 result = a.componentName.compareTo(b.componentName);
3163 }
3164 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07003165 }
Winson Chung11904872012-09-17 16:58:46 -07003166 };
3167 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003168 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3169 = new Comparator<AppInfo>() {
3170 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003171 if (a.firstInstallTime < b.firstInstallTime) return 1;
3172 if (a.firstInstallTime > b.firstInstallTime) return -1;
3173 return 0;
3174 }
3175 };
Winson Chung11904872012-09-17 16:58:46 -07003176 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3177 final Collator collator = Collator.getInstance();
3178 return new Comparator<AppWidgetProviderInfo>() {
3179 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003180 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003181 }
3182 };
3183 }
Winson Chung5308f242011-08-18 12:12:41 -07003184 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3185 if (info.activityInfo != null) {
3186 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3187 } else {
3188 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3189 }
3190 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003191 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003192 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003193 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003194 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003195 ShortcutNameComparator(PackageManager pm) {
3196 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003197 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003198 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003199 }
3200 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3201 mPackageManager = pm;
3202 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003203 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003204 }
3205 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003206 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003207 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3208 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3209 if (mLabelCache.containsKey(keyA)) {
3210 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003211 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003212 labelA = a.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003213
Winson Chung5308f242011-08-18 12:12:41 -07003214 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003215 }
Winson Chung5308f242011-08-18 12:12:41 -07003216 if (mLabelCache.containsKey(keyB)) {
3217 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003218 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003219 labelB = b.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003220
Winson Chung5308f242011-08-18 12:12:41 -07003221 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003222 }
Winson Chung11904872012-09-17 16:58:46 -07003223 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003224 }
3225 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003226 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003227 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003228 private PackageManager mPackageManager;
3229 private HashMap<Object, String> mLabelCache;
3230 WidgetAndShortcutNameComparator(PackageManager pm) {
3231 mPackageManager = pm;
3232 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003233 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003234 }
3235 public final int compare(Object a, Object b) {
3236 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003237 if (mLabelCache.containsKey(a)) {
3238 labelA = mLabelCache.get(a);
3239 } else {
3240 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003241 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003242 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003243 mLabelCache.put(a, labelA);
3244 }
3245 if (mLabelCache.containsKey(b)) {
3246 labelB = mLabelCache.get(b);
3247 } else {
3248 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003249 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003250 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003251 mLabelCache.put(b, labelB);
3252 }
Winson Chung11904872012-09-17 16:58:46 -07003253 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003254 }
3255 };
Joe Onoratobe386092009-11-17 17:32:16 -08003256
3257 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003258 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003259 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3260 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3261 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3262 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003263 if (mLoaderTask != null) {
3264 mLoaderTask.dumpState();
3265 } else {
3266 Log.d(TAG, "mLoaderTask=null");
3267 }
Joe Onoratobe386092009-11-17 17:32:16 -08003268 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003269}