blob: 498d91a388d5f6d6c6f4f9c2cc6ae4e608b62181 [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
Joe Onorato36115782010-06-17 13:28:48 -040078 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050079 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080080
Winson Chungee055712013-07-30 14:46:24 -070081 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -080082 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -040083
Daniel Sandlercc8befa2013-06-11 14:45:48 -040084 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -040085 private final Object mLock = new Object();
86 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -040087 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070088 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +020089 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Winson Chung81b52252012-08-27 15:34:29 -070091 // Specific runnable types that are run on the main thread deferred handler, this allows us to
92 // clear all queued binding runnables when the Launcher activity is destroyed.
93 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
94 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
95
96
Brad Fitzpatrick700889f2010-10-11 09:40:44 -070097 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
98 static {
99 sWorkerThread.start();
100 }
101 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
102
Joe Onoratocc67f472010-06-08 10:54:30 -0700103 // We start off with everything not loaded. After that, we assume that
104 // our monitoring of the package manager provides all updates and we never
105 // need to do a requery. These are only ever touched from the loader thread.
106 private boolean mWorkspaceLoaded;
107 private boolean mAllAppsLoaded;
108
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700109 // When we are loading pages synchronously, we can't just post the binding of items on the side
110 // pages as this delays the rotation process. Instead, we wait for a callback from the first
111 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
112 // a normal load, we also clear this set of Runnables.
113 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
114
Joe Onorato9c1289c2009-08-17 11:03:03 -0400115 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700117 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700118 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800119
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700120 // The lock that must be acquired before referencing any static bg data structures. Unlike
121 // other locks, this one can generally be held long-term because we never expect any of these
122 // static data structures to be referenced outside of the worker thread except on the first
123 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700124 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700125
Adam Cohen487f7dd2012-06-28 18:12:10 -0700126 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700127 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700128 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700129
Adam Cohen487f7dd2012-06-28 18:12:10 -0700130 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
131 // created by LauncherModel that are directly on the home screen (however, no widgets or
132 // shortcuts within folders).
133 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700134
Adam Cohen487f7dd2012-06-28 18:12:10 -0700135 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
136 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 new ArrayList<LauncherAppWidgetInfo>();
138
Adam Cohen487f7dd2012-06-28 18:12:10 -0700139 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
140 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700141
Adam Cohen487f7dd2012-06-28 18:12:10 -0700142 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
143 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700144
145 // sBgWorkspaceScreens is the ordered set of workspace screens.
146 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
147
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 // </ only access in worker thread >
149
150 private IconCache mIconCache;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800151 private Bitmap mDefaultIcon;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800152
Reena Lee99a73f32011-10-24 17:27:37 -0700153 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700154
Joe Onorato9c1289c2009-08-17 11:03:03 -0400155 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700156 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400157 public int getCurrentWorkspaceScreen();
158 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700159 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
160 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700161 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700162 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500163 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700164 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400165 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200166 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700167 public void bindAppsAdded(ArrayList<Long> newScreens,
168 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700169 ArrayList<ItemInfo> addAnimated,
170 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200171 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Winson Chung83892cc2013-05-01 16:53:33 -0700172 public void bindComponentsRemoved(ArrayList<String> packageNames,
Winson Chungdf95eb12013-10-16 14:57:07 -0700173 ArrayList<AppInfo> appInfos);
Michael Jurkac402cd92013-05-20 15:49:32 +0200174 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100175 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700176 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700177 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700178 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400179 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180
Winson Chung64359a52013-07-08 17:17:08 -0700181 public interface ItemInfoFilter {
182 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
183 }
184
Bjorn Bringert1307f632013-10-03 22:31:03 +0100185 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800186 Context context = app.getContext();
187 ContentResolver contentResolver = context.getContentResolver();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400188
Winson Chungee055712013-07-30 14:46:24 -0700189 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Winson Chunga6945242014-01-08 14:04:34 -0800190 mOldContentProviderExists = (contentResolver.acquireContentProviderClient(
191 LauncherSettings.Favorites.OLD_CONTENT_URI) != null);
Daniel Sandlere4f98912013-06-25 15:13:26 -0400192 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100193 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800194 mIconCache = iconCache;
195
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400196 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700197 Configuration config = res.getConfiguration();
198 mPreviousConfigMcc = config.mcc;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800199 }
200
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700201 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
202 * posted on the main thread handler. */
203 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700204 runOnMainThread(r, 0);
205 }
206 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700207 if (sWorkerThread.getThreadId() == Process.myTid()) {
208 // If we are on the worker thread, post onto the main handler
209 mHandler.post(r);
210 } else {
211 r.run();
212 }
213 }
214
215 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
216 * posted on the worker thread handler. */
217 private static void runOnWorkerThread(Runnable r) {
218 if (sWorkerThread.getThreadId() == Process.myTid()) {
219 r.run();
220 } else {
221 // If we are not on the worker thread, then post to the worker handler
222 sWorker.post(r);
223 }
224 }
225
Winson Chunga6945242014-01-08 14:04:34 -0800226 boolean canMigrateFromOldLauncherDb() {
227 return mOldContentProviderExists;
228 }
229
Winson Chungc9168342013-06-26 14:54:55 -0700230 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
231 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700232 LauncherAppState app = LauncherAppState.getInstance();
233 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
234 final int xCount = (int) grid.numColumns;
235 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700236 boolean[][] occupied = new boolean[xCount][yCount];
237
238 int cellX, cellY, spanX, spanY;
239 for (int i = 0; i < items.size(); ++i) {
240 final ItemInfo item = items.get(i);
241 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
242 if (item.screenId == screen) {
243 cellX = item.cellX;
244 cellY = item.cellY;
245 spanX = item.spanX;
246 spanY = item.spanY;
247 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
248 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
249 occupied[x][y] = true;
250 }
251 }
252 }
253 }
254 }
255
256 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
257 }
258 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700259 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700260 int firstScreenIndex,
261 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700262 // Lock on the app so that we don't try and get the items while apps are being added
263 LauncherAppState app = LauncherAppState.getInstance();
264 LauncherModel model = app.getModel();
265 boolean found = false;
266 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700267 if (sWorkerThread.getThreadId() != Process.myTid()) {
268 // Flush the LauncherModel worker thread, so that if we just did another
269 // processInstallShortcut, we give it time for its shortcut to get added to the
270 // database (getItemsInLocalCoordinates reads the database)
271 model.flushWorkerThread();
272 }
Winson Chungc9168342013-06-26 14:54:55 -0700273 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700274
275 // Try adding to the workspace screens incrementally, starting at the default or center
276 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700277 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
278 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700279 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700280 int[] tmpCoordinates = new int[2];
281 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700282 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700283 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700284 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700285 }
286 }
287 }
Winson Chungc9168342013-06-26 14:54:55 -0700288 return null;
289 }
290
Winson Chung94d67682013-09-25 16:29:40 -0700291 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps,
292 final ArrayList<AppInfo> allAppsApps) {
Winson Chung997a9232013-07-24 15:33:46 -0700293 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung94d67682013-09-25 16:29:40 -0700294 addAndBindAddedApps(context, workspaceApps, cb, allAppsApps);
Winson Chung997a9232013-07-24 15:33:46 -0700295 }
Winson Chung94d67682013-09-25 16:29:40 -0700296 public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps,
Winson Chungfe9d96a2013-11-14 11:30:05 -0800297 final Callbacks callbacks, final ArrayList<AppInfo> allAppsApps) {
298 if (workspaceApps == null || allAppsApps == null) {
299 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
300 }
Winson Chung94d67682013-09-25 16:29:40 -0700301 if (workspaceApps.isEmpty() && allAppsApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700302 return;
Winson Chung997a9232013-07-24 15:33:46 -0700303 }
Winson Chung64359a52013-07-08 17:17:08 -0700304 // Process the newly added applications and add them to the database first
305 Runnable r = new Runnable() {
306 public void run() {
307 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
308 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
309
Winson Chung76828c82013-08-19 15:43:29 -0700310 // Get the list of workspace screens. We need to append to this list and
311 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
312 // called.
313 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
314 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
315 for (Integer i : orderedScreens.keySet()) {
316 long screenId = orderedScreens.get(i);
317 workspaceScreens.add(screenId);
318 }
319
Winson Chung64359a52013-07-08 17:17:08 -0700320 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700321 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700322 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700323 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700324 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700325 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700326
327 // Short-circuit this logic if the icon exists somewhere on the workspace
328 if (LauncherModel.shortcutExists(context, name, launchIntent)) {
329 continue;
330 }
331
Winson Chung87412982013-10-03 18:34:14 -0700332 // Add this icon to the db, creating a new page if necessary. If there
333 // is only the empty page then we just add items to the first page.
334 // Otherwise, we add them to the next pages.
335 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700336 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700337 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700338 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200339 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700340
341 // If we can't find a valid position, then just add a new screen.
342 // This takes time so we need to re-queue the add until the new
343 // page is added. Create as many screens as necessary to satisfy
344 // the startSearchPageIndex.
345 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700346 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700347 while (numPagesToAdd > 0) {
348 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700349 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700350 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700351 addedWorkspaceScreensFinal.add(screenId);
352 numPagesToAdd--;
353 }
Winson Chung76828c82013-08-19 15:43:29 -0700354
Winson Chung64359a52013-07-08 17:17:08 -0700355 // Find the coordinate again
356 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700357 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700358 }
359 if (coords == null) {
360 throw new RuntimeException("Coordinates should not be null");
361 }
362
Winson Chung997a9232013-07-24 15:33:46 -0700363 ShortcutInfo shortcutInfo;
364 if (a instanceof ShortcutInfo) {
365 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200366 } else if (a instanceof AppInfo) {
367 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700368 } else {
369 throw new RuntimeException("Unexpected info type");
370 }
Winson Chung94d67682013-09-25 16:29:40 -0700371
Winson Chung64359a52013-07-08 17:17:08 -0700372 // Add the shortcut to the db
373 addItemToDatabase(context, shortcutInfo,
374 LauncherSettings.Favorites.CONTAINER_DESKTOP,
375 coords.first, coords.second[0], coords.second[1], false);
376 // Save the ShortcutInfo for binding in the workspace
377 addedShortcutsFinal.add(shortcutInfo);
378 }
379 }
380
Winson Chung76828c82013-08-19 15:43:29 -0700381 // Update the workspace screens
382 updateWorkspaceScreenOrder(context, workspaceScreens);
383
Winson Chung94d67682013-09-25 16:29:40 -0700384 if (!addedShortcutsFinal.isEmpty() || !allAppsApps.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700385 runOnMainThread(new Runnable() {
386 public void run() {
387 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
388 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700389 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
390 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700391 if (!addedShortcutsFinal.isEmpty()) {
392 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
393 long lastScreenId = info.screenId;
394 for (ItemInfo i : addedShortcutsFinal) {
395 if (i.screenId == lastScreenId) {
396 addAnimated.add(i);
397 } else {
398 addNotAnimated.add(i);
399 }
Winson Chung997a9232013-07-24 15:33:46 -0700400 }
401 }
Winson Chungd64d1762013-08-20 14:37:16 -0700402 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Winson Chung94d67682013-09-25 16:29:40 -0700403 addNotAnimated, addAnimated, allAppsApps);
Winson Chung997a9232013-07-24 15:33:46 -0700404 }
Winson Chung64359a52013-07-08 17:17:08 -0700405 }
Winson Chung997a9232013-07-24 15:33:46 -0700406 });
407 }
Winson Chung64359a52013-07-08 17:17:08 -0700408 }
409 };
410 runOnWorkerThread(r);
411 }
412
Joe Onorato56d82912010-03-07 14:32:10 -0500413 public Bitmap getFallbackIcon() {
Winson Chung5801ef02013-10-16 13:46:28 -0700414 if (mDefaultIcon == null) {
415 final Context context = LauncherAppState.getInstance().getContext();
416 mDefaultIcon = Utilities.createIconBitmap(
417 mIconCache.getFullResDefaultActivityIcon(), context);
418 }
Joe Onorato0589f0f2010-02-08 13:44:00 -0800419 return Bitmap.createBitmap(mDefaultIcon);
Joe Onoratof99f8c12009-10-31 17:27:36 -0400420 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800421
Winson Chung81b52252012-08-27 15:34:29 -0700422 public void unbindItemInfosAndClearQueuedBindRunnables() {
423 if (sWorkerThread.getThreadId() == Process.myTid()) {
424 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
425 "main thread");
426 }
427
428 // Clear any deferred bind runnables
429 mDeferredBindRunnables.clear();
430 // Remove any queued bind runnables
431 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
432 // Unbind all the workspace items
433 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700434 }
435
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700436 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700437 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700438 // Ensure that we don't use the same workspace items data structure on the main thread
439 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700440 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
441 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700442 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700443 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
444 tmpAppWidgets.addAll(sBgAppWidgets);
445 }
446 Runnable r = new Runnable() {
447 @Override
448 public void run() {
449 for (ItemInfo item : tmpWorkspaceItems) {
450 item.unbind();
451 }
452 for (ItemInfo item : tmpAppWidgets) {
453 item.unbind();
454 }
455 }
456 };
457 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700458 }
459
Joe Onorato9c1289c2009-08-17 11:03:03 -0400460 /**
461 * Adds an item to the DB if it was not created previously, or move it to a new
462 * <container, screen, cellX, cellY>
463 */
464 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700465 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400466 if (item.container == ItemInfo.NO_ID) {
467 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700468 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400469 } else {
470 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700471 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 }
473 }
474
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700475 static void checkItemInfoLocked(
476 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
477 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
478 if (modelItem != null && item != modelItem) {
479 // check all the data is consistent
480 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
481 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
482 ShortcutInfo shortcut = (ShortcutInfo) item;
483 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
484 modelShortcut.intent.filterEquals(shortcut.intent) &&
485 modelShortcut.id == shortcut.id &&
486 modelShortcut.itemType == shortcut.itemType &&
487 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700488 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700489 modelShortcut.cellX == shortcut.cellX &&
490 modelShortcut.cellY == shortcut.cellY &&
491 modelShortcut.spanX == shortcut.spanX &&
492 modelShortcut.spanY == shortcut.spanY &&
493 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
494 (modelShortcut.dropPos != null &&
495 shortcut.dropPos != null &&
496 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
497 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
498 // For all intents and purposes, this is the same object
499 return;
500 }
501 }
502
503 // the modelItem needs to match up perfectly with item if our model is
504 // to be consistent with the database-- for now, just require
505 // modelItem == item or the equality check above
506 String msg = "item: " + ((item != null) ? item.toString() : "null") +
507 "modelItem: " +
508 ((modelItem != null) ? modelItem.toString() : "null") +
509 "Error: ItemInfo passed to checkItemInfo doesn't match original";
510 RuntimeException e = new RuntimeException(msg);
511 if (stackTrace != null) {
512 e.setStackTrace(stackTrace);
513 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800514 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700515 }
516 }
517
Michael Jurka816474f2012-06-25 14:49:02 -0700518 static void checkItemInfo(final ItemInfo item) {
519 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
520 final long itemId = item.id;
521 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700522 public void run() {
523 synchronized (sBgLock) {
524 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700525 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700526 }
527 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700528 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700529 }
530
Michael Jurkac9d95c52011-08-29 14:03:34 -0700531 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
532 final ItemInfo item, final String callingFunction) {
533 final long itemId = item.id;
534 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
535 final ContentResolver cr = context.getContentResolver();
536
Adam Cohen487f7dd2012-06-28 18:12:10 -0700537 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700538 Runnable r = new Runnable() {
539 public void run() {
540 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700541 updateItemArrays(item, itemId, stackTrace);
542 }
543 };
544 runOnWorkerThread(r);
545 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700546
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700547 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
548 final ArrayList<ItemInfo> items, final String callingFunction) {
549 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700550
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700551 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
552 Runnable r = new Runnable() {
553 public void run() {
554 ArrayList<ContentProviderOperation> ops =
555 new ArrayList<ContentProviderOperation>();
556 int count = items.size();
557 for (int i = 0; i < count; i++) {
558 ItemInfo item = items.get(i);
559 final long itemId = item.id;
560 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
561 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700562
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700563 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
564 updateItemArrays(item, itemId, stackTrace);
565
566 }
567 try {
568 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
569 } catch (Exception e) {
570 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700571 }
572 }
573 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700574 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700575 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700576
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700577 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
578 // Lock on mBgLock *after* the db operation
579 synchronized (sBgLock) {
580 checkItemInfoLocked(itemId, item, stackTrace);
581
582 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
583 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
584 // Item is in a folder, make sure this folder exists
585 if (!sBgFolders.containsKey(item.container)) {
586 // An items container is being set to a that of an item which is not in
587 // the list of Folders.
588 String msg = "item: " + item + " container being set to: " +
589 item.container + ", not in the list of folders";
590 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700591 }
592 }
593
594 // Items are added/removed from the corresponding FolderInfo elsewhere, such
595 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
596 // that are on the desktop, as appropriate
597 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800598 if (modelItem != null &&
599 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
600 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700601 switch (modelItem.itemType) {
602 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
603 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
604 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
605 if (!sBgWorkspaceItems.contains(modelItem)) {
606 sBgWorkspaceItems.add(modelItem);
607 }
608 break;
609 default:
610 break;
611 }
612 } else {
613 sBgWorkspaceItems.remove(modelItem);
614 }
615 }
616 }
617
Michael Jurkac7700af2013-05-14 20:17:58 +0200618 public void flushWorkerThread() {
619 mFlushingWorkerThread = true;
620 Runnable waiter = new Runnable() {
621 public void run() {
622 synchronized (this) {
623 notifyAll();
624 mFlushingWorkerThread = false;
625 }
626 }
627 };
628
629 synchronized(waiter) {
630 runOnWorkerThread(waiter);
631 if (mLoaderTask != null) {
632 synchronized(mLoaderTask) {
633 mLoaderTask.notify();
634 }
635 }
636 boolean success = false;
637 while (!success) {
638 try {
639 waiter.wait();
640 success = true;
641 } catch (InterruptedException e) {
642 }
643 }
644 }
645 }
646
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400648 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700649 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700650 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400652 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400653 item.cellX = cellX;
654 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700655
Winson Chung3d503fb2011-07-13 17:25:49 -0700656 // We store hotseat items in canonical form which is this orientation invariant position
657 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700659 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700660 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700661 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700662 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700663 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400664
665 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400666 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700667 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
668 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700669 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400670
Michael Jurkac9d95c52011-08-29 14:03:34 -0700671 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700672 }
673
674 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700675 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
676 * cellX, cellY have already been updated on the ItemInfos.
677 */
678 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
679 final long container, final int screen) {
680
681 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
682 int count = items.size();
683
684 for (int i = 0; i < count; i++) {
685 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700686 item.container = container;
687
688 // We store hotseat items in canonical form which is this orientation invariant position
689 // in the hotseat
690 if (context instanceof Launcher && screen < 0 &&
691 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700692 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700693 item.cellY);
694 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700695 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700696 }
697
698 final ContentValues values = new ContentValues();
699 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
700 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
701 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700702 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700703
704 contentValues.add(values);
705 }
706 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
707 }
708
709 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700710 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800711 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700712 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700713 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700714 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800715 item.cellX = cellX;
716 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700717 item.spanX = spanX;
718 item.spanY = spanY;
719
720 // We store hotseat items in canonical form which is this orientation invariant position
721 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700722 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700723 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700724 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700725 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700726 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700727 }
Adam Cohend4844c32011-02-18 19:25:06 -0800728
Adam Cohend4844c32011-02-18 19:25:06 -0800729 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800730 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700731 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
732 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
733 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
734 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700735 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800736
Michael Jurka816474f2012-06-25 14:49:02 -0700737 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700738 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700739
740 /**
741 * Update an item to the database in a specified container.
742 */
743 static void updateItemInDatabase(Context context, final ItemInfo item) {
744 final ContentValues values = new ContentValues();
745 item.onAddToDatabase(values);
746 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
747 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800748 }
749
750 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400751 * Returns true if the shortcuts already exists in the database.
752 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800753 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 static boolean shortcutExists(Context context, String title, Intent intent) {
755 final ContentResolver cr = context.getContentResolver();
756 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
757 new String[] { "title", "intent" }, "title=? and intent=?",
758 new String[] { title, intent.toUri(0) }, null);
759 boolean result = false;
760 try {
761 result = c.moveToFirst();
762 } finally {
763 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800764 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400765 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700766 }
767
Joe Onorato9c1289c2009-08-17 11:03:03 -0400768 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700769 * Returns an ItemInfo array containing all the items in the LauncherModel.
770 * The ItemInfo.id is not set through this function.
771 */
772 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
773 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
774 final ContentResolver cr = context.getContentResolver();
775 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
776 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
777 LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
778 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
779
780 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
781 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
782 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
783 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
784 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
785 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
786 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
787
788 try {
789 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700790 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700791 item.cellX = c.getInt(cellXIndex);
792 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700793 item.spanX = Math.max(1, c.getInt(spanXIndex));
794 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700795 item.container = c.getInt(containerIndex);
796 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700797 item.screenId = c.getInt(screenIndex);
Winson Chungaafa03c2010-06-11 17:34:16 -0700798
799 items.add(item);
800 }
801 } catch (Exception e) {
802 items.clear();
803 } finally {
804 c.close();
805 }
806
807 return items;
808 }
809
810 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400811 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
812 */
813 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
814 final ContentResolver cr = context.getContentResolver();
815 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
816 "_id=? and (itemType=? or itemType=?)",
817 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700818 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700819
Joe Onorato9c1289c2009-08-17 11:03:03 -0400820 try {
821 if (c.moveToFirst()) {
822 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
823 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
824 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
825 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
826 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
827 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800828
Joe Onorato9c1289c2009-08-17 11:03:03 -0400829 FolderInfo folderInfo = null;
830 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700831 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
832 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400833 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700834 }
835
Joe Onorato9c1289c2009-08-17 11:03:03 -0400836 folderInfo.title = c.getString(titleIndex);
837 folderInfo.id = id;
838 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700839 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700840 folderInfo.cellX = c.getInt(cellXIndex);
841 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400842
843 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700844 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400845 } finally {
846 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700847 }
848
849 return null;
850 }
851
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852 /**
853 * Add an item to the database in a specified container. Sets the container, screen, cellX and
854 * cellY fields of the item. Also assigns an ID to the item.
855 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700856 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700857 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400858 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400859 item.cellX = cellX;
860 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700861 // We store hotseat items in canonical form which is this orientation invariant position
862 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700863 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700864 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700865 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700866 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700867 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700868 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400869
870 final ContentValues values = new ContentValues();
871 final ContentResolver cr = context.getContentResolver();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400872 item.onAddToDatabase(values);
873
Michael Jurka414300a2013-08-27 15:42:35 +0200874 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700875 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -0700876 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -0700877
Michael Jurkac9d95c52011-08-29 14:03:34 -0700878 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700879 public void run() {
880 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
881 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400882
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700883 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700884 synchronized (sBgLock) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700885 checkItemInfoLocked(item.id, item, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700886 sBgItemsIdMap.put(item.id, item);
887 switch (item.itemType) {
888 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
889 sBgFolders.put(item.id, (FolderInfo) item);
890 // Fall through
891 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
892 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
893 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
894 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
895 sBgWorkspaceItems.add(item);
896 } else {
897 if (!sBgFolders.containsKey(item.container)) {
898 // Adding an item to a folder that doesn't exist.
899 String msg = "adding item: " + item + " to a folder that " +
900 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -0700901 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700902 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700903 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700904 break;
905 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
906 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
907 break;
908 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700909 }
910 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700911 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700912 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700913 }
914
Joe Onorato9c1289c2009-08-17 11:03:03 -0400915 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 * Creates a new unique child id, for a given cell span across all layouts.
917 */
Michael Jurka845ba3b2010-09-28 17:09:46 -0700918 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -0700919 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -0700920 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -0700921 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -0700922 }
923
Winson Chungaafa03c2010-06-11 17:34:16 -0700924 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -0700925 * Removes the specified item from the database
926 * @param context
927 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -0400928 */
Michael Jurkac9d95c52011-08-29 14:03:34 -0700929 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400930 final ContentResolver cr = context.getContentResolver();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700931 final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Adam Cohen487f7dd2012-06-28 18:12:10 -0700932
Michael Jurka83df1882011-08-31 20:59:26 -0700933 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700934 public void run() {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700935 cr.delete(uriToDelete, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700936
937 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700938 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700939 switch (item.itemType) {
940 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
941 sBgFolders.remove(item.id);
942 for (ItemInfo info: sBgItemsIdMap.values()) {
943 if (info.container == item.id) {
944 // We are deleting a folder which still contains items that
945 // think they are contained by that folder.
946 String msg = "deleting a folder (" + item + ") which still " +
947 "contains items (" + info + ")";
Adam Cohen28b3e102012-10-04 17:21:33 -0700948 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700949 }
Adam Cohen487f7dd2012-06-28 18:12:10 -0700950 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700951 sBgWorkspaceItems.remove(item);
952 break;
953 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
954 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
955 sBgWorkspaceItems.remove(item);
956 break;
957 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
958 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
959 break;
960 }
961 sBgItemsIdMap.remove(item.id);
962 sBgDbIconCache.remove(item);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700963 }
964 }
Michael Jurka83df1882011-08-31 20:59:26 -0700965 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700966 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 }
968
969 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700970 * Update the order of the workspace screens in the database. The array list contains
971 * a list of screen ids in the order that they should appear.
972 */
Winson Chungc9168342013-06-26 14:54:55 -0700973 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -0800974 // Log to disk
975 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
976 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
977
Winson Chung64359a52013-07-08 17:17:08 -0700978 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700979 final ContentResolver cr = context.getContentResolver();
980 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
981
982 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700983 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700984 while (iter.hasNext()) {
985 long id = iter.next();
986 if (id < 0) {
987 iter.remove();
988 }
989 }
990
991 Runnable r = new Runnable() {
992 @Override
993 public void run() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 // Clear the table
995 cr.delete(uri, null, null);
Winson Chung76828c82013-08-19 15:43:29 -0700996 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -0700997 ContentValues[] values = new ContentValues[count];
998 for (int i = 0; i < count; i++) {
999 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001000 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1002 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 values[i] = v;
1004 }
1005 cr.bulkInsert(uri, values);
Winson Chung9e6a0a22013-08-27 11:58:12 -07001006
Winson Chungba9c37f2013-08-30 14:11:37 -07001007 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001008 sBgWorkspaceScreens.clear();
1009 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001010 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 }
1012 };
1013 runOnWorkerThread(r);
1014 }
1015
1016 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001017 * Remove the contents of the specified folder from the database
1018 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001019 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001020 final ContentResolver cr = context.getContentResolver();
1021
Michael Jurkac9d95c52011-08-29 14:03:34 -07001022 Runnable r = new Runnable() {
1023 public void run() {
1024 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001025 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001026 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001027 sBgItemsIdMap.remove(info.id);
1028 sBgFolders.remove(info.id);
1029 sBgDbIconCache.remove(info);
1030 sBgWorkspaceItems.remove(info);
1031 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001032
Michael Jurkac9d95c52011-08-29 14:03:34 -07001033 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1034 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001035 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001036 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001037 for (ItemInfo childInfo : info.contents) {
1038 sBgItemsIdMap.remove(childInfo.id);
1039 sBgDbIconCache.remove(childInfo);
1040 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001041 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001042 }
1043 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001044 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001045 }
1046
1047 /**
1048 * Set this as the current Launcher activity object for the loader.
1049 */
1050 public void initialize(Callbacks callbacks) {
1051 synchronized (mLock) {
1052 mCallbacks = new WeakReference<Callbacks>(callbacks);
1053 }
1054 }
1055
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001056 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001057 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1058 * ACTION_PACKAGE_CHANGED.
1059 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001060 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001061 public void onReceive(Context context, Intent intent) {
Joe Onorato36115782010-06-17 13:28:48 -04001062 if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001063
Joe Onorato36115782010-06-17 13:28:48 -04001064 final String action = intent.getAction();
Joe Onoratof99f8c12009-10-31 17:27:36 -04001065
Joe Onorato36115782010-06-17 13:28:48 -04001066 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
1067 || Intent.ACTION_PACKAGE_REMOVED.equals(action)
1068 || Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1069 final String packageName = intent.getData().getSchemeSpecificPart();
1070 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001071
Joe Onorato36115782010-06-17 13:28:48 -04001072 int op = PackageUpdatedTask.OP_NONE;
1073
1074 if (packageName == null || packageName.length() == 0) {
1075 // they sent us a bad intent
1076 return;
1077 }
1078
1079 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1080 op = PackageUpdatedTask.OP_UPDATE;
1081 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1082 if (!replacing) {
1083 op = PackageUpdatedTask.OP_REMOVE;
1084 }
1085 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1086 // later, we will update the package at this time
1087 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1088 if (!replacing) {
1089 op = PackageUpdatedTask.OP_ADD;
1090 } else {
1091 op = PackageUpdatedTask.OP_UPDATE;
1092 }
1093 }
1094
1095 if (op != PackageUpdatedTask.OP_NONE) {
1096 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
1097 }
1098
1099 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001100 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Joe Onoratocec58332010-10-07 14:37:40 -04001101 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Winson Chung3ee4a472014-01-06 15:53:37 -08001102 if (!replacing) {
1103 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
1104 if (mAppsCanBeOnRemoveableStorage) {
1105 // Only rebind if we support removable storage. It catches the case where
1106 // apps on the external sd card need to be reloaded
1107 startLoaderFromBackground();
1108 }
1109 } else {
1110 // If we are replacing then just update the packages in the list
1111 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1112 packages));
1113 }
Joe Onorato36115782010-06-17 13:28:48 -04001114 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Winson Chung3ee4a472014-01-06 15:53:37 -08001115 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1116 if (!replacing) {
1117 String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1118 enqueuePackageUpdated(new PackageUpdatedTask(
1119 PackageUpdatedTask.OP_UNAVAILABLE, packages));
1120 }
1121 // else, we are replacing the packages, so ignore this event and wait for
1122 // EXTERNAL_APPLICATIONS_AVAILABLE to update the packages at that time
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001123 } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001124 // If we have changed locale we need to clear out the labels in all apps/workspace.
1125 forceReload();
1126 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1127 // Check if configuration change was an mcc/mnc change which would affect app resources
1128 // and we would need to clear out the labels in all apps/workspace. Same handling as
1129 // above for ACTION_LOCALE_CHANGED
1130 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001131 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001132 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001133 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001134 forceReload();
1135 }
1136 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001137 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001138 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1139 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Michael Jurkaec9788e2011-08-29 11:24:45 -07001140 if (mCallbacks != null) {
1141 Callbacks callbacks = mCallbacks.get();
1142 if (callbacks != null) {
1143 callbacks.bindSearchablesChanged();
1144 }
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001145 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001146 }
1147 }
1148
Reena Lee93f824a2011-09-23 17:20:28 -07001149 private void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001150 resetLoadedState(true, true);
1151
Reena Lee93f824a2011-09-23 17:20:28 -07001152 // Do this here because if the launcher activity is running it will be restarted.
1153 // If it's not running startLoaderFromBackground will merely tell it that it needs
1154 // to reload.
1155 startLoaderFromBackground();
1156 }
1157
Winson Chungf0c6ae02012-03-21 16:10:31 -07001158 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1159 synchronized (mLock) {
1160 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1161 // mWorkspaceLoaded to true later
1162 stopLoaderLocked();
1163 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1164 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1165 }
1166 }
1167
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001168 /**
1169 * When the launcher is in the background, it's possible for it to miss paired
1170 * configuration changes. So whenever we trigger the loader from the background
1171 * tell the launcher that it needs to re-run the loader when it comes back instead
1172 * of doing it now.
1173 */
1174 public void startLoaderFromBackground() {
1175 boolean runLoader = false;
1176 if (mCallbacks != null) {
1177 Callbacks callbacks = mCallbacks.get();
1178 if (callbacks != null) {
1179 // Only actually run the loader if they're not paused.
1180 if (!callbacks.setLoadOnResume()) {
1181 runLoader = true;
1182 }
1183 }
1184 }
1185 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001186 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001187 }
Joe Onorato36115782010-06-17 13:28:48 -04001188 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001189
Reena Lee93f824a2011-09-23 17:20:28 -07001190 // If there is already a loader task running, tell it to stop.
1191 // returns true if isLaunching() was true on the old task
1192 private boolean stopLoaderLocked() {
1193 boolean isLaunching = false;
1194 LoaderTask oldTask = mLoaderTask;
1195 if (oldTask != null) {
1196 if (oldTask.isLaunching()) {
1197 isLaunching = true;
1198 }
1199 oldTask.stopLocked();
1200 }
1201 return isLaunching;
1202 }
1203
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Joe Onorato36115782010-06-17 13:28:48 -04001205 synchronized (mLock) {
1206 if (DEBUG_LOADERS) {
1207 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1208 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001209
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 // Clear any deferred bind-runnables from the synchronized load process
1211 // We must do this before any loading/binding is scheduled below.
1212 mDeferredBindRunnables.clear();
1213
Joe Onorato36115782010-06-17 13:28:48 -04001214 // Don't bother to start the thread if we know it's not going to do anything
1215 if (mCallbacks != null && mCallbacks.get() != null) {
1216 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001217 // also, don't downgrade isLaunching if we're already running
1218 isLaunching = isLaunching || stopLoaderLocked();
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001219 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
Derek Prothro7aff3992013-12-10 14:00:37 -05001220 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1221 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001222 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1223 } else {
1224 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1225 sWorker.post(mLoaderTask);
1226 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001227 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001228 }
1229 }
1230
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001231 void bindRemainingSynchronousPages() {
1232 // Post the remaining side pages to be loaded
1233 if (!mDeferredBindRunnables.isEmpty()) {
1234 for (final Runnable r : mDeferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001235 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001236 }
1237 mDeferredBindRunnables.clear();
1238 }
1239 }
1240
Joe Onorato36115782010-06-17 13:28:48 -04001241 public void stopLoader() {
1242 synchronized (mLock) {
1243 if (mLoaderTask != null) {
1244 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001245 }
1246 }
Joe Onorato36115782010-06-17 13:28:48 -04001247 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001248
Winson Chung76828c82013-08-19 15:43:29 -07001249 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1250 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1251 final ContentResolver contentResolver = context.getContentResolver();
1252 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1253 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1254 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1255
1256 try {
1257 final int idIndex = sc.getColumnIndexOrThrow(
1258 LauncherSettings.WorkspaceScreens._ID);
1259 final int rankIndex = sc.getColumnIndexOrThrow(
1260 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1261 while (sc.moveToNext()) {
1262 try {
1263 long screenId = sc.getLong(idIndex);
1264 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001265 orderedScreens.put(rank, screenId);
1266 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001267 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001268 }
1269 }
1270 } finally {
1271 sc.close();
1272 }
Winson Chunga90303b2013-11-15 13:05:06 -08001273
1274 // Log to disk
1275 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1276 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1277 for (Integer i : orderedScreens.keySet()) {
1278 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1279 }
1280 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1281 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001282 return orderedScreens;
1283 }
1284
Michael Jurkac57b7a82011-08-09 22:02:20 -07001285 public boolean isAllAppsLoaded() {
1286 return mAllAppsLoaded;
1287 }
1288
Winson Chung36a62fe2012-05-06 18:04:42 -07001289 boolean isLoadingWorkspace() {
1290 synchronized (mLock) {
1291 if (mLoaderTask != null) {
1292 return mLoaderTask.isLoadingWorkspace();
1293 }
1294 }
1295 return false;
1296 }
1297
Joe Onorato36115782010-06-17 13:28:48 -04001298 /**
1299 * Runnable for the thread that loads the contents of the launcher:
1300 * - workspace icons
1301 * - widgets
1302 * - all apps icons
1303 */
1304 private class LoaderTask implements Runnable {
1305 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001306 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001307 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001308 private boolean mStopped;
1309 private boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001310
Winson Chungc3eecff2011-07-11 17:44:15 -07001311 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001312
1313 LoaderTask(Context context, boolean isLaunching) {
1314 mContext = context;
1315 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001316 mLabelCache = new HashMap<Object, CharSequence>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001317 }
1318
Joe Onorato36115782010-06-17 13:28:48 -04001319 boolean isLaunching() {
1320 return mIsLaunching;
1321 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001322
Winson Chung36a62fe2012-05-06 18:04:42 -07001323 boolean isLoadingWorkspace() {
1324 return mIsLoadingAndBindingWorkspace;
1325 }
1326
Winson Chungc763c4e2013-07-19 13:49:06 -07001327 /** Returns whether this is an upgrade path */
1328 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001329 mIsLoadingAndBindingWorkspace = true;
1330
Joe Onorato36115782010-06-17 13:28:48 -04001331 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001332 if (DEBUG_LOADERS) {
1333 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001334 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001335
Winson Chungc763c4e2013-07-19 13:49:06 -07001336 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001337 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001338 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001339 synchronized (LoaderTask.this) {
1340 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001341 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001342 }
1343 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001344 }
1345 }
1346
Joe Onorato36115782010-06-17 13:28:48 -04001347 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001348 bindWorkspace(-1, isUpgradePath);
1349 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001350 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001351
Joe Onorato36115782010-06-17 13:28:48 -04001352 private void waitForIdle() {
1353 // Wait until the either we're stopped or the other threads are done.
1354 // This way we don't start loading all apps until the workspace has settled
1355 // down.
1356 synchronized (LoaderTask.this) {
1357 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001358
Joe Onorato36115782010-06-17 13:28:48 -04001359 mHandler.postIdle(new Runnable() {
1360 public void run() {
1361 synchronized (LoaderTask.this) {
1362 mLoadAndBindStepFinished = true;
1363 if (DEBUG_LOADERS) {
1364 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001365 }
Joe Onorato36115782010-06-17 13:28:48 -04001366 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001367 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001368 }
Joe Onorato36115782010-06-17 13:28:48 -04001369 });
1370
Michael Jurkac7700af2013-05-14 20:17:58 +02001371 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001372 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001373 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1374 // wait no longer than 1sec at a time
1375 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001376 } catch (InterruptedException ex) {
1377 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001378 }
1379 }
Joe Onorato36115782010-06-17 13:28:48 -04001380 if (DEBUG_LOADERS) {
1381 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001382 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001383 + "ms for previous step to finish binding");
1384 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001385 }
Joe Onorato36115782010-06-17 13:28:48 -04001386 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001387
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001388 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001389 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 // Ensure that we have a valid page index to load synchronously
1391 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1392 "valid page index");
1393 }
1394 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1395 // Ensure that we don't try and bind a specified page when the pages have not been
1396 // loaded already (we should load everything asynchronously in that case)
1397 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1398 }
1399 synchronized (mLock) {
1400 if (mIsLoaderTaskRunning) {
1401 // Ensure that we are never running the background loading at this point since
1402 // we also touch the background collections
1403 throw new RuntimeException("Error! Background loading is already running");
1404 }
1405 }
1406
1407 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1408 // data structures, we can't allow any other thread to touch that data, but because
1409 // this call is synchronous, we can get away with not locking).
1410
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001411 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001412 // operations from the previous activity. We need to ensure that all queued operations
1413 // are executed before any synchronous binding work is done.
1414 mHandler.flush();
1415
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001416 // Divide the set of loaded items into those that we are binding synchronously, and
1417 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001418 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001419 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1420 // arise from that.
1421 onlyBindAllApps();
1422 }
1423
Joe Onorato36115782010-06-17 13:28:48 -04001424 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001425 boolean isUpgrade = false;
1426
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001427 synchronized (mLock) {
1428 mIsLoaderTaskRunning = true;
1429 }
Joe Onorato36115782010-06-17 13:28:48 -04001430 // Optimize for end-user experience: if the Launcher is up and // running with the
1431 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1432 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001433 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001434 // Elevate priority when Home launches for the first time to avoid
1435 // starving at boot time. Staring at a blank home is not cool.
1436 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001437 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1438 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001439 android.os.Process.setThreadPriority(mIsLaunching
1440 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1441 }
Winson Chung64359a52013-07-08 17:17:08 -07001442 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001443 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001444
Joe Onorato36115782010-06-17 13:28:48 -04001445 if (mStopped) {
1446 break keep_running;
1447 }
1448
1449 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1450 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001451 synchronized (mLock) {
1452 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001453 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001454 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1455 }
1456 }
Joe Onorato36115782010-06-17 13:28:48 -04001457 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001458
1459 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001460 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1461 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001462
1463 // Restore the default thread priority after we are done loading items
1464 synchronized (mLock) {
1465 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1466 }
Joe Onorato36115782010-06-17 13:28:48 -04001467 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001468
Winson Chungaac01e12011-08-17 10:37:13 -07001469 // Update the saved icons if necessary
1470 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001471 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001472 for (Object key : sBgDbIconCache.keySet()) {
1473 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1474 }
1475 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001476 }
Winson Chungaac01e12011-08-17 10:37:13 -07001477
Winson Chungc58497e2013-09-03 17:48:37 -07001478 if (AppsCustomizePagedView.DISABLE_ALL_APPS) {
1479 // Ensure that all the applications that are in the system are
1480 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001481 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001482 verifyApplications();
1483 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001484 }
1485
Joe Onorato36115782010-06-17 13:28:48 -04001486 // Clear out this reference, otherwise we end up holding it until all of the
1487 // callback runnables are done.
1488 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Joe Onorato36115782010-06-17 13:28:48 -04001490 synchronized (mLock) {
1491 // If we are still the last one to be scheduled, remove ourselves.
1492 if (mLoaderTask == this) {
1493 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001494 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001495 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001496 }
Joe Onorato36115782010-06-17 13:28:48 -04001497 }
1498
1499 public void stopLocked() {
1500 synchronized (LoaderTask.this) {
1501 mStopped = true;
1502 this.notify();
1503 }
1504 }
1505
1506 /**
1507 * Gets the callbacks object. If we've been stopped, or if the launcher object
1508 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1509 * object that was around when the deferred message was scheduled, and if there's
1510 * a new Callbacks object around then also return null. This will save us from
1511 * calling onto it with data that will be ignored.
1512 */
1513 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1514 synchronized (mLock) {
1515 if (mStopped) {
1516 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001517 }
Joe Onorato36115782010-06-17 13:28:48 -04001518
1519 if (mCallbacks == null) {
1520 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001521 }
Joe Onorato36115782010-06-17 13:28:48 -04001522
1523 final Callbacks callbacks = mCallbacks.get();
1524 if (callbacks != oldCallbacks) {
1525 return null;
1526 }
1527 if (callbacks == null) {
1528 Log.w(TAG, "no mCallbacks");
1529 return null;
1530 }
1531
1532 return callbacks;
1533 }
1534 }
1535
Winson Chungc763c4e2013-07-19 13:49:06 -07001536 private void verifyApplications() {
1537 final Context context = mApp.getContext();
1538
1539 // Cross reference all the applications in our apps list with items in the workspace
1540 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001541 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001542 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001543 for (AppInfo app : mBgAllAppsList.data) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001544 tmpInfos = getItemInfoForComponentName(app.componentName);
1545 if (tmpInfos.isEmpty()) {
1546 // We are missing an application icon, so add this to the workspace
1547 added.add(app);
1548 // This is a rare event, so lets log it
1549 Log.e(TAG, "Missing Application on load: " + app);
1550 }
1551 }
1552 }
1553 if (!added.isEmpty()) {
1554 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chungfe9d96a2013-11-14 11:30:05 -08001555 addAndBindAddedApps(context, added, cb, new ArrayList<AppInfo>());
Winson Chungc763c4e2013-07-19 13:49:06 -07001556 }
1557 }
1558
Joe Onorato36115782010-06-17 13:28:48 -04001559 // check & update map of what's occupied; used to discard overlapping/invalid items
Winson Chunga0b7e862013-09-05 16:03:15 -07001560 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item,
Adam Cohenae4409d2013-11-26 10:34:59 -08001561 AtomicBoolean deleteOnInvalidPlacement) {
Winson Chung892c74d2013-08-22 16:15:50 -07001562 LauncherAppState app = LauncherAppState.getInstance();
1563 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001564 final int countX = (int) grid.numColumns;
1565 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001566
Adam Cohendcd297f2013-06-18 13:13:40 -07001567 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001568 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001569 // Return early if we detect that an item is under the hotseat button
1570 if (mCallbacks == null ||
1571 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001572 deleteOnInvalidPlacement.set(true);
Dan Sandler295ae182013-12-10 16:05:47 -05001573 Log.e(TAG, "Error loading shortcut into hotseat " + item
1574 + " into position (" + item.screenId + ":" + item.cellX + ","
1575 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001576 return false;
1577 }
1578
Dan Sandler295ae182013-12-10 16:05:47 -05001579 final ItemInfo[][] hotseatItems =
1580 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1581
Adam Cohenae4409d2013-11-26 10:34:59 -08001582 if (item.screenId >= grid.numHotseatIcons) {
1583 Log.e(TAG, "Error loading shortcut " + item
1584 + " into hotseat position " + item.screenId
1585 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1586 + ")");
1587 return false;
1588 }
1589
Dan Sandler295ae182013-12-10 16:05:47 -05001590 if (hotseatItems != null) {
1591 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001592 Log.e(TAG, "Error loading shortcut into hotseat " + item
1593 + " into position (" + item.screenId + ":" + item.cellX + ","
1594 + item.cellY + ") occupied by "
1595 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1596 [(int) item.screenId][0]);
1597 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001598 } else {
1599 hotseatItems[(int) item.screenId][0] = item;
1600 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001601 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001602 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001603 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001604 items[(int) item.screenId][0] = item;
1605 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001606 return true;
1607 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001608 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1609 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001610 return true;
1611 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001612
Adam Cohendcd297f2013-06-18 13:13:40 -07001613 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001614 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001615 occupied.put(item.screenId, items);
1616 }
1617
Dan Sandler295ae182013-12-10 16:05:47 -05001618 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001619 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1620 item.cellX < 0 || item.cellY < 0 ||
1621 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1622 Log.e(TAG, "Error loading shortcut " + item
1623 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1624 + item.cellX + "," + item.cellY
1625 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1626 return false;
1627 }
1628
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001629 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001630 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1631 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001632 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001633 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001634 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001635 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001636 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001637 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001638 return false;
1639 }
1640 }
1641 }
1642 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1643 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001644 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001645 }
1646 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001647
Joe Onorato36115782010-06-17 13:28:48 -04001648 return true;
1649 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001650
Winson Chungba9c37f2013-08-30 14:11:37 -07001651 /** Clears all the sBg data structures */
1652 private void clearSBgDataStructures() {
1653 synchronized (sBgLock) {
1654 sBgWorkspaceItems.clear();
1655 sBgAppWidgets.clear();
1656 sBgFolders.clear();
1657 sBgItemsIdMap.clear();
1658 sBgDbIconCache.clear();
1659 sBgWorkspaceScreens.clear();
1660 }
1661 }
1662
Winson Chunga6945242014-01-08 14:04:34 -08001663 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001664 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001665 // Log to disk
1666 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1667
Joe Onorato36115782010-06-17 13:28:48 -04001668 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001669
Joe Onorato36115782010-06-17 13:28:48 -04001670 final Context context = mContext;
1671 final ContentResolver contentResolver = context.getContentResolver();
1672 final PackageManager manager = context.getPackageManager();
1673 final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
1674 final boolean isSafeMode = manager.isSafeMode();
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001675
Winson Chung892c74d2013-08-22 16:15:50 -07001676 LauncherAppState app = LauncherAppState.getInstance();
1677 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1678 int countX = (int) grid.numColumns;
1679 int countY = (int) grid.numRows;
1680
Michael Jurkab85f8a42012-04-25 15:48:32 -07001681 // Make sure the default workspace is loaded, if needed
Michael Jurka414300a2013-08-27 15:42:35 +02001682 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
Adam Cohene25af792013-06-06 23:08:25 -07001683
Winson Chungc763c4e2013-07-19 13:49:06 -07001684 // Check if we need to do any upgrade-path logic
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001685 // (Includes having just imported default favorites)
Michael Jurka414300a2013-08-27 15:42:35 +02001686 boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001687
Winson Chung9f9f00b2013-11-15 13:27:00 -08001688 // Log to disk
1689 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001690
Winson Chung2abf94d2012-07-18 18:16:38 -07001691 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001692 clearSBgDataStructures();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001693
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001694 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001695 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001696 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001697 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001698
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001699 // +1 for the hotseat (it can be larger than the workspace)
1700 // Load workspace in reverse order to ensure that latest items are loaded first (and
1701 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001702 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001703
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001704 try {
1705 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1706 final int intentIndex = c.getColumnIndexOrThrow
1707 (LauncherSettings.Favorites.INTENT);
1708 final int titleIndex = c.getColumnIndexOrThrow
1709 (LauncherSettings.Favorites.TITLE);
1710 final int iconTypeIndex = c.getColumnIndexOrThrow(
1711 LauncherSettings.Favorites.ICON_TYPE);
1712 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1713 final int iconPackageIndex = c.getColumnIndexOrThrow(
1714 LauncherSettings.Favorites.ICON_PACKAGE);
1715 final int iconResourceIndex = c.getColumnIndexOrThrow(
1716 LauncherSettings.Favorites.ICON_RESOURCE);
1717 final int containerIndex = c.getColumnIndexOrThrow(
1718 LauncherSettings.Favorites.CONTAINER);
1719 final int itemTypeIndex = c.getColumnIndexOrThrow(
1720 LauncherSettings.Favorites.ITEM_TYPE);
1721 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1722 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001723 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1724 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001725 final int screenIndex = c.getColumnIndexOrThrow(
1726 LauncherSettings.Favorites.SCREEN);
1727 final int cellXIndex = c.getColumnIndexOrThrow
1728 (LauncherSettings.Favorites.CELLX);
1729 final int cellYIndex = c.getColumnIndexOrThrow
1730 (LauncherSettings.Favorites.CELLY);
1731 final int spanXIndex = c.getColumnIndexOrThrow
1732 (LauncherSettings.Favorites.SPANX);
1733 final int spanYIndex = c.getColumnIndexOrThrow(
1734 LauncherSettings.Favorites.SPANY);
1735 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1736 //final int displayModeIndex = c.getColumnIndexOrThrow(
1737 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001738
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001739 ShortcutInfo info;
1740 String intentDescription;
1741 LauncherAppWidgetInfo appWidgetInfo;
1742 int container;
1743 long id;
1744 Intent intent;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001745
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001746 while (!mStopped && c.moveToNext()) {
Adam Cohenae4409d2013-11-26 10:34:59 -08001747 AtomicBoolean deleteOnInvalidPlacement = new AtomicBoolean(false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001748 try {
1749 int itemType = c.getInt(itemTypeIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001750
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001751 switch (itemType) {
1752 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1753 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001754 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001755 intentDescription = c.getString(intentIndex);
1756 try {
1757 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001758 ComponentName cn = intent.getComponent();
Winson Chung68fd3c32013-08-30 16:38:00 -07001759 if (cn != null && !isValidPackageComponent(manager, cn)) {
Winson Chungee055712013-07-30 14:46:24 -07001760 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chung1323b482013-08-05 12:41:55 -07001761 // Log the invalid package, and remove it from the db
Winson Chunga0b7e862013-09-05 16:03:15 -07001762 Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
1763 itemsToRemove.add(id);
Winson Chungee055712013-07-30 14:46:24 -07001764 } else {
Winson Chung1323b482013-08-05 12:41:55 -07001765 // If apps can be on external storage, then we just
1766 // leave them for the user to remove (maybe add
1767 // visual treatment to it)
Winson Chung933bae62013-08-29 11:42:30 -07001768 Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
Winson Chungee055712013-07-30 14:46:24 -07001769 }
1770 continue;
1771 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001772 } catch (URISyntaxException e) {
Winson Chung933bae62013-08-29 11:42:30 -07001773 Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001774 continue;
1775 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001776
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001777 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1778 info = getShortcutInfo(manager, intent, context, c, iconIndex,
1779 titleIndex, mLabelCache);
1780 } else {
1781 info = getShortcutInfo(c, context, iconTypeIndex,
1782 iconPackageIndex, iconResourceIndex, iconIndex,
1783 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07001784
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001785 // App shortcuts that used to be automatically added to Launcher
1786 // didn't always have the correct intent flags set, so do that
1787 // here
1788 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001789 intent.getCategories() != null &&
1790 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001791 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001792 intent.addFlags(
1793 Intent.FLAG_ACTIVITY_NEW_TASK |
1794 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1795 }
Michael Jurka96879562012-03-22 05:54:33 -07001796 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001797
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001798 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07001799 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001800 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001801 container = c.getInt(containerIndex);
1802 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001804 info.cellX = c.getInt(cellXIndex);
1805 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001806 info.spanX = 1;
1807 info.spanY = 1;
Adam Cohenae4409d2013-11-26 10:34:59 -08001808
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001809 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001810 deleteOnInvalidPlacement.set(false);
1811 if (!checkItemPlacement(occupied, info, deleteOnInvalidPlacement)) {
1812 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001813 itemsToRemove.add(id);
1814 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001815 break;
1816 }
1817
1818 switch (container) {
1819 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1820 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1821 sBgWorkspaceItems.add(info);
1822 break;
1823 default:
1824 // Item is in a user folder
1825 FolderInfo folderInfo =
1826 findOrMakeFolder(sBgFolders, container);
1827 folderInfo.add(info);
1828 break;
1829 }
1830 sBgItemsIdMap.put(info.id, info);
1831
1832 // now that we've loaded everthing re-save it with the
1833 // icon in case it disappears somehow.
1834 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07001835 } else {
1836 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001837 }
1838 break;
1839
1840 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1841 id = c.getLong(idIndex);
1842 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
1843
1844 folderInfo.title = c.getString(titleIndex);
1845 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001846 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001847 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07001848 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001849 folderInfo.cellX = c.getInt(cellXIndex);
1850 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001851 folderInfo.spanX = 1;
1852 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001853
Daniel Sandler8802e962010-05-26 16:28:16 -04001854 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001855 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001856 if (!checkItemPlacement(occupied, folderInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001857 deleteOnInvalidPlacement)) {
1858 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001859 itemsToRemove.add(id);
1860 }
Daniel Sandler8802e962010-05-26 16:28:16 -04001861 break;
1862 }
Winson Chung5f8afe62013-08-12 16:19:28 -07001863
Joe Onorato9c1289c2009-08-17 11:03:03 -04001864 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001865 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
1866 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
1867 sBgWorkspaceItems.add(folderInfo);
1868 break;
Joe Onorato36115782010-06-17 13:28:48 -04001869 }
Joe Onorato17a89222011-02-08 17:26:11 -08001870
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 sBgItemsIdMap.put(folderInfo.id, folderInfo);
1872 sBgFolders.put(folderInfo.id, folderInfo);
1873 break;
1874
1875 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1876 // Read all Launcher-specific widget details
1877 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04001878 String savedProvider = c.getString(appWidgetProviderIndex);
1879
Joe Onorato36115782010-06-17 13:28:48 -04001880 id = c.getLong(idIndex);
Joe Onorato36115782010-06-17 13:28:48 -04001881
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001882 final AppWidgetProviderInfo provider =
1883 widgets.getAppWidgetInfo(appWidgetId);
Joe Onorato36115782010-06-17 13:28:48 -04001884
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001885 if (!isSafeMode && (provider == null || provider.provider == null ||
1886 provider.provider.getPackageName() == null)) {
1887 String log = "Deleting widget that isn't installed anymore: id="
1888 + id + " appWidgetId=" + appWidgetId;
1889 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07001890 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001891 itemsToRemove.add(id);
1892 } else {
1893 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1894 provider.provider);
1895 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07001896 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001897 appWidgetInfo.cellX = c.getInt(cellXIndex);
1898 appWidgetInfo.cellY = c.getInt(cellYIndex);
1899 appWidgetInfo.spanX = c.getInt(spanXIndex);
1900 appWidgetInfo.spanY = c.getInt(spanYIndex);
1901 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
1902 appWidgetInfo.minSpanX = minSpan[0];
1903 appWidgetInfo.minSpanY = minSpan[1];
Joe Onorato36115782010-06-17 13:28:48 -04001904
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 container = c.getInt(containerIndex);
1906 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1907 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1908 Log.e(TAG, "Widget found where container != " +
1909 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
1910 continue;
1911 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001912
Adam Cohene25af792013-06-06 23:08:25 -07001913 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001914 // check & update map of what's occupied
Adam Cohenae4409d2013-11-26 10:34:59 -08001915 deleteOnInvalidPlacement.set(false);
Winson Chunga0b7e862013-09-05 16:03:15 -07001916 if (!checkItemPlacement(occupied, appWidgetInfo,
Adam Cohenae4409d2013-11-26 10:34:59 -08001917 deleteOnInvalidPlacement)) {
1918 if (deleteOnInvalidPlacement.get()) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001919 itemsToRemove.add(id);
1920 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001921 break;
1922 }
Chris Wrenc3919c02013-09-18 09:48:33 -04001923 String providerName = provider.provider.flattenToString();
1924 if (!providerName.equals(savedProvider)) {
1925 ContentValues values = new ContentValues();
1926 values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
1927 providerName);
1928 String where = BaseColumns._ID + "= ?";
1929 String[] args = {Integer.toString(c.getInt(idIndex))};
1930 contentResolver.update(contentUri, values, where, args);
1931 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001932 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
1933 sBgAppWidgets.add(appWidgetInfo);
1934 }
Joe Onorato36115782010-06-17 13:28:48 -04001935 break;
1936 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001937 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05001938 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001939 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001940 }
1941 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04001942 if (c != null) {
1943 c.close();
1944 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001945 }
1946
Winson Chungba9c37f2013-08-30 14:11:37 -07001947 // Break early if we've stopped loading
1948 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001949 clearSBgDataStructures();
1950 return false;
1951 }
1952
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001953 if (itemsToRemove.size() > 0) {
1954 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Adam Cohen4caf2982013-08-20 18:54:31 -07001955 LauncherSettings.Favorites.CONTENT_URI);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001956 // Remove dead items
1957 for (long id : itemsToRemove) {
1958 if (DEBUG_LOADERS) {
1959 Log.d(TAG, "Removed id = " + id);
1960 }
1961 // Don't notify content observers
1962 try {
1963 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
1964 null, null);
1965 } catch (RemoteException e) {
1966 Log.w(TAG, "Could not remove id = " + id);
1967 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08001968 }
1969 }
1970
Winson Chungc763c4e2013-07-19 13:49:06 -07001971 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001972 long maxScreenId = 0;
1973 // If we're importing we use the old screen order.
1974 for (ItemInfo item: sBgItemsIdMap.values()) {
1975 long screenId = item.screenId;
1976 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1977 !sBgWorkspaceScreens.contains(screenId)) {
1978 sBgWorkspaceScreens.add(screenId);
1979 if (screenId > maxScreenId) {
1980 maxScreenId = screenId;
1981 }
1982 }
1983 }
1984 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08001985 // Log to disk
1986 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
1987 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
1988 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07001989
Michael Jurka414300a2013-08-27 15:42:35 +02001990 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07001991 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07001992
1993 // Update the max item id after we load an old db
1994 long maxItemId = 0;
1995 // If we're importing we use the old screen order.
1996 for (ItemInfo item: sBgItemsIdMap.values()) {
1997 maxItemId = Math.max(maxItemId, item.id);
1998 }
Michael Jurka414300a2013-08-27 15:42:35 +02001999 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002000 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002001 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2002 for (Integer i : orderedScreens.keySet()) {
2003 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002004 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002005 // Log to disk
2006 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2007 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002008
2009 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002010 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002011 for (ItemInfo item: sBgItemsIdMap.values()) {
2012 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002013 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2014 unusedScreens.contains(screenId)) {
2015 unusedScreens.remove(screenId);
2016 }
2017 }
2018
2019 // If there are any empty screens remove them, and update.
2020 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002021 // Log to disk
2022 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2023 TextUtils.join(", ", unusedScreens), true);
2024
Winson Chung933bae62013-08-29 11:42:30 -07002025 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002026 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2027 }
2028 }
2029
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002030 if (DEBUG_LOADERS) {
2031 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2032 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002033 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002034 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002035 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002036
Daniel Sandler566da102013-06-25 23:43:45 -04002037 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002038 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002039 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002040 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002041 line += " | ";
2042 }
Winson Chung892c74d2013-08-22 16:15:50 -07002043 for (int x = 0; x < countX; x++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002044 line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002045 }
Joe Onorato36115782010-06-17 13:28:48 -04002046 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002047 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002048 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002049 }
Joe Onorato36115782010-06-17 13:28:48 -04002050 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002051 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002052 }
2053
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 /** Filters the set of items who are directly or indirectly (via another container) on the
2055 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002056 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 ArrayList<ItemInfo> allWorkspaceItems,
2058 ArrayList<ItemInfo> currentScreenItems,
2059 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002060 // Purge any null ItemInfos
2061 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2062 while (iter.hasNext()) {
2063 ItemInfo i = iter.next();
2064 if (i == null) {
2065 iter.remove();
2066 }
2067 }
2068
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 // Order the set of items by their containers first, this allows use to walk through the
2070 // list sequentially, build up a list of containers that are in the specified screen,
2071 // as well as all items in those containers.
2072 Set<Long> itemsOnScreen = new HashSet<Long>();
2073 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2074 @Override
2075 public int compare(ItemInfo lhs, ItemInfo rhs) {
2076 return (int) (lhs.container - rhs.container);
2077 }
2078 });
2079 for (ItemInfo info : allWorkspaceItems) {
2080 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002081 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002082 currentScreenItems.add(info);
2083 itemsOnScreen.add(info.id);
2084 } else {
2085 otherScreenItems.add(info);
2086 }
2087 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2088 currentScreenItems.add(info);
2089 itemsOnScreen.add(info.id);
2090 } else {
2091 if (itemsOnScreen.contains(info.container)) {
2092 currentScreenItems.add(info);
2093 itemsOnScreen.add(info.id);
2094 } else {
2095 otherScreenItems.add(info);
2096 }
2097 }
2098 }
2099 }
2100
2101 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002102 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002103 ArrayList<LauncherAppWidgetInfo> appWidgets,
2104 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2105 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002106
2107 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002108 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002110 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 currentScreenWidgets.add(widget);
2112 } else {
2113 otherScreenWidgets.add(widget);
2114 }
2115 }
2116 }
2117
2118 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002119 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 HashMap<Long, ItemInfo> itemsIdMap,
2121 HashMap<Long, FolderInfo> folders,
2122 HashMap<Long, FolderInfo> currentScreenFolders,
2123 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002124
2125 for (long id : folders.keySet()) {
2126 ItemInfo info = itemsIdMap.get(id);
2127 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002128 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002130 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 currentScreenFolders.put(id, folder);
2132 } else {
2133 otherScreenFolders.put(id, folder);
2134 }
2135 }
2136 }
2137
2138 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2139 * right) */
2140 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002141 final LauncherAppState app = LauncherAppState.getInstance();
2142 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143 // XXX: review this
2144 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002145 @Override
2146 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002147 int cellCountX = (int) grid.numColumns;
2148 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002149 int screenOffset = cellCountX * cellCountY;
2150 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002151 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002152 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002153 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002154 rhs.cellY * cellCountX + rhs.cellX);
2155 return (int) (lr - rr);
2156 }
2157 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002158 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002159
Adam Cohendcd297f2013-06-18 13:13:40 -07002160 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2161 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002162 final Runnable r = new Runnable() {
2163 @Override
2164 public void run() {
2165 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2166 if (callbacks != null) {
2167 callbacks.bindScreens(orderedScreens);
2168 }
2169 }
2170 };
2171 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2172 }
2173
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002174 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2175 final ArrayList<ItemInfo> workspaceItems,
2176 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2177 final HashMap<Long, FolderInfo> folders,
2178 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002179
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002180 final boolean postOnMainThread = (deferredBindRunnables != null);
2181
2182 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002183 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002185 final int start = i;
2186 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 final Runnable r = new Runnable() {
2188 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002189 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002190 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002191 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002192 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2193 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002194 }
2195 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002196 };
2197 if (postOnMainThread) {
2198 deferredBindRunnables.add(r);
2199 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002200 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002201 }
Joe Onorato36115782010-06-17 13:28:48 -04002202 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002203
2204 // Bind the folders
2205 if (!folders.isEmpty()) {
2206 final Runnable r = new Runnable() {
2207 public void run() {
2208 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2209 if (callbacks != null) {
2210 callbacks.bindFolders(folders);
2211 }
2212 }
2213 };
2214 if (postOnMainThread) {
2215 deferredBindRunnables.add(r);
2216 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002217 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002218 }
2219 }
2220
2221 // Bind the widgets, one at a time
2222 N = appWidgets.size();
2223 for (int i = 0; i < N; i++) {
2224 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2225 final Runnable r = new Runnable() {
2226 public void run() {
2227 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2228 if (callbacks != null) {
2229 callbacks.bindAppWidget(widget);
2230 }
2231 }
2232 };
2233 if (postOnMainThread) {
2234 deferredBindRunnables.add(r);
2235 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002236 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002237 }
2238 }
2239 }
2240
2241 /**
2242 * Binds all loaded data to actual views on the main thread.
2243 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002244 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 final long t = SystemClock.uptimeMillis();
2246 Runnable r;
2247
2248 // Don't use these two variables in any of the callback runnables.
2249 // Otherwise we hold a reference to them.
2250 final Callbacks oldCallbacks = mCallbacks.get();
2251 if (oldCallbacks == null) {
2252 // This launcher has exited and nobody bothered to tell us. Just bail.
2253 Log.w(TAG, "LoaderTask running with no launcher");
2254 return;
2255 }
2256
Winson Chung9b9fb962013-11-15 15:39:34 -08002257 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002258 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2259 ArrayList<LauncherAppWidgetInfo> appWidgets =
2260 new ArrayList<LauncherAppWidgetInfo>();
2261 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2262 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002263 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002264 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002265 workspaceItems.addAll(sBgWorkspaceItems);
2266 appWidgets.addAll(sBgAppWidgets);
2267 folders.putAll(sBgFolders);
2268 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002269 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002270 }
2271
Derek Prothro7aff3992013-12-10 14:00:37 -05002272 final boolean isLoadingSynchronously =
2273 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002274 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002275 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002276 if (currScreen >= orderedScreenIds.size()) {
2277 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002278 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002279 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002280 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002281 final long currentScreenId = currentScreen < 0
2282 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002283
2284 // Load all the items that are on the current page first (and in the process, unbind
2285 // all the existing workspace items before we call startBinding() below.
2286 unbindWorkspaceItemsOnMainThread();
2287
2288 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2290 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2291 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2292 new ArrayList<LauncherAppWidgetInfo>();
2293 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2294 new ArrayList<LauncherAppWidgetInfo>();
2295 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2296 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2297
Winson Chung9b9fb962013-11-15 15:39:34 -08002298 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002299 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002300 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002302 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002303 otherFolders);
2304 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2305 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2306
2307 // Tell the workspace that we're about to start binding items
2308 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002309 public void run() {
2310 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2311 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002313 }
2314 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002315 };
Winson Chung81b52252012-08-27 15:34:29 -07002316 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002317
Adam Cohendcd297f2013-06-18 13:13:40 -07002318 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2319
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002320 // Load items on the current page
2321 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2322 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002323 if (isLoadingSynchronously) {
2324 r = new Runnable() {
2325 public void run() {
2326 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002327 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002328 callbacks.onPageBoundSynchronously(currentScreen);
2329 }
2330 }
2331 };
Winson Chung81b52252012-08-27 15:34:29 -07002332 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002333 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002334
Winson Chung4a2afa32012-07-19 14:53:05 -07002335 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2336 // work until after the first render)
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 mDeferredBindRunnables.clear();
2338 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002339 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002340
2341 // Tell the workspace that we're done binding items
2342 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002343 public void run() {
2344 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2345 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002346 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002347 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002348
Winson Chung98e030b2012-05-07 16:01:11 -07002349 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002350 if (DEBUG_LOADERS) {
2351 Log.d(TAG, "bound workspace in "
2352 + (SystemClock.uptimeMillis()-t) + "ms");
2353 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002354
2355 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002356 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002358 if (isLoadingSynchronously) {
2359 mDeferredBindRunnables.add(r);
2360 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002361 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002362 }
Joe Onorato36115782010-06-17 13:28:48 -04002363 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002364
Joe Onorato36115782010-06-17 13:28:48 -04002365 private void loadAndBindAllApps() {
2366 if (DEBUG_LOADERS) {
2367 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2368 }
2369 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002370 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002371 synchronized (LoaderTask.this) {
2372 if (mStopped) {
2373 return;
2374 }
2375 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002376 }
Joe Onorato36115782010-06-17 13:28:48 -04002377 } else {
2378 onlyBindAllApps();
2379 }
2380 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002381
Joe Onorato36115782010-06-17 13:28:48 -04002382 private void onlyBindAllApps() {
2383 final Callbacks oldCallbacks = mCallbacks.get();
2384 if (oldCallbacks == null) {
2385 // This launcher has exited and nobody bothered to tell us. Just bail.
2386 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2387 return;
2388 }
2389
2390 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002391 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002392 final ArrayList<AppInfo> list
2393 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002394 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002395 public void run() {
2396 final long t = SystemClock.uptimeMillis();
2397 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2398 if (callbacks != null) {
2399 callbacks.bindAllApplications(list);
2400 }
2401 if (DEBUG_LOADERS) {
2402 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2403 + (SystemClock.uptimeMillis()-t) + "ms");
2404 }
2405 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002406 };
2407 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002408 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002409 r.run();
2410 } else {
2411 mHandler.post(r);
2412 }
Joe Onorato36115782010-06-17 13:28:48 -04002413 }
2414
Winson Chung64359a52013-07-08 17:17:08 -07002415 private void loadAllApps() {
2416 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002417
Joe Onorato36115782010-06-17 13:28:48 -04002418 final Callbacks oldCallbacks = mCallbacks.get();
2419 if (oldCallbacks == null) {
2420 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002421 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002422 return;
2423 }
2424
Winson Chung64359a52013-07-08 17:17:08 -07002425 final PackageManager packageManager = mContext.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04002426 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2427 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2428
Winson Chung64359a52013-07-08 17:17:08 -07002429 // Clear the list of apps
2430 mBgAllAppsList.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002431
Winson Chung64359a52013-07-08 17:17:08 -07002432 // Query for the set of apps
2433 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2434 List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
2435 if (DEBUG_LOADERS) {
2436 Log.d(TAG, "queryIntentActivities took "
2437 + (SystemClock.uptimeMillis()-qiaTime) + "ms");
2438 Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
2439 }
2440 // Fail if we don't have any apps
2441 if (apps == null || apps.isEmpty()) {
2442 return;
2443 }
2444 // Sort the applications by name
2445 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2446 Collections.sort(apps,
2447 new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
2448 if (DEBUG_LOADERS) {
2449 Log.d(TAG, "sort took "
2450 + (SystemClock.uptimeMillis()-sortTime) + "ms");
Joe Onorato9c1289c2009-08-17 11:03:03 -04002451 }
2452
Winson Chung64359a52013-07-08 17:17:08 -07002453 // Create the ApplicationInfos
Winson Chung64359a52013-07-08 17:17:08 -07002454 for (int i = 0; i < apps.size(); i++) {
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002455 ResolveInfo app = apps.get(i);
Bjorn Bringert1307f632013-10-03 22:31:03 +01002456 // This builds the icon bitmaps.
2457 mBgAllAppsList.add(new AppInfo(packageManager, app,
2458 mIconCache, mLabelCache));
Winson Chung64359a52013-07-08 17:17:08 -07002459 }
2460
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002461 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002462 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2463 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002464
2465 // Post callback on main thread
2466 mHandler.post(new Runnable() {
2467 public void run() {
2468 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002469 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002470 if (callbacks != null) {
2471 callbacks.bindAllApplications(added);
2472 if (DEBUG_LOADERS) {
2473 Log.d(TAG, "bound " + added.size() + " apps in "
2474 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2475 }
2476 } else {
2477 Log.i(TAG, "not binding apps: no Launcher activity");
2478 }
2479 }
2480 });
2481
Joe Onorato36115782010-06-17 13:28:48 -04002482 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002483 Log.d(TAG, "Icons processed in "
2484 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002485 }
2486 }
2487
2488 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002489 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002490 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2491 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2492 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2493 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2494 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2495 }
Joe Onorato36115782010-06-17 13:28:48 -04002496 }
2497 }
2498
2499 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002500 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002501 }
2502
2503 private class PackageUpdatedTask implements Runnable {
2504 int mOp;
2505 String[] mPackages;
2506
2507 public static final int OP_NONE = 0;
2508 public static final int OP_ADD = 1;
2509 public static final int OP_UPDATE = 2;
2510 public static final int OP_REMOVE = 3; // uninstlled
2511 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2512
2513
2514 public PackageUpdatedTask(int op, String[] packages) {
2515 mOp = op;
2516 mPackages = packages;
2517 }
2518
2519 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002520 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002521
2522 final String[] packages = mPackages;
2523 final int N = packages.length;
2524 switch (mOp) {
2525 case OP_ADD:
2526 for (int i=0; i<N; i++) {
2527 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002528 mBgAllAppsList.addPackage(context, packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002529 }
2530 break;
2531 case OP_UPDATE:
2532 for (int i=0; i<N; i++) {
2533 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002534 mBgAllAppsList.updatePackage(context, packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002535 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002536 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002537 }
2538 break;
2539 case OP_REMOVE:
2540 case OP_UNAVAILABLE:
2541 for (int i=0; i<N; i++) {
2542 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Adam Cohen487f7dd2012-06-28 18:12:10 -07002543 mBgAllAppsList.removePackage(packages[i]);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002544 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04002545 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04002546 }
2547 break;
2548 }
2549
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002550 ArrayList<AppInfo> added = null;
2551 ArrayList<AppInfo> modified = null;
2552 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04002553
Adam Cohen487f7dd2012-06-28 18:12:10 -07002554 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002555 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07002556 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002557 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07002558 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002559 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07002560 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04002561 }
Winson Chung5d55f332012-07-16 20:45:03 -07002562 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07002563 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07002564 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07002565 }
2566
Joe Onorato36115782010-06-17 13:28:48 -04002567 final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
2568 if (callbacks == null) {
2569 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
2570 return;
2571 }
2572
2573 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002574 // Ensure that we add all the workspace applications to the db
2575 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
Winson Chung94d67682013-09-25 16:29:40 -07002576 if (!AppsCustomizePagedView.DISABLE_ALL_APPS) {
2577 addAndBindAddedApps(context, new ArrayList<ItemInfo>(), cb, added);
2578 } else {
2579 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
2580 addAndBindAddedApps(context, addedInfos, cb, added);
2581 }
Joe Onorato36115782010-06-17 13:28:48 -04002582 }
2583 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002584 final ArrayList<AppInfo> modifiedFinal = modified;
Winson Chung64359a52013-07-08 17:17:08 -07002585
2586 // Update the launcher db to reflect the changes
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002587 for (AppInfo a : modifiedFinal) {
Winson Chung64359a52013-07-08 17:17:08 -07002588 ArrayList<ItemInfo> infos =
2589 getItemInfoForComponentName(a.componentName);
2590 for (ItemInfo i : infos) {
2591 if (isShortcutInfoUpdateable(i)) {
2592 ShortcutInfo info = (ShortcutInfo) i;
2593 info.title = a.title.toString();
2594 updateItemInDatabase(context, info);
2595 }
2596 }
2597 }
2598
Joe Onorato36115782010-06-17 13:28:48 -04002599 mHandler.post(new Runnable() {
2600 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002601 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2602 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04002603 callbacks.bindAppsUpdated(modifiedFinal);
2604 }
2605 }
2606 });
2607 }
Winson Chung83892cc2013-05-01 16:53:33 -07002608
Winson Chungdf95eb12013-10-16 14:57:07 -07002609 final ArrayList<String> removedPackageNames =
2610 new ArrayList<String>();
2611 if (mOp == OP_REMOVE) {
2612 // Mark all packages in the broadcast to be removed
2613 removedPackageNames.addAll(Arrays.asList(packages));
2614 } else if (mOp == OP_UPDATE) {
2615 // Mark disabled packages in the broadcast to be removed
2616 final PackageManager pm = context.getPackageManager();
2617 for (int i=0; i<N; i++) {
2618 if (isPackageDisabled(pm, packages[i])) {
2619 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07002620 }
2621 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002622 }
2623 // Remove all the components associated with this package
2624 for (String pn : removedPackageNames) {
2625 ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
2626 for (ItemInfo i : infos) {
2627 deleteItemFromDatabase(context, i);
2628 }
2629 }
2630 // Remove all the specific components
2631 for (AppInfo a : removedApps) {
2632 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName);
2633 for (ItemInfo i : infos) {
2634 deleteItemFromDatabase(context, i);
2635 }
2636 }
2637 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
2638 // Remove any queued items from the install queue
2639 String spKey = LauncherAppState.getSharedPreferencesKey();
2640 SharedPreferences sp =
2641 context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
2642 InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames);
2643 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04002644 mHandler.post(new Runnable() {
2645 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002646 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2647 if (callbacks == cb && cb != null) {
Winson Chungdf95eb12013-10-16 14:57:07 -07002648 callbacks.bindComponentsRemoved(removedPackageNames, removedApps);
Joe Onorato36115782010-06-17 13:28:48 -04002649 }
2650 }
2651 });
Joe Onoratobe386092009-11-17 17:32:16 -08002652 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002653
Michael Jurkac402cd92013-05-20 15:49:32 +02002654 final ArrayList<Object> widgetsAndShortcuts =
2655 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07002656 mHandler.post(new Runnable() {
2657 @Override
2658 public void run() {
Winson Chungcd2b0142011-06-08 16:02:26 -07002659 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2660 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02002661 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07002662 }
2663 }
2664 });
Adam Cohen4caf2982013-08-20 18:54:31 -07002665
2666 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07002667 mHandler.post(new Runnable() {
2668 public void run() {
2669 Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
2670 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07002671 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07002672 }
2673 }
2674 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04002675 }
2676 }
2677
Michael Jurkac402cd92013-05-20 15:49:32 +02002678 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
2679 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
2680 PackageManager packageManager = context.getPackageManager();
2681 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
2682 widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
2683 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2684 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
2685 Collections.sort(widgetsAndShortcuts,
2686 new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
2687 return widgetsAndShortcuts;
2688 }
2689
Winson Chungdf95eb12013-10-16 14:57:07 -07002690 private boolean isPackageDisabled(PackageManager pm, String packageName) {
2691 try {
2692 PackageInfo pi = pm.getPackageInfo(packageName, 0);
2693 return !pi.applicationInfo.enabled;
2694 } catch (NameNotFoundException e) {
2695 // Fall through
2696 }
2697 return false;
2698 }
Winson Chung1323b482013-08-05 12:41:55 -07002699 private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
Winson Chungee055712013-07-30 14:46:24 -07002700 if (cn == null) {
2701 return false;
2702 }
Winson Chungdf95eb12013-10-16 14:57:07 -07002703 if (isPackageDisabled(pm, cn.getPackageName())) {
2704 return false;
2705 }
Winson Chungee055712013-07-30 14:46:24 -07002706
2707 try {
Winson Chungba9c37f2013-08-30 14:11:37 -07002708 // Check the activity
Winson Chungdf95eb12013-10-16 14:57:07 -07002709 PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
Winson Chungee055712013-07-30 14:46:24 -07002710 return (pm.getActivityInfo(cn, 0) != null);
2711 } catch (NameNotFoundException e) {
2712 return false;
2713 }
2714 }
2715
Joe Onorato9c1289c2009-08-17 11:03:03 -04002716 /**
Joe Onorato56d82912010-03-07 14:32:10 -05002717 * This is called from the code that adds shortcuts from the intent receiver. This
2718 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04002719 */
Joe Onorato56d82912010-03-07 14:32:10 -05002720 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
Winson Chungc3eecff2011-07-11 17:44:15 -07002721 return getShortcutInfo(manager, intent, context, null, -1, -1, null);
Joe Onorato56d82912010-03-07 14:32:10 -05002722 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002723
Joe Onorato56d82912010-03-07 14:32:10 -05002724 /**
2725 * Make an ShortcutInfo object for a shortcut that is an application.
2726 *
2727 * If c is not null, then it will be used to fill in missing data like the title and icon.
2728 */
2729 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Winson Chungc3eecff2011-07-11 17:44:15 -07002730 Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Joe Onorato56d82912010-03-07 14:32:10 -05002731 ComponentName componentName = intent.getComponent();
Winson Chung1323b482013-08-05 12:41:55 -07002732 final ShortcutInfo info = new ShortcutInfo();
Winson Chung68fd3c32013-08-30 16:38:00 -07002733 if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Winson Chungee055712013-07-30 14:46:24 -07002734 Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002735 return null;
Winson Chung1323b482013-08-05 12:41:55 -07002736 } else {
2737 try {
2738 PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
2739 info.initFlagsAndFirstInstallTime(pi);
2740 } catch (NameNotFoundException e) {
2741 Log.d(TAG, "getPackInfo failed for package " +
2742 componentName.getPackageName());
2743 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002744 }
2745
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002746 // TODO: See if the PackageManager knows about this case. If it doesn't
2747 // then return null & delete this.
2748
Joe Onorato56d82912010-03-07 14:32:10 -05002749 // the resource -- This may implicitly give us back the fallback icon,
2750 // but don't worry about that. All we're doing with usingFallbackIcon is
2751 // to avoid saving lots of copies of that in the database, and most apps
2752 // have icons anyway.
Winson Chungc208ff92012-03-29 17:37:41 -07002753
2754 // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
2755 // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
2756 // via resolveActivity().
Winson Chungee055712013-07-30 14:46:24 -07002757 Bitmap icon = null;
Winson Chungc208ff92012-03-29 17:37:41 -07002758 ResolveInfo resolveInfo = null;
2759 ComponentName oldComponent = intent.getComponent();
2760 Intent newIntent = new Intent(intent.getAction(), null);
2761 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2762 newIntent.setPackage(oldComponent.getPackageName());
2763 List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
2764 for (ResolveInfo i : infos) {
2765 ComponentName cn = new ComponentName(i.activityInfo.packageName,
2766 i.activityInfo.name);
2767 if (cn.equals(oldComponent)) {
2768 resolveInfo = i;
2769 }
2770 }
2771 if (resolveInfo == null) {
2772 resolveInfo = manager.resolveActivity(intent, 0);
2773 }
Joe Onorato56d82912010-03-07 14:32:10 -05002774 if (resolveInfo != null) {
Winson Chungaac01e12011-08-17 10:37:13 -07002775 icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002776 }
Joe Onorato56d82912010-03-07 14:32:10 -05002777 // the db
2778 if (icon == null) {
2779 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002780 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002781 }
2782 }
2783 // the fallback icon
2784 if (icon == null) {
2785 icon = getFallbackIcon();
2786 info.usingFallbackIcon = true;
2787 }
2788 info.setIcon(icon);
2789
2790 // from the resource
2791 if (resolveInfo != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002792 ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
2793 if (labelCache != null && labelCache.containsKey(key)) {
2794 info.title = labelCache.get(key);
Winson Chungc3eecff2011-07-11 17:44:15 -07002795 } else {
2796 info.title = resolveInfo.activityInfo.loadLabel(manager);
2797 if (labelCache != null) {
Winson Chung5308f242011-08-18 12:12:41 -07002798 labelCache.put(key, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07002799 }
2800 }
Joe Onorato56d82912010-03-07 14:32:10 -05002801 }
2802 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04002803 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05002804 if (c != null) {
2805 info.title = c.getString(titleIndex);
2806 }
2807 }
2808 // fall back to the class name of the activity
2809 if (info.title == null) {
2810 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07002811 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002812 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
2813 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002814 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07002815
Winson Chung64359a52013-07-08 17:17:08 -07002816 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
2817 ItemInfoFilter f) {
2818 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
2819 for (ItemInfo i : infos) {
2820 if (i instanceof ShortcutInfo) {
2821 ShortcutInfo info = (ShortcutInfo) i;
2822 ComponentName cn = info.intent.getComponent();
2823 if (cn != null && f.filterItem(null, info, cn)) {
2824 filtered.add(info);
2825 }
2826 } else if (i instanceof FolderInfo) {
2827 FolderInfo info = (FolderInfo) i;
2828 for (ShortcutInfo s : info.contents) {
2829 ComponentName cn = s.intent.getComponent();
2830 if (cn != null && f.filterItem(info, s, cn)) {
2831 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07002832 }
2833 }
Winson Chung64359a52013-07-08 17:17:08 -07002834 } else if (i instanceof LauncherAppWidgetInfo) {
2835 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
2836 ComponentName cn = info.providerName;
2837 if (cn != null && f.filterItem(null, info, cn)) {
2838 filtered.add(info);
2839 }
Winson Chung8a435102012-08-30 17:16:53 -07002840 }
2841 }
Winson Chung64359a52013-07-08 17:17:08 -07002842 return new ArrayList<ItemInfo>(filtered);
2843 }
2844
2845 private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
Winson Chung64359a52013-07-08 17:17:08 -07002846 ItemInfoFilter filter = new ItemInfoFilter() {
2847 @Override
2848 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2849 return cn.getPackageName().equals(pn);
2850 }
2851 };
2852 return filterItemInfos(sBgItemsIdMap.values(), filter);
2853 }
2854
2855 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
Winson Chung64359a52013-07-08 17:17:08 -07002856 ItemInfoFilter filter = new ItemInfoFilter() {
2857 @Override
2858 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
2859 return cn.equals(cname);
2860 }
2861 };
2862 return filterItemInfos(sBgItemsIdMap.values(), filter);
2863 }
2864
2865 public static boolean isShortcutInfoUpdateable(ItemInfo i) {
2866 if (i instanceof ShortcutInfo) {
2867 ShortcutInfo info = (ShortcutInfo) i;
2868 // We need to check for ACTION_MAIN otherwise getComponent() might
2869 // return null for some shortcuts (for instance, for shortcuts to
2870 // web pages.)
2871 Intent intent = info.intent;
2872 ComponentName name = intent.getComponent();
2873 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
2874 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
2875 return true;
2876 }
2877 }
2878 return false;
Winson Chung8a435102012-08-30 17:16:53 -07002879 }
2880
2881 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08002882 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002883 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08002884 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05002885 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
2886 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002887
Joe Onorato56d82912010-03-07 14:32:10 -05002888 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07002889 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04002890 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002891
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07002892 // TODO: If there's an explicit component and we can't install that, delete it.
2893
Joe Onorato56d82912010-03-07 14:32:10 -05002894 info.title = c.getString(titleIndex);
2895
Joe Onorato9c1289c2009-08-17 11:03:03 -04002896 int iconType = c.getInt(iconTypeIndex);
2897 switch (iconType) {
2898 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
2899 String packageName = c.getString(iconPackageIndex);
2900 String resourceName = c.getString(iconResourceIndex);
2901 PackageManager packageManager = context.getPackageManager();
Joe Onorato56d82912010-03-07 14:32:10 -05002902 info.customIcon = false;
2903 // the resource
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002904 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -04002905 Resources resources = packageManager.getResourcesForApplication(packageName);
Joe Onorato56d82912010-03-07 14:32:10 -05002906 if (resources != null) {
2907 final int id = resources.getIdentifier(resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07002908 icon = Utilities.createIconBitmap(
2909 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002910 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002911 } catch (Exception e) {
Joe Onorato56d82912010-03-07 14:32:10 -05002912 // drop this. we have other places to look for icons
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002913 }
Joe Onorato56d82912010-03-07 14:32:10 -05002914 // the db
2915 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07002916 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002917 }
2918 // the fallback icon
2919 if (icon == null) {
2920 icon = getFallbackIcon();
2921 info.usingFallbackIcon = true;
2922 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002923 break;
2924 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07002925 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05002926 if (icon == null) {
2927 icon = getFallbackIcon();
2928 info.customIcon = false;
2929 info.usingFallbackIcon = true;
2930 } else {
2931 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002932 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002933 break;
2934 default:
Joe Onoratod8d22da2010-03-11 17:59:11 -08002935 icon = getFallbackIcon();
Joe Onorato56d82912010-03-07 14:32:10 -05002936 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002937 info.customIcon = false;
2938 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002939 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08002940 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002941 return info;
2942 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002943
Michael Jurka931dc972011-08-05 15:08:15 -07002944 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07002945 @SuppressWarnings("all") // suppress dead code warning
2946 final boolean debug = false;
2947 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05002948 Log.d(TAG, "getIconFromCursor app="
2949 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
2950 }
2951 byte[] data = c.getBlob(iconIndex);
2952 try {
Michael Jurka931dc972011-08-05 15:08:15 -07002953 return Utilities.createIconBitmap(
2954 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05002955 } catch (Exception e) {
2956 return null;
2957 }
2958 }
2959
Winson Chung3d503fb2011-07-13 17:25:49 -07002960 ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
2961 int cellX, int cellY, boolean notify) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07002962 final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
Adam Cohend9198822011-11-22 16:42:47 -08002963 if (info == null) {
2964 return null;
2965 }
Winson Chung3d503fb2011-07-13 17:25:49 -07002966 addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
Joe Onorato0589f0f2010-02-08 13:44:00 -08002967
2968 return info;
2969 }
2970
Winson Chunga9abd0e2010-10-27 17:18:37 -07002971 /**
Winson Chung55cef262010-10-28 14:14:18 -07002972 * Attempts to find an AppWidgetProviderInfo that matches the given component.
2973 */
2974 AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
2975 ComponentName component) {
2976 List<AppWidgetProviderInfo> widgets =
2977 AppWidgetManager.getInstance(context).getInstalledProviders();
2978 for (AppWidgetProviderInfo info : widgets) {
2979 if (info.provider.equals(component)) {
2980 return info;
2981 }
2982 }
2983 return null;
Winson Chunga9abd0e2010-10-27 17:18:37 -07002984 }
2985
Winson Chung68846fd2010-10-29 11:00:27 -07002986 /**
2987 * Returns a list of all the widgets that can handle configuration with a particular mimeType.
2988 */
2989 List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
2990 final PackageManager packageManager = context.getPackageManager();
2991 final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
2992 new ArrayList<WidgetMimeTypeHandlerData>();
2993
2994 final Intent supportsIntent =
2995 new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
2996 supportsIntent.setType(mimeType);
2997
2998 // Create a set of widget configuration components that we can test against
2999 final List<AppWidgetProviderInfo> widgets =
3000 AppWidgetManager.getInstance(context).getInstalledProviders();
3001 final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
3002 new HashMap<ComponentName, AppWidgetProviderInfo>();
3003 for (AppWidgetProviderInfo info : widgets) {
3004 configurationComponentToWidget.put(info.configure, info);
3005 }
3006
3007 // Run through each of the intents that can handle this type of clip data, and cross
3008 // reference them with the components that are actual configuration components
3009 final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
3010 PackageManager.MATCH_DEFAULT_ONLY);
3011 for (ResolveInfo info : activities) {
3012 final ActivityInfo activityInfo = info.activityInfo;
3013 final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
3014 activityInfo.name);
3015 if (configurationComponentToWidget.containsKey(infoComponent)) {
3016 supportedConfigurationActivities.add(
3017 new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
3018 configurationComponentToWidget.get(infoComponent)));
3019 }
3020 }
3021 return supportedConfigurationActivities;
3022 }
3023
Winson Chunga9abd0e2010-10-27 17:18:37 -07003024 ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003025 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3026 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3027 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3028
Adam Cohend9198822011-11-22 16:42:47 -08003029 if (intent == null) {
3030 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3031 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3032 return null;
3033 }
3034
Joe Onorato0589f0f2010-02-08 13:44:00 -08003035 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003036 boolean customIcon = false;
3037 ShortcutIconResource iconResource = null;
3038
3039 if (bitmap != null && bitmap instanceof Bitmap) {
3040 icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003041 customIcon = true;
3042 } else {
3043 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
3044 if (extra != null && extra instanceof ShortcutIconResource) {
3045 try {
3046 iconResource = (ShortcutIconResource) extra;
3047 final PackageManager packageManager = context.getPackageManager();
3048 Resources resources = packageManager.getResourcesForApplication(
3049 iconResource.packageName);
3050 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
Michael Jurkac9a96192010-11-01 11:52:08 -07003051 icon = Utilities.createIconBitmap(
3052 mIconCache.getFullResIcon(resources, id), context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003053 } catch (Exception e) {
3054 Log.w(TAG, "Could not load shortcut icon: " + extra);
3055 }
3056 }
3057 }
3058
Michael Jurkac9d95c52011-08-29 14:03:34 -07003059 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003060
3061 if (icon == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07003062 if (fallbackIcon != null) {
3063 icon = fallbackIcon;
3064 } else {
3065 icon = getFallbackIcon();
3066 info.usingFallbackIcon = true;
3067 }
Joe Onorato56d82912010-03-07 14:32:10 -05003068 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003069 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003070
Joe Onorato0589f0f2010-02-08 13:44:00 -08003071 info.title = name;
3072 info.intent = intent;
3073 info.customIcon = customIcon;
3074 info.iconResource = iconResource;
3075
3076 return info;
3077 }
3078
Winson Chungaac01e12011-08-17 10:37:13 -07003079 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3080 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003081 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003082 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003083 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003084 }
Joe Onorato56d82912010-03-07 14:32:10 -05003085 // If this icon doesn't have a custom icon, check to see
3086 // what's stored in the DB, and if it doesn't match what
3087 // we're going to show, store what we are going to show back
3088 // into the DB. We do this so when we're loading, if the
3089 // package manager can't find an icon (for example because
3090 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003091 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003092 cache.put(info, c.getBlob(iconIndex));
3093 return true;
3094 }
3095 return false;
3096 }
3097 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3098 boolean needSave = false;
3099 try {
3100 if (data != null) {
3101 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3102 Bitmap loaded = info.getIcon(mIconCache);
3103 needSave = !saved.sameAs(loaded);
3104 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003105 needSave = true;
3106 }
Winson Chungaac01e12011-08-17 10:37:13 -07003107 } catch (Exception e) {
3108 needSave = true;
3109 }
3110 if (needSave) {
3111 Log.d(TAG, "going to save icon bitmap for info=" + info);
3112 // This is slower than is ideal, but this only happens once
3113 // or when the app is updated with a new icon.
3114 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003115 }
3116 }
3117
Joe Onorato9c1289c2009-08-17 11:03:03 -04003118 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003119 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003120 * or make a new one.
3121 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003122 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003123 // See if a placeholder was created for us already
3124 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003125 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003126 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003127 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003128 folders.put(id, folderInfo);
3129 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003130 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003131 }
3132
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003133 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003134 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003135 return new Comparator<AppInfo>() {
3136 public final int compare(AppInfo a, AppInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003137 int result = collator.compare(a.title.toString().trim(),
3138 b.title.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003139 if (result == 0) {
3140 result = a.componentName.compareTo(b.componentName);
3141 }
3142 return result;
Michael Jurka5b1808d2011-07-11 19:59:46 -07003143 }
Winson Chung11904872012-09-17 16:58:46 -07003144 };
3145 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003146 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3147 = new Comparator<AppInfo>() {
3148 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003149 if (a.firstInstallTime < b.firstInstallTime) return 1;
3150 if (a.firstInstallTime > b.firstInstallTime) return -1;
3151 return 0;
3152 }
3153 };
Winson Chung11904872012-09-17 16:58:46 -07003154 public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
3155 final Collator collator = Collator.getInstance();
3156 return new Comparator<AppWidgetProviderInfo>() {
3157 public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
Winson Chung780fe592013-09-26 14:48:44 -07003158 return collator.compare(a.label.toString().trim(), b.label.toString().trim());
Winson Chung11904872012-09-17 16:58:46 -07003159 }
3160 };
3161 }
Winson Chung5308f242011-08-18 12:12:41 -07003162 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3163 if (info.activityInfo != null) {
3164 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3165 } else {
3166 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3167 }
3168 }
Winson Chung785d2eb2011-04-14 16:08:02 -07003169 public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
Winson Chung11904872012-09-17 16:58:46 -07003170 private Collator mCollator;
Winson Chung785d2eb2011-04-14 16:08:02 -07003171 private PackageManager mPackageManager;
Winson Chungc3eecff2011-07-11 17:44:15 -07003172 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003173 ShortcutNameComparator(PackageManager pm) {
3174 mPackageManager = pm;
Winson Chungc3eecff2011-07-11 17:44:15 -07003175 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003176 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003177 }
3178 ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
3179 mPackageManager = pm;
3180 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003181 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003182 }
3183 public final int compare(ResolveInfo a, ResolveInfo b) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003184 CharSequence labelA, labelB;
Winson Chung5308f242011-08-18 12:12:41 -07003185 ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
3186 ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
3187 if (mLabelCache.containsKey(keyA)) {
3188 labelA = mLabelCache.get(keyA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003189 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003190 labelA = a.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003191
Winson Chung5308f242011-08-18 12:12:41 -07003192 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003193 }
Winson Chung5308f242011-08-18 12:12:41 -07003194 if (mLabelCache.containsKey(keyB)) {
3195 labelB = mLabelCache.get(keyB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003196 } else {
Winson Chung780fe592013-09-26 14:48:44 -07003197 labelB = b.loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003198
Winson Chung5308f242011-08-18 12:12:41 -07003199 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003200 }
Winson Chung11904872012-09-17 16:58:46 -07003201 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003202 }
3203 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003204 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Winson Chung11904872012-09-17 16:58:46 -07003205 private Collator mCollator;
Winson Chung1ed747a2011-05-03 16:18:34 -07003206 private PackageManager mPackageManager;
3207 private HashMap<Object, String> mLabelCache;
3208 WidgetAndShortcutNameComparator(PackageManager pm) {
3209 mPackageManager = pm;
3210 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003211 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003212 }
3213 public final int compare(Object a, Object b) {
3214 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003215 if (mLabelCache.containsKey(a)) {
3216 labelA = mLabelCache.get(a);
3217 } else {
3218 labelA = (a instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003219 ((AppWidgetProviderInfo) a).label :
Winson Chung780fe592013-09-26 14:48:44 -07003220 ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003221 mLabelCache.put(a, labelA);
3222 }
3223 if (mLabelCache.containsKey(b)) {
3224 labelB = mLabelCache.get(b);
3225 } else {
3226 labelB = (b instanceof AppWidgetProviderInfo) ?
Winson Chung1ed747a2011-05-03 16:18:34 -07003227 ((AppWidgetProviderInfo) b).label :
Winson Chung780fe592013-09-26 14:48:44 -07003228 ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003229 mLabelCache.put(b, labelB);
3230 }
Winson Chung11904872012-09-17 16:58:46 -07003231 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003232 }
3233 };
Joe Onoratobe386092009-11-17 17:32:16 -08003234
3235 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003236 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003237 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3238 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3239 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3240 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003241 if (mLoaderTask != null) {
3242 mLoaderTask.dumpState();
3243 } else {
3244 Log.d(TAG, "mLoaderTask=null");
3245 }
Joe Onoratobe386092009-11-17 17:32:16 -08003246 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003247}