blob: 3c1cf485d22b0e28420b4ef276071767449f52e4 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
Sunny Goyale0f58d72014-11-10 18:05:31 -080032import android.content.pm.LauncherApps.Callback;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040034import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070036import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.content.res.Resources;
38import android.database.Cursor;
39import android.graphics.Bitmap;
40import android.graphics.BitmapFactory;
41import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040049import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080050import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070051import android.util.Log;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Adam Cohendcd297f2013-06-18 13:13:40 -070077import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079/**
80 * Maintains in-memory state of the Launcher. It is expected that there should be only one
81 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070082 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 */
Kenny Guyed131872014-04-30 03:02:21 +010084public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010085 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080086 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040087 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070088 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080089 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040090
Joe Onorato9c1289c2009-08-17 11:03:03 -040091 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070092
Daniel Sandler8707e0f2013-08-15 15:54:18 -070093 // true = use a "More Apps" folder for non-workspace apps on upgrade
94 // false = strew non-workspace apps across the workspace on upgrade
95 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050096 public static final int LOADER_FLAG_NONE = 0;
97 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
98 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
99
Joe Onorato36115782010-06-17 13:28:48 -0400100 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500101 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800102
Winson Chungee055712013-07-30 14:46:24 -0700103 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800104 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400105
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400106 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400107 private final Object mLock = new Object();
108 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400109 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700110 private boolean mIsLoaderTaskRunning;
Michael Jurkac7700af2013-05-14 20:17:58 +0200111 private volatile boolean mFlushingWorkerThread;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Sunny Goyale0f58d72014-11-10 18:05:31 -0800113 /**
114 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
115 */
116 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
117
Winson Chung81b52252012-08-27 15:34:29 -0700118 // Specific runnable types that are run on the main thread deferred handler, this allows us to
119 // clear all queued binding runnables when the Launcher activity is destroyed.
120 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
121 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
122
Jason Monkbbe1e242014-05-16 17:37:34 -0400123 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700124
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700125 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
126 static {
127 sWorkerThread.start();
128 }
129 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
130
Joe Onoratocc67f472010-06-08 10:54:30 -0700131 // We start off with everything not loaded. After that, we assume that
132 // our monitoring of the package manager provides all updates and we never
133 // need to do a requery. These are only ever touched from the loader thread.
134 private boolean mWorkspaceLoaded;
135 private boolean mAllAppsLoaded;
136
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700137 // When we are loading pages synchronously, we can't just post the binding of items on the side
138 // pages as this delays the rotation process. Instead, we wait for a callback from the first
139 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
140 // a normal load, we also clear this set of Runnables.
141 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
142
Joe Onorato9c1289c2009-08-17 11:03:03 -0400143 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800144
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700146 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800147
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148 // The lock that must be acquired before referencing any static bg data structures. Unlike
149 // other locks, this one can generally be held long-term because we never expect any of these
150 // static data structures to be referenced outside of the worker thread except on the first
151 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700152 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700153
Adam Cohen487f7dd2012-06-28 18:12:10 -0700154 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700156 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
159 // created by LauncherModel that are directly on the home screen (however, no widgets or
160 // shortcuts within folders).
161 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
164 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 new ArrayList<LauncherAppWidgetInfo>();
166
Adam Cohen487f7dd2012-06-28 18:12:10 -0700167 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
168 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700169
Adam Cohen487f7dd2012-06-28 18:12:10 -0700170 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
171 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700172
173 // sBgWorkspaceScreens is the ordered set of workspace screens.
174 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
175
Adam Cohen59400422014-03-05 18:07:04 -0800176 // sBgWidgetProviders is the set of widget providers including custom internal widgets
177 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
178 public static boolean sWidgetProvidersDirty;
179
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700180 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700181 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
182 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700183
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 // </ only access in worker thread >
185
186 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187
Reena Lee99a73f32011-10-24 17:27:37 -0700188 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700189
Kenny Guyed131872014-04-30 03:02:21 +0100190 private final LauncherAppsCompat mLauncherApps;
191 private final UserManagerCompat mUserManager;
192
Joe Onorato9c1289c2009-08-17 11:03:03 -0400193 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700194 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400195 public int getCurrentWorkspaceScreen();
196 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700197 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
198 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700199 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700200 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500201 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700202 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400203 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200204 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700205 public void bindAppsAdded(ArrayList<Long> newScreens,
206 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700207 ArrayList<ItemInfo> addAnimated,
208 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200209 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700210 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
211 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
212 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700213 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700214 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700215 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700216 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200217 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100218 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700219 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700220 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700221 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400222 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223
Winson Chung64359a52013-07-08 17:17:08 -0700224 public interface ItemInfoFilter {
225 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
226 }
227
Bjorn Bringert1307f632013-10-03 22:31:03 +0100228 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800229 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400230
Winson Chungee055712013-07-30 14:46:24 -0700231 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700232 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400233 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
234 // resource string.
235 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
236 ProviderInfo providerInfo =
237 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
238 ProviderInfo redirectProvider =
239 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700240
241 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400242 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700243
244 if (mOldContentProviderExists) {
245 Log.d(TAG, "Old launcher provider exists.");
246 } else {
247 Log.d(TAG, "Old launcher provider does not exist.");
248 }
249
Daniel Sandlere4f98912013-06-25 15:13:26 -0400250 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100251 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800252 mIconCache = iconCache;
253
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400254 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700255 Configuration config = res.getConfiguration();
256 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100257 mLauncherApps = LauncherAppsCompat.getInstance(context);
258 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800259 }
260
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700261 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
262 * posted on the main thread handler. */
263 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700264 runOnMainThread(r, 0);
265 }
266 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700267 if (sWorkerThread.getThreadId() == Process.myTid()) {
268 // If we are on the worker thread, post onto the main handler
269 mHandler.post(r);
270 } else {
271 r.run();
272 }
273 }
274
275 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
276 * posted on the worker thread handler. */
277 private static void runOnWorkerThread(Runnable r) {
278 if (sWorkerThread.getThreadId() == Process.myTid()) {
279 r.run();
280 } else {
281 // If we are not on the worker thread, then post to the worker handler
282 sWorker.post(r);
283 }
284 }
285
Winson Chunge43a1e72014-01-15 10:33:02 -0800286 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
287 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800288 }
289
Winson Chungc9168342013-06-26 14:54:55 -0700290 static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
291 long screen) {
Winson Chung892c74d2013-08-22 16:15:50 -0700292 LauncherAppState app = LauncherAppState.getInstance();
293 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
294 final int xCount = (int) grid.numColumns;
295 final int yCount = (int) grid.numRows;
Winson Chungc9168342013-06-26 14:54:55 -0700296 boolean[][] occupied = new boolean[xCount][yCount];
297
298 int cellX, cellY, spanX, spanY;
299 for (int i = 0; i < items.size(); ++i) {
300 final ItemInfo item = items.get(i);
301 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
302 if (item.screenId == screen) {
303 cellX = item.cellX;
304 cellY = item.cellY;
305 spanX = item.spanX;
306 spanY = item.spanY;
307 for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
308 for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
309 occupied[x][y] = true;
310 }
311 }
312 }
313 }
314 }
315
316 return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
317 }
318 static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Winson Chung156ab5b2013-07-12 14:14:16 -0700319 Intent launchIntent,
Winson Chung76828c82013-08-19 15:43:29 -0700320 int firstScreenIndex,
321 ArrayList<Long> workspaceScreens) {
Winson Chungc9168342013-06-26 14:54:55 -0700322 // Lock on the app so that we don't try and get the items while apps are being added
323 LauncherAppState app = LauncherAppState.getInstance();
324 LauncherModel model = app.getModel();
325 boolean found = false;
326 synchronized (app) {
Winson Chung64359a52013-07-08 17:17:08 -0700327 if (sWorkerThread.getThreadId() != Process.myTid()) {
328 // Flush the LauncherModel worker thread, so that if we just did another
329 // processInstallShortcut, we give it time for its shortcut to get added to the
330 // database (getItemsInLocalCoordinates reads the database)
331 model.flushWorkerThread();
332 }
Winson Chungc9168342013-06-26 14:54:55 -0700333 final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
Winson Chungc9168342013-06-26 14:54:55 -0700334
335 // Try adding to the workspace screens incrementally, starting at the default or center
336 // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
Winson Chung76828c82013-08-19 15:43:29 -0700337 firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
338 int count = workspaceScreens.size();
Winson Chung156ab5b2013-07-12 14:14:16 -0700339 for (int screen = firstScreenIndex; screen < count && !found; screen++) {
Winson Chungc9168342013-06-26 14:54:55 -0700340 int[] tmpCoordinates = new int[2];
341 if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
Winson Chung76828c82013-08-19 15:43:29 -0700342 workspaceScreens.get(screen))) {
Winson Chungc9168342013-06-26 14:54:55 -0700343 // Update the Launcher db
Winson Chung76828c82013-08-19 15:43:29 -0700344 return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
Winson Chungc9168342013-06-26 14:54:55 -0700345 }
346 }
347 }
Winson Chungc9168342013-06-26 14:54:55 -0700348 return null;
349 }
350
Sunny Goyale755d462014-07-22 13:48:29 -0700351 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500352 // Process the updated package state
353 Runnable r = new Runnable() {
354 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800355 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500356 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700357 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500358 }
359 }
360 };
361 mHandler.post(r);
362 }
363
Sunny Goyala22666f2014-09-18 13:25:15 -0700364 public void updatePackageBadge(final String packageName) {
365 // Process the updated package badge
366 Runnable r = new Runnable() {
367 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800368 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700369 if (callbacks != null) {
370 callbacks.updatePackageBadge(packageName);
371 }
372 }
373 };
374 mHandler.post(r);
375 }
376
Adam Cohen76a47a12014-02-05 11:47:43 -0800377 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800378 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800379
380 if (allAppsApps == null) {
381 throw new RuntimeException("allAppsApps must not be null");
382 }
383 if (allAppsApps.isEmpty()) {
384 return;
385 }
386
387 // Process the newly added applications and add them to the database first
388 Runnable r = new Runnable() {
389 public void run() {
390 runOnMainThread(new Runnable() {
391 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800392 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800393 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500394 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800395 }
396 }
397 });
398 }
399 };
400 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700401 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800402
403 public void addAndBindAddedWorkspaceApps(final Context context,
404 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800405 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800406
407 if (workspaceApps == null) {
Winson Chungfe9d96a2013-11-14 11:30:05 -0800408 throw new RuntimeException("workspaceApps and allAppsApps must not be null");
409 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800410 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700411 return;
Winson Chung997a9232013-07-24 15:33:46 -0700412 }
Winson Chung64359a52013-07-08 17:17:08 -0700413 // Process the newly added applications and add them to the database first
414 Runnable r = new Runnable() {
415 public void run() {
416 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
417 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
418
Winson Chung76828c82013-08-19 15:43:29 -0700419 // Get the list of workspace screens. We need to append to this list and
420 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
421 // called.
422 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
423 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
424 for (Integer i : orderedScreens.keySet()) {
425 long screenId = orderedScreens.get(i);
426 workspaceScreens.add(screenId);
427 }
428
Winson Chung64359a52013-07-08 17:17:08 -0700429 synchronized(sBgLock) {
Winson Chung94d67682013-09-25 16:29:40 -0700430 Iterator<ItemInfo> iter = workspaceApps.iterator();
Winson Chung64359a52013-07-08 17:17:08 -0700431 while (iter.hasNext()) {
Winson Chung997a9232013-07-24 15:33:46 -0700432 ItemInfo a = iter.next();
Winson Chung64359a52013-07-08 17:17:08 -0700433 final String name = a.title.toString();
Winson Chung997a9232013-07-24 15:33:46 -0700434 final Intent launchIntent = a.getIntent();
Winson Chung64359a52013-07-08 17:17:08 -0700435
436 // Short-circuit this logic if the icon exists somewhere on the workspace
Sunny Goyale0f58d72014-11-10 18:05:31 -0800437 if (shortcutExists(context, name, launchIntent, a.user)) {
Winson Chung64359a52013-07-08 17:17:08 -0700438 continue;
439 }
440
Winson Chung87412982013-10-03 18:34:14 -0700441 // Add this icon to the db, creating a new page if necessary. If there
442 // is only the empty page then we just add items to the first page.
443 // Otherwise, we add them to the next pages.
444 int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1;
Winson Chung64359a52013-07-08 17:17:08 -0700445 Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700446 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700447 if (coords == null) {
Michael Jurka414300a2013-08-27 15:42:35 +0200448 LauncherProvider lp = LauncherAppState.getLauncherProvider();
Winson Chungc763c4e2013-07-19 13:49:06 -0700449
450 // If we can't find a valid position, then just add a new screen.
451 // This takes time so we need to re-queue the add until the new
452 // page is added. Create as many screens as necessary to satisfy
453 // the startSearchPageIndex.
454 int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
Winson Chung76828c82013-08-19 15:43:29 -0700455 workspaceScreens.size());
Winson Chungc763c4e2013-07-19 13:49:06 -0700456 while (numPagesToAdd > 0) {
457 long screenId = lp.generateNewScreenId();
Winson Chungc763c4e2013-07-19 13:49:06 -0700458 // Save the screen id for binding in the workspace
Winson Chung76828c82013-08-19 15:43:29 -0700459 workspaceScreens.add(screenId);
Winson Chungc763c4e2013-07-19 13:49:06 -0700460 addedWorkspaceScreensFinal.add(screenId);
461 numPagesToAdd--;
462 }
Winson Chung76828c82013-08-19 15:43:29 -0700463
Winson Chung64359a52013-07-08 17:17:08 -0700464 // Find the coordinate again
465 coords = LauncherModel.findNextAvailableIconSpace(context,
Winson Chung76828c82013-08-19 15:43:29 -0700466 name, launchIntent, startSearchPageIndex, workspaceScreens);
Winson Chung64359a52013-07-08 17:17:08 -0700467 }
468 if (coords == null) {
469 throw new RuntimeException("Coordinates should not be null");
470 }
471
Winson Chung997a9232013-07-24 15:33:46 -0700472 ShortcutInfo shortcutInfo;
473 if (a instanceof ShortcutInfo) {
474 shortcutInfo = (ShortcutInfo) a;
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200475 } else if (a instanceof AppInfo) {
476 shortcutInfo = ((AppInfo) a).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700477 } else {
478 throw new RuntimeException("Unexpected info type");
479 }
Winson Chung94d67682013-09-25 16:29:40 -0700480
Winson Chung64359a52013-07-08 17:17:08 -0700481 // Add the shortcut to the db
482 addItemToDatabase(context, shortcutInfo,
483 LauncherSettings.Favorites.CONTAINER_DESKTOP,
484 coords.first, coords.second[0], coords.second[1], false);
485 // Save the ShortcutInfo for binding in the workspace
486 addedShortcutsFinal.add(shortcutInfo);
487 }
488 }
489
Winson Chung76828c82013-08-19 15:43:29 -0700490 // Update the workspace screens
491 updateWorkspaceScreenOrder(context, workspaceScreens);
492
Adam Cohen76a47a12014-02-05 11:47:43 -0800493 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700494 runOnMainThread(new Runnable() {
495 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800496 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700497 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700498 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
499 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700500 if (!addedShortcutsFinal.isEmpty()) {
501 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
502 long lastScreenId = info.screenId;
503 for (ItemInfo i : addedShortcutsFinal) {
504 if (i.screenId == lastScreenId) {
505 addAnimated.add(i);
506 } else {
507 addNotAnimated.add(i);
508 }
Winson Chung997a9232013-07-24 15:33:46 -0700509 }
510 }
Winson Chungd64d1762013-08-20 14:37:16 -0700511 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800512 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700513 }
Winson Chung64359a52013-07-08 17:17:08 -0700514 }
Winson Chung997a9232013-07-24 15:33:46 -0700515 });
516 }
Winson Chung64359a52013-07-08 17:17:08 -0700517 }
518 };
519 runOnWorkerThread(r);
520 }
521
Winson Chung81b52252012-08-27 15:34:29 -0700522 public void unbindItemInfosAndClearQueuedBindRunnables() {
523 if (sWorkerThread.getThreadId() == Process.myTid()) {
524 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
525 "main thread");
526 }
527
528 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400529 synchronized (mDeferredBindRunnables) {
530 mDeferredBindRunnables.clear();
531 }
Winson Chung81b52252012-08-27 15:34:29 -0700532 // Remove any queued bind runnables
533 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
534 // Unbind all the workspace items
535 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700536 }
537
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700538 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700539 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700540 // Ensure that we don't use the same workspace items data structure on the main thread
541 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700542 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
543 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700544 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700545 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
546 tmpAppWidgets.addAll(sBgAppWidgets);
547 }
548 Runnable r = new Runnable() {
549 @Override
550 public void run() {
551 for (ItemInfo item : tmpWorkspaceItems) {
552 item.unbind();
553 }
554 for (ItemInfo item : tmpAppWidgets) {
555 item.unbind();
556 }
557 }
558 };
559 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700560 }
561
Joe Onorato9c1289c2009-08-17 11:03:03 -0400562 /**
563 * Adds an item to the DB if it was not created previously, or move it to a new
564 * <container, screen, cellX, cellY>
565 */
566 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700567 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400568 if (item.container == ItemInfo.NO_ID) {
569 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700570 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400571 } else {
572 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800574 }
575 }
576
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700577 static void checkItemInfoLocked(
578 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
579 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
580 if (modelItem != null && item != modelItem) {
581 // check all the data is consistent
582 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
583 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
584 ShortcutInfo shortcut = (ShortcutInfo) item;
585 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
586 modelShortcut.intent.filterEquals(shortcut.intent) &&
587 modelShortcut.id == shortcut.id &&
588 modelShortcut.itemType == shortcut.itemType &&
589 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700590 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700591 modelShortcut.cellX == shortcut.cellX &&
592 modelShortcut.cellY == shortcut.cellY &&
593 modelShortcut.spanX == shortcut.spanX &&
594 modelShortcut.spanY == shortcut.spanY &&
595 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
596 (modelShortcut.dropPos != null &&
597 shortcut.dropPos != null &&
598 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
599 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
600 // For all intents and purposes, this is the same object
601 return;
602 }
603 }
604
605 // the modelItem needs to match up perfectly with item if our model is
606 // to be consistent with the database-- for now, just require
607 // modelItem == item or the equality check above
608 String msg = "item: " + ((item != null) ? item.toString() : "null") +
609 "modelItem: " +
610 ((modelItem != null) ? modelItem.toString() : "null") +
611 "Error: ItemInfo passed to checkItemInfo doesn't match original";
612 RuntimeException e = new RuntimeException(msg);
613 if (stackTrace != null) {
614 e.setStackTrace(stackTrace);
615 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800616 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700617 }
618 }
619
Michael Jurka816474f2012-06-25 14:49:02 -0700620 static void checkItemInfo(final ItemInfo item) {
621 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
622 final long itemId = item.id;
623 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700624 public void run() {
625 synchronized (sBgLock) {
626 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700627 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700628 }
629 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700630 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700631 }
632
Michael Jurkac9d95c52011-08-29 14:03:34 -0700633 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
634 final ItemInfo item, final String callingFunction) {
635 final long itemId = item.id;
636 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
637 final ContentResolver cr = context.getContentResolver();
638
Adam Cohen487f7dd2012-06-28 18:12:10 -0700639 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700640 Runnable r = new Runnable() {
641 public void run() {
642 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700643 updateItemArrays(item, itemId, stackTrace);
644 }
645 };
646 runOnWorkerThread(r);
647 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700648
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700649 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
650 final ArrayList<ItemInfo> items, final String callingFunction) {
651 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700652
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700653 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
654 Runnable r = new Runnable() {
655 public void run() {
656 ArrayList<ContentProviderOperation> ops =
657 new ArrayList<ContentProviderOperation>();
658 int count = items.size();
659 for (int i = 0; i < count; i++) {
660 ItemInfo item = items.get(i);
661 final long itemId = item.id;
662 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
663 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700664
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700665 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
666 updateItemArrays(item, itemId, stackTrace);
667
668 }
669 try {
670 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
671 } catch (Exception e) {
672 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700673 }
674 }
675 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700676 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700677 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700678
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700679 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
680 // Lock on mBgLock *after* the db operation
681 synchronized (sBgLock) {
682 checkItemInfoLocked(itemId, item, stackTrace);
683
684 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
685 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
686 // Item is in a folder, make sure this folder exists
687 if (!sBgFolders.containsKey(item.container)) {
688 // An items container is being set to a that of an item which is not in
689 // the list of Folders.
690 String msg = "item: " + item + " container being set to: " +
691 item.container + ", not in the list of folders";
692 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700693 }
694 }
695
696 // Items are added/removed from the corresponding FolderInfo elsewhere, such
697 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
698 // that are on the desktop, as appropriate
699 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800700 if (modelItem != null &&
701 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
702 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700703 switch (modelItem.itemType) {
704 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
705 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
706 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
707 if (!sBgWorkspaceItems.contains(modelItem)) {
708 sBgWorkspaceItems.add(modelItem);
709 }
710 break;
711 default:
712 break;
713 }
714 } else {
715 sBgWorkspaceItems.remove(modelItem);
716 }
717 }
718 }
719
Michael Jurkac7700af2013-05-14 20:17:58 +0200720 public void flushWorkerThread() {
721 mFlushingWorkerThread = true;
722 Runnable waiter = new Runnable() {
723 public void run() {
724 synchronized (this) {
725 notifyAll();
726 mFlushingWorkerThread = false;
727 }
728 }
729 };
730
731 synchronized(waiter) {
732 runOnWorkerThread(waiter);
733 if (mLoaderTask != null) {
734 synchronized(mLoaderTask) {
735 mLoaderTask.notify();
736 }
737 }
738 boolean success = false;
739 while (!success) {
740 try {
741 waiter.wait();
742 success = true;
743 } catch (InterruptedException e) {
744 }
745 }
746 }
747 }
748
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400750 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700751 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700752 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700753 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400754 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400755 item.cellX = cellX;
756 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757
Winson Chung3d503fb2011-07-13 17:25:49 -0700758 // We store hotseat items in canonical form which is this orientation invariant position
759 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700760 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700761 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700762 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700763 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700764 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700765 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400766
767 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400768 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700769 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
770 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700771 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400772
Michael Jurkac9d95c52011-08-29 14:03:34 -0700773 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700774 }
775
776 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700777 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
778 * cellX, cellY have already been updated on the ItemInfos.
779 */
780 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
781 final long container, final int screen) {
782
783 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
784 int count = items.size();
785
786 for (int i = 0; i < count; i++) {
787 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700788 item.container = container;
789
790 // We store hotseat items in canonical form which is this orientation invariant position
791 // in the hotseat
792 if (context instanceof Launcher && screen < 0 &&
793 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700794 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700795 item.cellY);
796 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700797 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700798 }
799
800 final ContentValues values = new ContentValues();
801 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
802 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
803 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700805
806 contentValues.add(values);
807 }
808 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
809 }
810
811 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700812 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800813 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700814 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700816 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800817 item.cellX = cellX;
818 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700819 item.spanX = spanX;
820 item.spanY = spanY;
821
822 // We store hotseat items in canonical form which is this orientation invariant position
823 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700825 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700827 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700829 }
Adam Cohend4844c32011-02-18 19:25:06 -0800830
Adam Cohend4844c32011-02-18 19:25:06 -0800831 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800832 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700833 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
834 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
835 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
836 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700837 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800838
Michael Jurka816474f2012-06-25 14:49:02 -0700839 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700840 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700841
842 /**
843 * Update an item to the database in a specified container.
844 */
845 static void updateItemInDatabase(Context context, final ItemInfo item) {
846 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100847 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700848 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
849 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800850 }
851
852 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400853 * Returns true if the shortcuts already exists in the database.
854 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800855 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800856 static boolean shortcutExists(Context context, String title, Intent intent,
857 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400858 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700859 final Intent intentWithPkg, intentWithoutPkg;
860
861 if (intent.getComponent() != null) {
862 // If component is not null, an intent with null package will produce
863 // the same result and should also be a match.
864 if (intent.getPackage() != null) {
865 intentWithPkg = intent;
866 intentWithoutPkg = new Intent(intent).setPackage(null);
867 } else {
868 intentWithPkg = new Intent(intent).setPackage(
869 intent.getComponent().getPackageName());
870 intentWithoutPkg = intent;
871 }
872 } else {
873 intentWithPkg = intent;
874 intentWithoutPkg = intent;
875 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800876 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
877 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400878 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800879 new String[] { "title", "intent", "profileId" },
880 "title=? and (intent=? or intent=?) and profileId=?",
881 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
882 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400883 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800884 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400885 } finally {
886 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800887 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700888 }
889
Joe Onorato9c1289c2009-08-17 11:03:03 -0400890 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700891 * Returns an ItemInfo array containing all the items in the LauncherModel.
892 * The ItemInfo.id is not set through this function.
893 */
894 static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
895 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
896 final ContentResolver cr = context.getContentResolver();
897 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
898 LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
Kenny Guyed131872014-04-30 03:02:21 +0100899 LauncherSettings.Favorites.SCREEN,
900 LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
901 LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY,
902 LauncherSettings.Favorites.PROFILE_ID }, null, null, null);
Winson Chungaafa03c2010-06-11 17:34:16 -0700903
904 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
905 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
906 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
907 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
908 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
909 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
910 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
Kenny Guyed131872014-04-30 03:02:21 +0100911 final int profileIdIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.PROFILE_ID);
912 UserManagerCompat userManager = UserManagerCompat.getInstance(context);
Winson Chungaafa03c2010-06-11 17:34:16 -0700913 try {
914 while (c.moveToNext()) {
Michael Jurkac9d95c52011-08-29 14:03:34 -0700915 ItemInfo item = new ItemInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -0700916 item.cellX = c.getInt(cellXIndex);
917 item.cellY = c.getInt(cellYIndex);
Winson Chung61c69862013-08-21 19:10:29 -0700918 item.spanX = Math.max(1, c.getInt(spanXIndex));
919 item.spanY = Math.max(1, c.getInt(spanYIndex));
Winson Chungaafa03c2010-06-11 17:34:16 -0700920 item.container = c.getInt(containerIndex);
921 item.itemType = c.getInt(itemTypeIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700922 item.screenId = c.getInt(screenIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +0100923 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +0100924 item.user = userManager.getUserForSerialNumber(serialNumber);
925 // Skip if user has been deleted.
926 if (item.user != null) {
927 items.add(item);
928 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700929 }
930 } catch (Exception e) {
931 items.clear();
932 } finally {
933 c.close();
934 }
935
936 return items;
937 }
938
939 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400940 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
941 */
942 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
943 final ContentResolver cr = context.getContentResolver();
944 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
945 "_id=? and (itemType=? or itemType=?)",
946 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700947 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700948
Joe Onorato9c1289c2009-08-17 11:03:03 -0400949 try {
950 if (c.moveToFirst()) {
951 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
952 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
953 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
954 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
955 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
956 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800957
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 FolderInfo folderInfo = null;
959 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700960 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
961 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400962 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700963 }
964
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965 folderInfo.title = c.getString(titleIndex);
966 folderInfo.id = id;
967 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700968 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700969 folderInfo.cellX = c.getInt(cellXIndex);
970 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971
972 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700973 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 } finally {
975 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700976 }
977
978 return null;
979 }
980
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981 /**
982 * Add an item to the database in a specified container. Sets the container, screen, cellX and
983 * cellY fields of the item. Also assigns an ID to the item.
984 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700985 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700986 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400987 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 item.cellX = cellX;
989 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700990 // We store hotseat items in canonical form which is this orientation invariant position
991 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700992 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700993 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700995 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700997 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998
999 final ContentValues values = new ContentValues();
1000 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001001 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001002
Michael Jurka414300a2013-08-27 15:42:35 +02001003 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001004 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chung3d503fb2011-07-13 17:25:49 -07001005 item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Winson Chungaafa03c2010-06-11 17:34:16 -07001006
Jason Monk8e19cf22014-03-20 15:06:57 -04001007 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001008 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001009 public void run() {
1010 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1011 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001013 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001014 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001015 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001016 sBgItemsIdMap.put(item.id, item);
1017 switch (item.itemType) {
1018 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1019 sBgFolders.put(item.id, (FolderInfo) item);
1020 // Fall through
1021 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1022 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1023 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1024 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1025 sBgWorkspaceItems.add(item);
1026 } else {
1027 if (!sBgFolders.containsKey(item.container)) {
1028 // Adding an item to a folder that doesn't exist.
1029 String msg = "adding item: " + item + " to a folder that " +
1030 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001031 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001032 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001033 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001034 break;
1035 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1036 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1037 break;
1038 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039 }
1040 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001041 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001043 }
1044
Joe Onorato9c1289c2009-08-17 11:03:03 -04001045 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001046 * Creates a new unique child id, for a given cell span across all layouts.
1047 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001048 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001050 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001051 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001052 }
1053
Sunny Goyal34942622014-08-29 17:20:55 -07001054 private static ArrayList<ItemInfo> getItemsByPackageName(
1055 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001056 ItemInfoFilter filter = new ItemInfoFilter() {
1057 @Override
1058 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1059 return cn.getPackageName().equals(pn) && info.user.equals(user);
1060 }
1061 };
Sunny Goyal34942622014-08-29 17:20:55 -07001062 return filterItemInfos(sBgItemsIdMap.values(), filter);
1063 }
1064
1065 /**
1066 * Removes all the items from the database corresponding to the specified package.
1067 */
1068 static void deletePackageFromDatabase(Context context, final String pn,
1069 final UserHandleCompat user) {
1070 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001071 }
1072
1073 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001074 * Removes the specified item from the database
1075 * @param context
1076 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001077 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001078 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001079 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1080 items.add(item);
1081 deleteItemsFromDatabase(context, items);
1082 }
1083
1084 /**
1085 * Removes the specified items from the database
1086 * @param context
1087 * @param item
1088 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001089 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001090 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001091
Michael Jurka83df1882011-08-31 20:59:26 -07001092 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001093 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001094 for (ItemInfo item : items) {
1095 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1096 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001097
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001098 // Lock on mBgLock *after* the db operation
1099 synchronized (sBgLock) {
1100 switch (item.itemType) {
1101 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1102 sBgFolders.remove(item.id);
1103 for (ItemInfo info: sBgItemsIdMap.values()) {
1104 if (info.container == item.id) {
1105 // We are deleting a folder which still contains items that
1106 // think they are contained by that folder.
1107 String msg = "deleting a folder (" + item + ") which still " +
1108 "contains items (" + info + ")";
1109 Log.e(TAG, msg);
1110 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001111 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001112 sBgWorkspaceItems.remove(item);
1113 break;
1114 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1115 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1116 sBgWorkspaceItems.remove(item);
1117 break;
1118 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1119 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1120 break;
1121 }
1122 sBgItemsIdMap.remove(item.id);
1123 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001124 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001125 }
1126 }
Michael Jurka83df1882011-08-31 20:59:26 -07001127 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001128 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001129 }
1130
1131 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001132 * Update the order of the workspace screens in the database. The array list contains
1133 * a list of screen ids in the order that they should appear.
1134 */
Winson Chungc9168342013-06-26 14:54:55 -07001135 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001136 // Log to disk
1137 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1138 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1139
Winson Chung64359a52013-07-08 17:17:08 -07001140 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001141 final ContentResolver cr = context.getContentResolver();
1142 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1143
1144 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001145 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001146 while (iter.hasNext()) {
1147 long id = iter.next();
1148 if (id < 0) {
1149 iter.remove();
1150 }
1151 }
1152
1153 Runnable r = new Runnable() {
1154 @Override
1155 public void run() {
Yura085c8532014-02-11 15:15:29 +00001156 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001157 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001158 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001159 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 for (int i = 0; i < count; i++) {
1161 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001162 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1164 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001165 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 }
Yura085c8532014-02-11 15:15:29 +00001167
1168 try {
1169 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1170 } catch (Exception ex) {
1171 throw new RuntimeException(ex);
1172 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001173
Winson Chungba9c37f2013-08-30 14:11:37 -07001174 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001175 sBgWorkspaceScreens.clear();
1176 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001177 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001178 }
1179 };
1180 runOnWorkerThread(r);
1181 }
1182
1183 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001184 * Remove the contents of the specified folder from the database
1185 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001186 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001187 final ContentResolver cr = context.getContentResolver();
1188
Michael Jurkac9d95c52011-08-29 14:03:34 -07001189 Runnable r = new Runnable() {
1190 public void run() {
1191 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001192 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001193 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001194 sBgItemsIdMap.remove(info.id);
1195 sBgFolders.remove(info.id);
1196 sBgDbIconCache.remove(info);
1197 sBgWorkspaceItems.remove(info);
1198 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001199
Michael Jurkac9d95c52011-08-29 14:03:34 -07001200 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1201 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001202 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001203 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 for (ItemInfo childInfo : info.contents) {
1205 sBgItemsIdMap.remove(childInfo.id);
1206 sBgDbIconCache.remove(childInfo);
1207 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001208 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001209 }
1210 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001212 }
1213
1214 /**
1215 * Set this as the current Launcher activity object for the loader.
1216 */
1217 public void initialize(Callbacks callbacks) {
1218 synchronized (mLock) {
1219 mCallbacks = new WeakReference<Callbacks>(callbacks);
1220 }
1221 }
1222
Kenny Guyed131872014-04-30 03:02:21 +01001223 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001224 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001225 int op = PackageUpdatedTask.OP_UPDATE;
1226 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1227 user));
1228 }
1229
1230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_REMOVE;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001239 int op = PackageUpdatedTask.OP_ADD;
1240 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1241 user));
1242 }
1243
1244 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001245 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001246 boolean replacing) {
1247 if (!replacing) {
1248 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1249 user));
1250 if (mAppsCanBeOnRemoveableStorage) {
1251 // Only rebind if we support removable storage. It catches the
1252 // case where
1253 // apps on the external sd card need to be reloaded
1254 startLoaderFromBackground();
1255 }
1256 } else {
1257 // If we are replacing then just update the packages in the list
1258 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1259 packageNames, user));
1260 }
1261 }
1262
1263 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001264 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001265 boolean replacing) {
1266 if (!replacing) {
1267 enqueuePackageUpdated(new PackageUpdatedTask(
1268 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1269 user));
1270 }
Kenny Guyed131872014-04-30 03:02:21 +01001271 }
1272
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001273 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001274 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1275 * ACTION_PACKAGE_CHANGED.
1276 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001277 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001278 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001279 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001280
Joe Onorato36115782010-06-17 13:28:48 -04001281 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001282 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001283 // If we have changed locale we need to clear out the labels in all apps/workspace.
1284 forceReload();
1285 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1286 // Check if configuration change was an mcc/mnc change which would affect app resources
1287 // and we would need to clear out the labels in all apps/workspace. Same handling as
1288 // above for ACTION_LOCALE_CHANGED
1289 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001290 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001291 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001292 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001293 forceReload();
1294 }
1295 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001296 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001297 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1298 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001299 Callbacks callbacks = getCallback();
1300 if (callbacks != null) {
1301 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001302 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001303 }
1304 }
1305
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001306 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001307 resetLoadedState(true, true);
1308
Reena Lee93f824a2011-09-23 17:20:28 -07001309 // Do this here because if the launcher activity is running it will be restarted.
1310 // If it's not running startLoaderFromBackground will merely tell it that it needs
1311 // to reload.
1312 startLoaderFromBackground();
1313 }
1314
Winson Chungf0c6ae02012-03-21 16:10:31 -07001315 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1316 synchronized (mLock) {
1317 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1318 // mWorkspaceLoaded to true later
1319 stopLoaderLocked();
1320 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1321 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1322 }
1323 }
1324
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001325 /**
1326 * When the launcher is in the background, it's possible for it to miss paired
1327 * configuration changes. So whenever we trigger the loader from the background
1328 * tell the launcher that it needs to re-run the loader when it comes back instead
1329 * of doing it now.
1330 */
1331 public void startLoaderFromBackground() {
1332 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001333 Callbacks callbacks = getCallback();
1334 if (callbacks != null) {
1335 // Only actually run the loader if they're not paused.
1336 if (!callbacks.setLoadOnResume()) {
1337 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001338 }
1339 }
1340 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001341 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001342 }
Joe Onorato36115782010-06-17 13:28:48 -04001343 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001344
Reena Lee93f824a2011-09-23 17:20:28 -07001345 // If there is already a loader task running, tell it to stop.
1346 // returns true if isLaunching() was true on the old task
1347 private boolean stopLoaderLocked() {
1348 boolean isLaunching = false;
1349 LoaderTask oldTask = mLoaderTask;
1350 if (oldTask != null) {
1351 if (oldTask.isLaunching()) {
1352 isLaunching = true;
1353 }
1354 oldTask.stopLocked();
1355 }
1356 return isLaunching;
1357 }
1358
Adam Cohen1a85c582014-09-30 09:48:49 -07001359 public boolean isCurrentCallbacks(Callbacks callbacks) {
1360 return (mCallbacks != null && mCallbacks.get() == callbacks);
1361 }
1362
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001363 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001364 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1365 }
1366
1367 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001368 synchronized (mLock) {
1369 if (DEBUG_LOADERS) {
1370 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1371 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001372
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373 // Clear any deferred bind-runnables from the synchronized load process
1374 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001375 synchronized (mDeferredBindRunnables) {
1376 mDeferredBindRunnables.clear();
1377 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001378
Joe Onorato36115782010-06-17 13:28:48 -04001379 // Don't bother to start the thread if we know it's not going to do anything
1380 if (mCallbacks != null && mCallbacks.get() != null) {
1381 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001382 // also, don't downgrade isLaunching if we're already running
1383 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001384 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001385 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1386 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1388 } else {
1389 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1390 sWorker.post(mLoaderTask);
1391 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001392 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001393 }
1394 }
1395
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001396 void bindRemainingSynchronousPages() {
1397 // Post the remaining side pages to be loaded
1398 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001399 Runnable[] deferredBindRunnables = null;
1400 synchronized (mDeferredBindRunnables) {
1401 deferredBindRunnables = mDeferredBindRunnables.toArray(
1402 new Runnable[mDeferredBindRunnables.size()]);
1403 mDeferredBindRunnables.clear();
1404 }
1405 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001406 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001407 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001408 }
1409 }
1410
Joe Onorato36115782010-06-17 13:28:48 -04001411 public void stopLoader() {
1412 synchronized (mLock) {
1413 if (mLoaderTask != null) {
1414 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001415 }
1416 }
Joe Onorato36115782010-06-17 13:28:48 -04001417 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001418
Winson Chung76828c82013-08-19 15:43:29 -07001419 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1420 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1421 final ContentResolver contentResolver = context.getContentResolver();
1422 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1423 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1424 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1425
1426 try {
1427 final int idIndex = sc.getColumnIndexOrThrow(
1428 LauncherSettings.WorkspaceScreens._ID);
1429 final int rankIndex = sc.getColumnIndexOrThrow(
1430 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1431 while (sc.moveToNext()) {
1432 try {
1433 long screenId = sc.getLong(idIndex);
1434 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001435 orderedScreens.put(rank, screenId);
1436 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001437 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001438 }
1439 }
1440 } finally {
1441 sc.close();
1442 }
Winson Chunga90303b2013-11-15 13:05:06 -08001443
1444 // Log to disk
1445 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1446 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1447 for (Integer i : orderedScreens.keySet()) {
1448 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1449 }
1450 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1451 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001452 return orderedScreens;
1453 }
1454
Michael Jurkac57b7a82011-08-09 22:02:20 -07001455 public boolean isAllAppsLoaded() {
1456 return mAllAppsLoaded;
1457 }
1458
Winson Chung36a62fe2012-05-06 18:04:42 -07001459 boolean isLoadingWorkspace() {
1460 synchronized (mLock) {
1461 if (mLoaderTask != null) {
1462 return mLoaderTask.isLoadingWorkspace();
1463 }
1464 }
1465 return false;
1466 }
1467
Joe Onorato36115782010-06-17 13:28:48 -04001468 /**
1469 * Runnable for the thread that loads the contents of the launcher:
1470 * - workspace icons
1471 * - widgets
1472 * - all apps icons
1473 */
1474 private class LoaderTask implements Runnable {
1475 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001476 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001477 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001478 private boolean mStopped;
1479 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001480 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001481
Winson Chungc3eecff2011-07-11 17:44:15 -07001482 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001483
Dan Sandlerd5024042014-01-09 15:01:33 -05001484 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001485 mContext = context;
1486 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001487 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001488 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489 }
1490
Joe Onorato36115782010-06-17 13:28:48 -04001491 boolean isLaunching() {
1492 return mIsLaunching;
1493 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001494
Winson Chung36a62fe2012-05-06 18:04:42 -07001495 boolean isLoadingWorkspace() {
1496 return mIsLoadingAndBindingWorkspace;
1497 }
1498
Winson Chungc763c4e2013-07-19 13:49:06 -07001499 /** Returns whether this is an upgrade path */
1500 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001501 mIsLoadingAndBindingWorkspace = true;
1502
Joe Onorato36115782010-06-17 13:28:48 -04001503 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001504 if (DEBUG_LOADERS) {
1505 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001506 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001507
Winson Chungc763c4e2013-07-19 13:49:06 -07001508 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001509 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001510 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001511 synchronized (LoaderTask.this) {
1512 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001513 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001514 }
1515 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001516 }
1517 }
1518
Joe Onorato36115782010-06-17 13:28:48 -04001519 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001520 bindWorkspace(-1, isUpgradePath);
1521 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001522 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001523
Joe Onorato36115782010-06-17 13:28:48 -04001524 private void waitForIdle() {
1525 // Wait until the either we're stopped or the other threads are done.
1526 // This way we don't start loading all apps until the workspace has settled
1527 // down.
1528 synchronized (LoaderTask.this) {
1529 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001530
Joe Onorato36115782010-06-17 13:28:48 -04001531 mHandler.postIdle(new Runnable() {
1532 public void run() {
1533 synchronized (LoaderTask.this) {
1534 mLoadAndBindStepFinished = true;
1535 if (DEBUG_LOADERS) {
1536 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001537 }
Joe Onorato36115782010-06-17 13:28:48 -04001538 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001539 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001540 }
Joe Onorato36115782010-06-17 13:28:48 -04001541 });
1542
Michael Jurkac7700af2013-05-14 20:17:58 +02001543 while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
Joe Onorato36115782010-06-17 13:28:48 -04001544 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001545 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1546 // wait no longer than 1sec at a time
1547 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001548 } catch (InterruptedException ex) {
1549 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001550 }
1551 }
Joe Onorato36115782010-06-17 13:28:48 -04001552 if (DEBUG_LOADERS) {
1553 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001554 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001555 + "ms for previous step to finish binding");
1556 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001557 }
Joe Onorato36115782010-06-17 13:28:48 -04001558 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001559
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001560 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001561 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001562 // Ensure that we have a valid page index to load synchronously
1563 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1564 "valid page index");
1565 }
1566 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1567 // Ensure that we don't try and bind a specified page when the pages have not been
1568 // loaded already (we should load everything asynchronously in that case)
1569 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1570 }
1571 synchronized (mLock) {
1572 if (mIsLoaderTaskRunning) {
1573 // Ensure that we are never running the background loading at this point since
1574 // we also touch the background collections
1575 throw new RuntimeException("Error! Background loading is already running");
1576 }
1577 }
1578
1579 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1580 // data structures, we can't allow any other thread to touch that data, but because
1581 // this call is synchronous, we can get away with not locking).
1582
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001583 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001584 // operations from the previous activity. We need to ensure that all queued operations
1585 // are executed before any synchronous binding work is done.
1586 mHandler.flush();
1587
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001588 // Divide the set of loaded items into those that we are binding synchronously, and
1589 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001590 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001591 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1592 // arise from that.
1593 onlyBindAllApps();
1594 }
1595
Joe Onorato36115782010-06-17 13:28:48 -04001596 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001597 boolean isUpgrade = false;
1598
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001599 synchronized (mLock) {
1600 mIsLoaderTaskRunning = true;
1601 }
Joe Onorato36115782010-06-17 13:28:48 -04001602 // Optimize for end-user experience: if the Launcher is up and // running with the
1603 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1604 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001605 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001606 // Elevate priority when Home launches for the first time to avoid
1607 // starving at boot time. Staring at a blank home is not cool.
1608 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001609 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1610 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001611 android.os.Process.setThreadPriority(mIsLaunching
1612 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1613 }
Winson Chung64359a52013-07-08 17:17:08 -07001614 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001615 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001616
Joe Onorato36115782010-06-17 13:28:48 -04001617 if (mStopped) {
1618 break keep_running;
1619 }
1620
1621 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1622 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001623 synchronized (mLock) {
1624 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001625 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001626 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1627 }
1628 }
Joe Onorato36115782010-06-17 13:28:48 -04001629 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001630
1631 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001632 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1633 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001634
1635 // Restore the default thread priority after we are done loading items
1636 synchronized (mLock) {
1637 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1638 }
Joe Onorato36115782010-06-17 13:28:48 -04001639 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001640
Winson Chungaac01e12011-08-17 10:37:13 -07001641 // Update the saved icons if necessary
1642 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001643 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001644 for (Object key : sBgDbIconCache.keySet()) {
1645 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1646 }
1647 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001648 }
Winson Chungaac01e12011-08-17 10:37:13 -07001649
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001650 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001651 // Ensure that all the applications that are in the system are
1652 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001653 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001654 verifyApplications();
1655 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001656 }
1657
Joe Onorato36115782010-06-17 13:28:48 -04001658 // Clear out this reference, otherwise we end up holding it until all of the
1659 // callback runnables are done.
1660 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001661
Joe Onorato36115782010-06-17 13:28:48 -04001662 synchronized (mLock) {
1663 // If we are still the last one to be scheduled, remove ourselves.
1664 if (mLoaderTask == this) {
1665 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001666 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001667 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001668 }
Joe Onorato36115782010-06-17 13:28:48 -04001669 }
1670
1671 public void stopLocked() {
1672 synchronized (LoaderTask.this) {
1673 mStopped = true;
1674 this.notify();
1675 }
1676 }
1677
1678 /**
1679 * Gets the callbacks object. If we've been stopped, or if the launcher object
1680 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1681 * object that was around when the deferred message was scheduled, and if there's
1682 * a new Callbacks object around then also return null. This will save us from
1683 * calling onto it with data that will be ignored.
1684 */
1685 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1686 synchronized (mLock) {
1687 if (mStopped) {
1688 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001689 }
Joe Onorato36115782010-06-17 13:28:48 -04001690
1691 if (mCallbacks == null) {
1692 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001693 }
Joe Onorato36115782010-06-17 13:28:48 -04001694
1695 final Callbacks callbacks = mCallbacks.get();
1696 if (callbacks != oldCallbacks) {
1697 return null;
1698 }
1699 if (callbacks == null) {
1700 Log.w(TAG, "no mCallbacks");
1701 return null;
1702 }
1703
1704 return callbacks;
1705 }
1706 }
1707
Winson Chungc763c4e2013-07-19 13:49:06 -07001708 private void verifyApplications() {
1709 final Context context = mApp.getContext();
1710
1711 // Cross reference all the applications in our apps list with items in the workspace
1712 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001713 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001714 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001715 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001716 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001717 if (tmpInfos.isEmpty()) {
1718 // We are missing an application icon, so add this to the workspace
1719 added.add(app);
1720 // This is a rare event, so lets log it
1721 Log.e(TAG, "Missing Application on load: " + app);
1722 }
1723 }
1724 }
1725 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001726 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001727 }
1728 }
1729
Joe Onorato36115782010-06-17 13:28:48 -04001730 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001731 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001732 LauncherAppState app = LauncherAppState.getInstance();
1733 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001734 final int countX = (int) grid.numColumns;
1735 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001736
Adam Cohendcd297f2013-06-18 13:13:40 -07001737 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001738 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001739 // Return early if we detect that an item is under the hotseat button
1740 if (mCallbacks == null ||
1741 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001742 Log.e(TAG, "Error loading shortcut into hotseat " + item
1743 + " into position (" + item.screenId + ":" + item.cellX + ","
1744 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001745 return false;
1746 }
1747
Dan Sandler295ae182013-12-10 16:05:47 -05001748 final ItemInfo[][] hotseatItems =
1749 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1750
Adam Cohenae4409d2013-11-26 10:34:59 -08001751 if (item.screenId >= grid.numHotseatIcons) {
1752 Log.e(TAG, "Error loading shortcut " + item
1753 + " into hotseat position " + item.screenId
1754 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1755 + ")");
1756 return false;
1757 }
1758
Dan Sandler295ae182013-12-10 16:05:47 -05001759 if (hotseatItems != null) {
1760 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001761 Log.e(TAG, "Error loading shortcut into hotseat " + item
1762 + " into position (" + item.screenId + ":" + item.cellX + ","
1763 + item.cellY + ") occupied by "
1764 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1765 [(int) item.screenId][0]);
1766 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001767 } else {
1768 hotseatItems[(int) item.screenId][0] = item;
1769 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001770 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001771 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001772 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001773 items[(int) item.screenId][0] = item;
1774 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001775 return true;
1776 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001777 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1778 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001779 return true;
1780 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001781
Adam Cohendcd297f2013-06-18 13:13:40 -07001782 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001783 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001784 occupied.put(item.screenId, items);
1785 }
1786
Dan Sandler295ae182013-12-10 16:05:47 -05001787 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001788 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1789 item.cellX < 0 || item.cellY < 0 ||
1790 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1791 Log.e(TAG, "Error loading shortcut " + item
1792 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1793 + item.cellX + "," + item.cellY
1794 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1795 return false;
1796 }
1797
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001798 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001799 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1800 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001801 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001802 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001803 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001804 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001805 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001806 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001807 return false;
1808 }
1809 }
1810 }
1811 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1812 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001813 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001814 }
1815 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001816
Joe Onorato36115782010-06-17 13:28:48 -04001817 return true;
1818 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001819
Winson Chungba9c37f2013-08-30 14:11:37 -07001820 /** Clears all the sBg data structures */
1821 private void clearSBgDataStructures() {
1822 synchronized (sBgLock) {
1823 sBgWorkspaceItems.clear();
1824 sBgAppWidgets.clear();
1825 sBgFolders.clear();
1826 sBgItemsIdMap.clear();
1827 sBgDbIconCache.clear();
1828 sBgWorkspaceScreens.clear();
1829 }
1830 }
1831
Dan Sandlerd5024042014-01-09 15:01:33 -05001832 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001833 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001834 // Log to disk
1835 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1836
Joe Onorato36115782010-06-17 13:28:48 -04001837 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001838
Joe Onorato36115782010-06-17 13:28:48 -04001839 final Context context = mContext;
1840 final ContentResolver contentResolver = context.getContentResolver();
1841 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001842 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001843 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1844 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001845 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001846
Winson Chung892c74d2013-08-22 16:15:50 -07001847 LauncherAppState app = LauncherAppState.getInstance();
1848 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1849 int countX = (int) grid.numColumns;
1850 int countY = (int) grid.numRows;
1851
Dan Sandlerd5024042014-01-09 15:01:33 -05001852 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1853 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1854 LauncherAppState.getLauncherProvider().deleteDatabase();
1855 }
1856
1857 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1858 // append the user's Launcher2 shortcuts
1859 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1860 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1861 } else {
1862 // Make sure the default workspace is loaded
1863 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001864 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001865 }
Adam Cohene25af792013-06-06 23:08:25 -07001866
Adam Cohen71483f42014-05-15 14:04:01 -07001867 // This code path is for our old migration code and should no longer be exercised
1868 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001869
Winson Chung9f9f00b2013-11-15 13:27:00 -08001870 // Log to disk
1871 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001872
Winson Chung2abf94d2012-07-18 18:16:38 -07001873 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001874 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001875 final HashSet<String> installingPkgs = PackageInstallerCompat
1876 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001877
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001878 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001879 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001880 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001881 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001882 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 // +1 for the hotseat (it can be larger than the workspace)
1885 // Load workspace in reverse order to ensure that latest items are loaded first (and
1886 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001887 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001888
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001889 try {
1890 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1891 final int intentIndex = c.getColumnIndexOrThrow
1892 (LauncherSettings.Favorites.INTENT);
1893 final int titleIndex = c.getColumnIndexOrThrow
1894 (LauncherSettings.Favorites.TITLE);
1895 final int iconTypeIndex = c.getColumnIndexOrThrow(
1896 LauncherSettings.Favorites.ICON_TYPE);
1897 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1898 final int iconPackageIndex = c.getColumnIndexOrThrow(
1899 LauncherSettings.Favorites.ICON_PACKAGE);
1900 final int iconResourceIndex = c.getColumnIndexOrThrow(
1901 LauncherSettings.Favorites.ICON_RESOURCE);
1902 final int containerIndex = c.getColumnIndexOrThrow(
1903 LauncherSettings.Favorites.CONTAINER);
1904 final int itemTypeIndex = c.getColumnIndexOrThrow(
1905 LauncherSettings.Favorites.ITEM_TYPE);
1906 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1907 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001908 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1909 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001910 final int screenIndex = c.getColumnIndexOrThrow(
1911 LauncherSettings.Favorites.SCREEN);
1912 final int cellXIndex = c.getColumnIndexOrThrow
1913 (LauncherSettings.Favorites.CELLX);
1914 final int cellYIndex = c.getColumnIndexOrThrow
1915 (LauncherSettings.Favorites.CELLY);
1916 final int spanXIndex = c.getColumnIndexOrThrow
1917 (LauncherSettings.Favorites.SPANX);
1918 final int spanYIndex = c.getColumnIndexOrThrow(
1919 LauncherSettings.Favorites.SPANY);
Chris Wrenf4d08112014-01-16 18:13:56 -05001920 final int restoredIndex = c.getColumnIndexOrThrow(
1921 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001922 final int profileIdIndex = c.getColumnIndexOrThrow(
1923 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001924 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1925 //final int displayModeIndex = c.getColumnIndexOrThrow(
1926 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001927
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001928 ShortcutInfo info;
1929 String intentDescription;
1930 LauncherAppWidgetInfo appWidgetInfo;
1931 int container;
1932 long id;
1933 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001934 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001935
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001936 while (!mStopped && c.moveToNext()) {
1937 try {
1938 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001939 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001940 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001941
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001942 switch (itemType) {
1943 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1944 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001945 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001946 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001947 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001948 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001949 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001950 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001951 if (user == null) {
1952 // User has been deleted remove the item.
1953 itemsToRemove.add(id);
1954 continue;
1955 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001956 try {
1957 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001958 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001959 if (cn != null && cn.getPackageName() != null) {
1960 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1961 cn.getPackageName(), user);
1962 boolean validComponent = validPkg &&
1963 launcherApps.isActivityEnabledForProfile(cn, user);
1964
1965 if (validComponent) {
1966 if (restored) {
1967 // no special handling necessary for this item
1968 restoredRows.add(id);
1969 restored = false;
1970 }
1971 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001972 intent = null;
1973 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1974 // We allow auto install apps to have their intent
1975 // updated after an install.
1976 intent = manager.getLaunchIntentForPackage(
1977 cn.getPackageName());
1978 if (intent != null) {
1979 ContentValues values = new ContentValues();
1980 values.put(LauncherSettings.Favorites.INTENT,
1981 intent.toUri(0));
1982 String where = BaseColumns._ID + "= ?";
1983 String[] args = {Long.toString(id)};
1984 contentResolver.update(contentUri, values, where, args);
1985 }
1986 }
1987
1988 if (intent == null) {
1989 // The app is installed but the component is no
1990 // longer available.
1991 Launcher.addDumpLog(TAG,
1992 "Invalid component removed: " + cn, true);
1993 itemsToRemove.add(id);
1994 continue;
1995 } else {
1996 // no special handling necessary for this item
1997 restoredRows.add(id);
1998 restored = false;
1999 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002000 } else if (restored) {
2001 // Package is not yet available but might be
2002 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002003 Launcher.addDumpLog(TAG,
2004 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002005
2006 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2007 // Restore has started once.
2008 } else if (installingPkgs.contains(cn.getPackageName())) {
2009 // App restore has started. Update the flag
2010 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2011 ContentValues values = new ContentValues();
2012 values.put(LauncherSettings.Favorites.RESTORED,
2013 promiseType);
2014 String where = BaseColumns._ID + "= ?";
2015 String[] args = {Long.toString(id)};
2016 contentResolver.update(contentUri, values, where, args);
2017
2018 } else if (REMOVE_UNRESTORED_ICONS) {
2019 Launcher.addDumpLog(TAG,
2020 "Unrestored package removed: " + cn, true);
2021 itemsToRemove.add(id);
2022 continue;
2023 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002024 } else if (launcherApps.isAppEnabled(
2025 manager, cn.getPackageName(),
2026 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2027 // Package is present but not available.
2028 allowMissingTarget = true;
2029 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2030 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002031 // SdCard is not ready yet. Package might get available,
2032 // once it is ready.
2033 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2034 + " (check again later)", true);
2035 HashSet<String> pkgs = sPendingPackages.get(user);
2036 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002037 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002038 sPendingPackages.put(user, pkgs);
2039 }
2040 pkgs.add(cn.getPackageName());
2041 allowMissingTarget = true;
2042 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002043
2044 } else {
2045 // Do not wait for external media load anymore.
2046 // Log the invalid package, and remove it
2047 Launcher.addDumpLog(TAG,
2048 "Invalid package removed: " + cn, true);
2049 itemsToRemove.add(id);
2050 continue;
Winson Chungee055712013-07-30 14:46:24 -07002051 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002052 } else if (cn == null) {
2053 // For shortcuts with no component, keep them as they are
2054 restoredRows.add(id);
2055 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002056 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002058 Launcher.addDumpLog(TAG,
2059 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002060 continue;
2061 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002062
Chris Wrenf4d08112014-01-16 18:13:56 -05002063 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002064 if (user.equals(UserHandleCompat.myUserHandle())) {
2065 Launcher.addDumpLog(TAG,
2066 "constructing info for partially restored package",
2067 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002068 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002069 intent = getRestoredItemIntent(c, context, intent);
2070 } else {
2071 // Don't restore items for other profiles.
2072 itemsToRemove.add(id);
2073 continue;
2074 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002075 } else if (itemType ==
2076 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002077 info = getShortcutInfo(manager, intent, user, context, c,
2078 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 } else {
2080 info = getShortcutInfo(c, context, iconTypeIndex,
2081 iconPackageIndex, iconResourceIndex, iconIndex,
2082 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002083
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 // App shortcuts that used to be automatically added to Launcher
2085 // didn't always have the correct intent flags set, so do that
2086 // here
2087 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002088 intent.getCategories() != null &&
2089 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002090 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 intent.addFlags(
2092 Intent.FLAG_ACTIVITY_NEW_TASK |
2093 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2094 }
Michael Jurka96879562012-03-22 05:54:33 -07002095 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002096
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002097 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002098 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002099 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002100 container = c.getInt(containerIndex);
2101 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002102 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002103 info.cellX = c.getInt(cellXIndex);
2104 info.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002105 info.spanX = 1;
2106 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002107 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002108 info.isDisabled = disabledState;
2109 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2110 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2111 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002112
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002113 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002114 if (!checkItemPlacement(occupied, info)) {
2115 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 break;
2117 }
2118
2119 switch (container) {
2120 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2121 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2122 sBgWorkspaceItems.add(info);
2123 break;
2124 default:
2125 // Item is in a user folder
2126 FolderInfo folderInfo =
2127 findOrMakeFolder(sBgFolders, container);
2128 folderInfo.add(info);
2129 break;
2130 }
2131 sBgItemsIdMap.put(info.id, info);
2132
2133 // now that we've loaded everthing re-save it with the
2134 // icon in case it disappears somehow.
2135 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002136 } else {
2137 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002138 }
2139 break;
2140
2141 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2142 id = c.getLong(idIndex);
2143 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2144
2145 folderInfo.title = c.getString(titleIndex);
2146 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002147 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002149 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002150 folderInfo.cellX = c.getInt(cellXIndex);
2151 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002152 folderInfo.spanX = 1;
2153 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002154
Daniel Sandler8802e962010-05-26 16:28:16 -04002155 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002156 if (!checkItemPlacement(occupied, folderInfo)) {
2157 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002158 break;
2159 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002160
Joe Onorato9c1289c2009-08-17 11:03:03 -04002161 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002162 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2163 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2164 sBgWorkspaceItems.add(folderInfo);
2165 break;
Joe Onorato36115782010-06-17 13:28:48 -04002166 }
Joe Onorato17a89222011-02-08 17:26:11 -08002167
Chris Wrenf4d08112014-01-16 18:13:56 -05002168 if (restored) {
2169 // no special handling required for restored folders
2170 restoredRows.add(id);
2171 }
2172
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002173 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2174 sBgFolders.put(folderInfo.id, folderInfo);
2175 break;
2176
2177 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002178 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002180 boolean customWidget = itemType ==
2181 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2182
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002183 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002184 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002185 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002186 final ComponentName component =
2187 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002188
Sunny Goyal651077b2014-06-30 14:15:31 -07002189 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002190 final boolean isIdValid = (restoreStatus &
2191 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002192
Sunny Goyalff572272014-07-23 13:58:07 -07002193 final boolean wasProviderReady = (restoreStatus &
2194 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002195
Adam Cohen59400422014-03-05 18:07:04 -08002196 final LauncherAppWidgetProviderInfo provider =
2197 LauncherModel.getProviderInfo(context,
2198 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002199
2200 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002201 if (!isSafeMode && !customWidget &&
2202 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002203 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002204 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002205
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002206 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002207 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002208 itemsToRemove.add(id);
2209 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002210 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2212 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002213
2214 if (!customWidget) {
2215 int[] minSpan =
2216 Launcher.getMinSpanForWidget(context, provider);
2217 appWidgetInfo.minSpanX = minSpan[0];
2218 appWidgetInfo.minSpanY = minSpan[1];
2219 }
Sunny Goyalff572272014-07-23 13:58:07 -07002220
2221 int status = restoreStatus;
2222 if (!wasProviderReady) {
2223 // If provider was not previously ready, update the
2224 // status and UI flag.
2225
2226 // Id would be valid only if the widget restore broadcast was received.
2227 if (isIdValid) {
2228 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2229 } else {
2230 status &= ~LauncherAppWidgetInfo
2231 .FLAG_PROVIDER_NOT_READY;
2232 }
2233 }
2234 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002235 } else {
2236 Log.v(TAG, "Widget restore pending id=" + id
2237 + " appWidgetId=" + appWidgetId
2238 + " status =" + restoreStatus);
2239 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002240 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002241 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002242
2243 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2244 // Restore has started once.
2245 } else if (installingPkgs.contains(component.getPackageName())) {
2246 // App restore has started. Update the flag
2247 appWidgetInfo.restoreStatus |=
2248 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002249 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002250 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002251 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002252 itemsToRemove.add(id);
2253 continue;
2254 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002255 }
Sunny Goyalff572272014-07-23 13:58:07 -07002256
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002257 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002258 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002259 appWidgetInfo.cellX = c.getInt(cellXIndex);
2260 appWidgetInfo.cellY = c.getInt(cellYIndex);
2261 appWidgetInfo.spanX = c.getInt(spanXIndex);
2262 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002263
Adam Cohen59400422014-03-05 18:07:04 -08002264 if (!customWidget) {
2265 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2266 appWidgetInfo.minSpanX = minSpan[0];
2267 appWidgetInfo.minSpanY = minSpan[1];
2268 }
2269
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002270 container = c.getInt(containerIndex);
2271 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2272 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2273 Log.e(TAG, "Widget found where container != " +
2274 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2275 continue;
2276 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002277
Adam Cohene25af792013-06-06 23:08:25 -07002278 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002279 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002280 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2281 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002282 break;
2283 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002284
Adam Cohen59400422014-03-05 18:07:04 -08002285 if (!customWidget) {
2286 String providerName =
2287 appWidgetInfo.providerName.flattenToString();
2288 if (!providerName.equals(savedProvider) ||
2289 (appWidgetInfo.restoreStatus != restoreStatus)) {
2290 ContentValues values = new ContentValues();
2291 values.put(
2292 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2293 providerName);
2294 values.put(LauncherSettings.Favorites.RESTORED,
2295 appWidgetInfo.restoreStatus);
2296 String where = BaseColumns._ID + "= ?";
2297 String[] args = {Long.toString(id)};
2298 contentResolver.update(contentUri, values, where, args);
2299 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002300 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2302 sBgAppWidgets.add(appWidgetInfo);
2303 }
Joe Onorato36115782010-06-17 13:28:48 -04002304 break;
2305 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002306 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002307 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002308 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002309 }
2310 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002311 if (c != null) {
2312 c.close();
2313 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002314 }
2315
Winson Chungba9c37f2013-08-30 14:11:37 -07002316 // Break early if we've stopped loading
2317 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002318 clearSBgDataStructures();
2319 return false;
2320 }
2321
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002322 if (itemsToRemove.size() > 0) {
2323 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002324 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002325 // Remove dead items
2326 for (long id : itemsToRemove) {
2327 if (DEBUG_LOADERS) {
2328 Log.d(TAG, "Removed id = " + id);
2329 }
2330 // Don't notify content observers
2331 try {
2332 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2333 null, null);
2334 } catch (RemoteException e) {
2335 Log.w(TAG, "Could not remove id = " + id);
2336 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002337 }
2338 }
2339
Chris Wrenf4d08112014-01-16 18:13:56 -05002340 if (restoredRows.size() > 0) {
2341 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002342 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002343 // Update restored items that no longer require special handling
2344 try {
2345 StringBuilder selectionBuilder = new StringBuilder();
2346 selectionBuilder.append(LauncherSettings.Favorites._ID);
2347 selectionBuilder.append(" IN (");
2348 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2349 selectionBuilder.append(")");
2350 ContentValues values = new ContentValues();
2351 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002352 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002353 values, selectionBuilder.toString(), null);
2354 } catch (RemoteException e) {
2355 Log.w(TAG, "Could not update restored rows");
2356 }
2357 }
2358
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002359 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2360 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002361 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002362 null, sWorker);
2363 }
2364
Winson Chungc763c4e2013-07-19 13:49:06 -07002365 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 long maxScreenId = 0;
2367 // If we're importing we use the old screen order.
2368 for (ItemInfo item: sBgItemsIdMap.values()) {
2369 long screenId = item.screenId;
2370 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2371 !sBgWorkspaceScreens.contains(screenId)) {
2372 sBgWorkspaceScreens.add(screenId);
2373 if (screenId > maxScreenId) {
2374 maxScreenId = screenId;
2375 }
2376 }
2377 }
2378 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002379 // Log to disk
2380 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2381 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2382 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002383
Michael Jurka414300a2013-08-27 15:42:35 +02002384 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002385 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002386
2387 // Update the max item id after we load an old db
2388 long maxItemId = 0;
2389 // If we're importing we use the old screen order.
2390 for (ItemInfo item: sBgItemsIdMap.values()) {
2391 maxItemId = Math.max(maxItemId, item.id);
2392 }
Michael Jurka414300a2013-08-27 15:42:35 +02002393 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002394 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002395 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2396 for (Integer i : orderedScreens.keySet()) {
2397 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002398 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002399 // Log to disk
2400 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2401 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002402
2403 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002404 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002405 for (ItemInfo item: sBgItemsIdMap.values()) {
2406 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002407 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2408 unusedScreens.contains(screenId)) {
2409 unusedScreens.remove(screenId);
2410 }
2411 }
2412
2413 // If there are any empty screens remove them, and update.
2414 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002415 // Log to disk
2416 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2417 TextUtils.join(", ", unusedScreens), true);
2418
Winson Chung933bae62013-08-29 11:42:30 -07002419 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002420 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2421 }
2422 }
2423
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002424 if (DEBUG_LOADERS) {
2425 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2426 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002427 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002428 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002430
Daniel Sandler566da102013-06-25 23:43:45 -04002431 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002432 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002433 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002434 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 line += " | ";
2436 }
Winson Chung892c74d2013-08-22 16:15:50 -07002437 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002438 ItemInfo[][] screen = occupied.get(screenId);
2439 if (x < screen.length && y < screen[x].length) {
2440 line += (screen[x][y] != null) ? "#" : ".";
2441 } else {
2442 line += "!";
2443 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002444 }
Joe Onorato36115782010-06-17 13:28:48 -04002445 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002446 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002447 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002448 }
Joe Onorato36115782010-06-17 13:28:48 -04002449 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002450 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002451 }
2452
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453 /** Filters the set of items who are directly or indirectly (via another container) on the
2454 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002455 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 ArrayList<ItemInfo> allWorkspaceItems,
2457 ArrayList<ItemInfo> currentScreenItems,
2458 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002459 // Purge any null ItemInfos
2460 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2461 while (iter.hasNext()) {
2462 ItemInfo i = iter.next();
2463 if (i == null) {
2464 iter.remove();
2465 }
2466 }
2467
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 // Order the set of items by their containers first, this allows use to walk through the
2469 // list sequentially, build up a list of containers that are in the specified screen,
2470 // as well as all items in those containers.
2471 Set<Long> itemsOnScreen = new HashSet<Long>();
2472 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2473 @Override
2474 public int compare(ItemInfo lhs, ItemInfo rhs) {
2475 return (int) (lhs.container - rhs.container);
2476 }
2477 });
2478 for (ItemInfo info : allWorkspaceItems) {
2479 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002480 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002481 currentScreenItems.add(info);
2482 itemsOnScreen.add(info.id);
2483 } else {
2484 otherScreenItems.add(info);
2485 }
2486 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2487 currentScreenItems.add(info);
2488 itemsOnScreen.add(info.id);
2489 } else {
2490 if (itemsOnScreen.contains(info.container)) {
2491 currentScreenItems.add(info);
2492 itemsOnScreen.add(info.id);
2493 } else {
2494 otherScreenItems.add(info);
2495 }
2496 }
2497 }
2498 }
2499
2500 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002501 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002502 ArrayList<LauncherAppWidgetInfo> appWidgets,
2503 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2504 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002505
2506 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002507 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002509 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002510 currentScreenWidgets.add(widget);
2511 } else {
2512 otherScreenWidgets.add(widget);
2513 }
2514 }
2515 }
2516
2517 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002518 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002519 HashMap<Long, ItemInfo> itemsIdMap,
2520 HashMap<Long, FolderInfo> folders,
2521 HashMap<Long, FolderInfo> currentScreenFolders,
2522 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523
2524 for (long id : folders.keySet()) {
2525 ItemInfo info = itemsIdMap.get(id);
2526 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002527 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002528 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002529 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 currentScreenFolders.put(id, folder);
2531 } else {
2532 otherScreenFolders.put(id, folder);
2533 }
2534 }
2535 }
2536
2537 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2538 * right) */
2539 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002540 final LauncherAppState app = LauncherAppState.getInstance();
2541 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542 // XXX: review this
2543 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002544 @Override
2545 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002546 int cellCountX = (int) grid.numColumns;
2547 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002548 int screenOffset = cellCountX * cellCountY;
2549 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002550 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002551 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002552 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002553 rhs.cellY * cellCountX + rhs.cellX);
2554 return (int) (lr - rr);
2555 }
2556 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002557 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002558
Adam Cohendcd297f2013-06-18 13:13:40 -07002559 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2560 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002561 final Runnable r = new Runnable() {
2562 @Override
2563 public void run() {
2564 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2565 if (callbacks != null) {
2566 callbacks.bindScreens(orderedScreens);
2567 }
2568 }
2569 };
2570 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2571 }
2572
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002573 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2574 final ArrayList<ItemInfo> workspaceItems,
2575 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2576 final HashMap<Long, FolderInfo> folders,
2577 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002578
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002579 final boolean postOnMainThread = (deferredBindRunnables != null);
2580
2581 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002582 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002584 final int start = i;
2585 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002586 final Runnable r = new Runnable() {
2587 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002588 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002589 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002590 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002591 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2592 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002593 }
2594 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002595 };
2596 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002597 synchronized (deferredBindRunnables) {
2598 deferredBindRunnables.add(r);
2599 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002600 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002601 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002602 }
Joe Onorato36115782010-06-17 13:28:48 -04002603 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002604
2605 // Bind the folders
2606 if (!folders.isEmpty()) {
2607 final Runnable r = new Runnable() {
2608 public void run() {
2609 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2610 if (callbacks != null) {
2611 callbacks.bindFolders(folders);
2612 }
2613 }
2614 };
2615 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002616 synchronized (deferredBindRunnables) {
2617 deferredBindRunnables.add(r);
2618 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002619 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002620 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002621 }
2622 }
2623
2624 // Bind the widgets, one at a time
2625 N = appWidgets.size();
2626 for (int i = 0; i < N; i++) {
2627 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2628 final Runnable r = new Runnable() {
2629 public void run() {
2630 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2631 if (callbacks != null) {
2632 callbacks.bindAppWidget(widget);
2633 }
2634 }
2635 };
2636 if (postOnMainThread) {
2637 deferredBindRunnables.add(r);
2638 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002639 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 }
2641 }
2642 }
2643
2644 /**
2645 * Binds all loaded data to actual views on the main thread.
2646 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002647 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002648 final long t = SystemClock.uptimeMillis();
2649 Runnable r;
2650
2651 // Don't use these two variables in any of the callback runnables.
2652 // Otherwise we hold a reference to them.
2653 final Callbacks oldCallbacks = mCallbacks.get();
2654 if (oldCallbacks == null) {
2655 // This launcher has exited and nobody bothered to tell us. Just bail.
2656 Log.w(TAG, "LoaderTask running with no launcher");
2657 return;
2658 }
2659
Winson Chung9b9fb962013-11-15 15:39:34 -08002660 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002661 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2662 ArrayList<LauncherAppWidgetInfo> appWidgets =
2663 new ArrayList<LauncherAppWidgetInfo>();
2664 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2665 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002666 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002667 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668 workspaceItems.addAll(sBgWorkspaceItems);
2669 appWidgets.addAll(sBgAppWidgets);
2670 folders.putAll(sBgFolders);
2671 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002672 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002673 }
2674
Derek Prothro7aff3992013-12-10 14:00:37 -05002675 final boolean isLoadingSynchronously =
2676 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002677 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002678 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002679 if (currScreen >= orderedScreenIds.size()) {
2680 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002681 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002682 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002683 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002684 final long currentScreenId = currentScreen < 0
2685 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002686
2687 // Load all the items that are on the current page first (and in the process, unbind
2688 // all the existing workspace items before we call startBinding() below.
2689 unbindWorkspaceItemsOnMainThread();
2690
2691 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002692 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2693 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2694 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2695 new ArrayList<LauncherAppWidgetInfo>();
2696 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2697 new ArrayList<LauncherAppWidgetInfo>();
2698 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2699 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2700
Winson Chung9b9fb962013-11-15 15:39:34 -08002701 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002702 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002703 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002704 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002705 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002706 otherFolders);
2707 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2708 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2709
2710 // Tell the workspace that we're about to start binding items
2711 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002712 public void run() {
2713 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2714 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002715 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002716 }
2717 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002718 };
Winson Chung81b52252012-08-27 15:34:29 -07002719 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002720
Adam Cohendcd297f2013-06-18 13:13:40 -07002721 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2722
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002723 // Load items on the current page
2724 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2725 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002726 if (isLoadingSynchronously) {
2727 r = new Runnable() {
2728 public void run() {
2729 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002730 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002731 callbacks.onPageBoundSynchronously(currentScreen);
2732 }
2733 }
2734 };
Winson Chung81b52252012-08-27 15:34:29 -07002735 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002736 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002737
Winson Chung4a2afa32012-07-19 14:53:05 -07002738 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2739 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002740 synchronized (mDeferredBindRunnables) {
2741 mDeferredBindRunnables.clear();
2742 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002743 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002744 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002745
2746 // Tell the workspace that we're done binding items
2747 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002748 public void run() {
2749 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2750 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002751 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002752 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002753
Winson Chung98e030b2012-05-07 16:01:11 -07002754 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002755 if (DEBUG_LOADERS) {
2756 Log.d(TAG, "bound workspace in "
2757 + (SystemClock.uptimeMillis()-t) + "ms");
2758 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002759
2760 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002761 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002762 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002763 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002764 synchronized (mDeferredBindRunnables) {
2765 mDeferredBindRunnables.add(r);
2766 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002767 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002768 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002769 }
Joe Onorato36115782010-06-17 13:28:48 -04002770 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002771
Joe Onorato36115782010-06-17 13:28:48 -04002772 private void loadAndBindAllApps() {
2773 if (DEBUG_LOADERS) {
2774 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2775 }
2776 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002777 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002778 synchronized (LoaderTask.this) {
2779 if (mStopped) {
2780 return;
2781 }
2782 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002783 }
Joe Onorato36115782010-06-17 13:28:48 -04002784 } else {
2785 onlyBindAllApps();
2786 }
2787 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002788
Joe Onorato36115782010-06-17 13:28:48 -04002789 private void onlyBindAllApps() {
2790 final Callbacks oldCallbacks = mCallbacks.get();
2791 if (oldCallbacks == null) {
2792 // This launcher has exited and nobody bothered to tell us. Just bail.
2793 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2794 return;
2795 }
2796
2797 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002798 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002799 final ArrayList<AppInfo> list
2800 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002801 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002802 public void run() {
2803 final long t = SystemClock.uptimeMillis();
2804 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2805 if (callbacks != null) {
2806 callbacks.bindAllApplications(list);
2807 }
2808 if (DEBUG_LOADERS) {
2809 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2810 + (SystemClock.uptimeMillis()-t) + "ms");
2811 }
2812 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002813 };
2814 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002815 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002816 r.run();
2817 } else {
2818 mHandler.post(r);
2819 }
Joe Onorato36115782010-06-17 13:28:48 -04002820 }
2821
Winson Chung64359a52013-07-08 17:17:08 -07002822 private void loadAllApps() {
2823 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002824
Joe Onorato36115782010-06-17 13:28:48 -04002825 final Callbacks oldCallbacks = mCallbacks.get();
2826 if (oldCallbacks == null) {
2827 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002828 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002829 return;
2830 }
2831
2832 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2833 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2834
Kenny Guyed131872014-04-30 03:02:21 +01002835 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2836
Winson Chung64359a52013-07-08 17:17:08 -07002837 // Clear the list of apps
2838 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002839 SharedPreferences prefs = mContext.getSharedPreferences(
2840 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002841 for (UserHandleCompat user : profiles) {
2842 // Query for the set of apps
2843 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2844 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2845 if (DEBUG_LOADERS) {
2846 Log.d(TAG, "getActivityList took "
2847 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2848 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2849 }
2850 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002851 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002852 if (apps == null || apps.isEmpty()) {
2853 return;
2854 }
2855 // Sort the applications by name
2856 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2857 Collections.sort(apps,
2858 new LauncherModel.ShortcutNameComparator(mLabelCache));
2859 if (DEBUG_LOADERS) {
2860 Log.d(TAG, "sort took "
2861 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2862 }
Joe Onorato36115782010-06-17 13:28:48 -04002863
Kenny Guyed131872014-04-30 03:02:21 +01002864 // Create the ApplicationInfos
2865 for (int i = 0; i < apps.size(); i++) {
2866 LauncherActivityInfoCompat app = apps.get(i);
2867 // This builds the icon bitmaps.
2868 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2869 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002870
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002871 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002872 // Add shortcuts for packages which were installed while launcher was dead.
2873 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2874 + mUserManager.getSerialNumberForUser(user);
2875 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2876 HashSet<String> newPackageSet = new HashSet<String>();
2877
2878 for (LauncherActivityInfoCompat info : apps) {
2879 String packageName = info.getComponentName().getPackageName();
2880 if (!packagesAdded.contains(packageName)
2881 && !newPackageSet.contains(packageName)) {
2882 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2883 }
2884 newPackageSet.add(packageName);
2885 }
2886
2887 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2888 }
Winson Chung64359a52013-07-08 17:17:08 -07002889 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002890 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002891 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2892 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002893
2894 // Post callback on main thread
2895 mHandler.post(new Runnable() {
2896 public void run() {
2897 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002898 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002899 if (callbacks != null) {
2900 callbacks.bindAllApplications(added);
2901 if (DEBUG_LOADERS) {
2902 Log.d(TAG, "bound " + added.size() + " apps in "
2903 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2904 }
2905 } else {
2906 Log.i(TAG, "not binding apps: no Launcher activity");
2907 }
2908 }
2909 });
2910
Joe Onorato36115782010-06-17 13:28:48 -04002911 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002912 Log.d(TAG, "Icons processed in "
2913 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002914 }
2915 }
2916
2917 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002918 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002919 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2920 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2921 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2922 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2923 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2924 }
Joe Onorato36115782010-06-17 13:28:48 -04002925 }
2926 }
2927
2928 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002929 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002930 }
2931
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002932 private class AppsAvailabilityCheck extends BroadcastReceiver {
2933
2934 @Override
2935 public void onReceive(Context context, Intent intent) {
2936 synchronized (sBgLock) {
2937 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2938 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002939 final PackageManager manager = context.getPackageManager();
2940 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2941 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002942 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2943 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002944 packagesRemoved.clear();
2945 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002946 for (String pkg : entry.getValue()) {
2947 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002948 boolean packageOnSdcard = launcherApps.isAppEnabled(
2949 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2950 if (packageOnSdcard) {
2951 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2952 packagesUnavailable.add(pkg);
2953 } else {
2954 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2955 packagesRemoved.add(pkg);
2956 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002957 }
2958 }
2959 if (!packagesRemoved.isEmpty()) {
2960 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2961 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2962 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002963 if (!packagesUnavailable.isEmpty()) {
2964 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2965 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2966 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002967 }
Sunny Goyal34942622014-08-29 17:20:55 -07002968 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002969 }
2970 }
2971 }
2972
Joe Onorato36115782010-06-17 13:28:48 -04002973 private class PackageUpdatedTask implements Runnable {
2974 int mOp;
2975 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002976 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002977
2978 public static final int OP_NONE = 0;
2979 public static final int OP_ADD = 1;
2980 public static final int OP_UPDATE = 2;
2981 public static final int OP_REMOVE = 3; // uninstlled
2982 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2983
2984
Kenny Guyed131872014-04-30 03:02:21 +01002985 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002986 mOp = op;
2987 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002988 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002989 }
2990
2991 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002992 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002993
2994 final String[] packages = mPackages;
2995 final int N = packages.length;
2996 switch (mOp) {
2997 case OP_ADD:
2998 for (int i=0; i<N; i++) {
2999 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003000 mIconCache.remove(packages[i], mUser);
3001 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003002 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003003
3004 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003005 if (ADD_MANAGED_PROFILE_SHORTCUTS
3006 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003007 SharedPreferences prefs = context.getSharedPreferences(
3008 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3009 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3010 + mUserManager.getSerialNumberForUser(mUser);
3011 Set<String> shortcutSet = new HashSet<String>(
3012 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3013
3014 for (int i=0; i<N; i++) {
3015 if (!shortcutSet.contains(packages[i])) {
3016 shortcutSet.add(packages[i]);
3017 List<LauncherActivityInfoCompat> activities =
3018 mLauncherApps.getActivityList(packages[i], mUser);
3019 if (activities != null && !activities.isEmpty()) {
3020 InstallShortcutReceiver.queueInstallShortcut(
3021 activities.get(0), context);
3022 }
3023 }
3024 }
3025
3026 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3027 }
Joe Onorato36115782010-06-17 13:28:48 -04003028 break;
3029 case OP_UPDATE:
3030 for (int i=0; i<N; i++) {
3031 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003032 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003033 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003034 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003035 }
3036 break;
3037 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003038 // Remove the packageName for the set of auto-installed shortcuts. This
3039 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003040 if (ADD_MANAGED_PROFILE_SHORTCUTS
3041 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003042 SharedPreferences prefs = context.getSharedPreferences(
3043 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3044 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3045 + mUserManager.getSerialNumberForUser(mUser);
3046 HashSet<String> shortcutSet = new HashSet<String>(
3047 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3048 shortcutSet.removeAll(Arrays.asList(mPackages));
3049 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3050 }
3051 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003052 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003053 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003054 for (int i=0; i<N; i++) {
3055 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003056 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003057 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003058 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003059 }
3060 break;
3061 }
3062
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003063 ArrayList<AppInfo> added = null;
3064 ArrayList<AppInfo> modified = null;
3065 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003066
Adam Cohen487f7dd2012-06-28 18:12:10 -07003067 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003068 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003069 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003070 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003071 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003072 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003073 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003074 }
Winson Chung5d55f332012-07-16 20:45:03 -07003075 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003076 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003077 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003078 }
3079
Sunny Goyale0f58d72014-11-10 18:05:31 -08003080 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003081 if (callbacks == null) {
3082 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3083 return;
3084 }
3085
Sunny Goyal4390ace2014-10-13 11:33:11 -07003086 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3087 new HashMap<ComponentName, AppInfo>();
3088
Joe Onorato36115782010-06-17 13:28:48 -04003089 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003090 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003091 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003092 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003093 addAndBindAddedWorkspaceApps(context, addedInfos);
3094 } else {
3095 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003096 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003097 for (AppInfo ai : added) {
3098 addedOrUpdatedApps.put(ai.componentName, ai);
3099 }
Joe Onorato36115782010-06-17 13:28:48 -04003100 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003101
Joe Onorato36115782010-06-17 13:28:48 -04003102 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003103 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003104 for (AppInfo ai : modified) {
3105 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003106 }
3107
Joe Onorato36115782010-06-17 13:28:48 -04003108 mHandler.post(new Runnable() {
3109 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003110 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003111 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003112 callbacks.bindAppsUpdated(modifiedFinal);
3113 }
3114 }
3115 });
3116 }
Winson Chung83892cc2013-05-01 16:53:33 -07003117
Sunny Goyal4390ace2014-10-13 11:33:11 -07003118 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003119 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003120 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3121 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3122 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3123
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003124 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003125 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003126 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003127 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3128 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003129 boolean infoUpdated = false;
3130 boolean shortcutUpdated = false;
3131
3132 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003133 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003134 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003135 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3136 si.iconResource.resourceName, mIconCache, context);
3137 if (icon != null) {
3138 si.setIcon(icon);
3139 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003140 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003141 }
3142 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003143
3144 ComponentName cn = si.getTargetComponent();
3145 if (cn != null && packageSet.contains(cn.getPackageName())) {
3146 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3147
3148 if (si.isPromise()) {
3149 mIconCache.deletePreloadedIcon(cn, mUser);
3150 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3151 // Auto install icon
3152 PackageManager pm = context.getPackageManager();
3153 ResolveInfo matched = pm.resolveActivity(
3154 new Intent(Intent.ACTION_MAIN)
3155 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3156 PackageManager.MATCH_DEFAULT_ONLY);
3157 if (matched == null) {
3158 // Try to find the best match activity.
3159 Intent intent = pm.getLaunchIntentForPackage(
3160 cn.getPackageName());
3161 if (intent != null) {
3162 cn = intent.getComponent();
3163 appInfo = addedOrUpdatedApps.get(cn);
3164 }
3165
3166 if ((intent == null) || (appInfo == null)) {
3167 removedShortcuts.add(si);
3168 continue;
3169 }
3170 si.promisedIntent = intent;
3171 }
3172 }
3173
3174 // Restore the shortcut.
3175 si.intent = si.promisedIntent;
3176 si.promisedIntent = null;
3177 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3178 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3179 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3180
3181 infoUpdated = true;
3182 si.updateIcon(mIconCache);
3183 }
3184
3185 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3186 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3187 si.updateIcon(mIconCache);
3188 si.title = appInfo.title.toString();
3189 si.contentDescription = appInfo.contentDescription;
3190 infoUpdated = true;
3191 }
3192
3193 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3194 // Since package was just updated, the target must be available now.
3195 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3196 shortcutUpdated = true;
3197 }
3198 }
3199
3200 if (infoUpdated || shortcutUpdated) {
3201 updatedShortcuts.add(si);
3202 }
3203 if (infoUpdated) {
3204 updateItemInDatabase(context, si);
3205 }
3206 } else if (info instanceof LauncherAppWidgetInfo) {
3207 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3208 if (mUser.equals(widgetInfo.user)
3209 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3210 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3211 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3212 widgets.add(widgetInfo);
3213 updateItemInDatabase(context, widgetInfo);
3214 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003215 }
3216 }
3217 }
3218
Sunny Goyal4390ace2014-10-13 11:33:11 -07003219 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3220 mHandler.post(new Runnable() {
3221
3222 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003223 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003224 if (callbacks == cb && cb != null) {
3225 callbacks.bindShortcutsChanged(
3226 updatedShortcuts, removedShortcuts, mUser);
3227 }
3228 }
3229 });
3230 if (!removedShortcuts.isEmpty()) {
3231 deleteItemsFromDatabase(context, removedShortcuts);
3232 }
3233 }
3234 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003235 mHandler.post(new Runnable() {
3236 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003237 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003238 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003239 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003240 }
3241 }
3242 });
3243 }
3244 }
3245
Winson Chungdf95eb12013-10-16 14:57:07 -07003246 final ArrayList<String> removedPackageNames =
3247 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003248 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003249 // Mark all packages in the broadcast to be removed
3250 removedPackageNames.addAll(Arrays.asList(packages));
3251 } else if (mOp == OP_UPDATE) {
3252 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003253 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003254 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003255 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003256 }
3257 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003258 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003259
Winson Chungdf95eb12013-10-16 14:57:07 -07003260 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003261 final int removeReason;
3262 if (mOp == OP_UNAVAILABLE) {
3263 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3264 } else {
3265 // Remove all the components associated with this package
3266 for (String pn : removedPackageNames) {
3267 deletePackageFromDatabase(context, pn, mUser);
3268 }
3269 // Remove all the specific components
3270 for (AppInfo a : removedApps) {
3271 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3272 deleteItemsFromDatabase(context, infos);
3273 }
3274 removeReason = 0;
3275 }
3276
Winson Chungdf95eb12013-10-16 14:57:07 -07003277 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003278 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003279 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003280 mHandler.post(new Runnable() {
3281 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003282 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003283 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003284 callbacks.bindComponentsRemoved(
3285 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003286 }
3287 }
3288 });
Joe Onoratobe386092009-11-17 17:32:16 -08003289 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003290
Michael Jurkac402cd92013-05-20 15:49:32 +02003291 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003292 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003293 mHandler.post(new Runnable() {
3294 @Override
3295 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003296 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003297 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003298 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003299 }
3300 }
3301 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003302
3303 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003304 mHandler.post(new Runnable() {
3305 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003306 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003307 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003308 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003309 }
3310 }
3311 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003312 }
3313 }
3314
Adam Cohen59400422014-03-05 18:07:04 -08003315 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3316 synchronized (sBgLock) {
3317 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3318 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3319 }
3320 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3321 List<AppWidgetProviderInfo> widgets =
3322 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3323 LauncherAppWidgetProviderInfo info;
3324 for (AppWidgetProviderInfo pInfo : widgets) {
3325 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3326 sBgWidgetProviders.put(info.provider, info);
3327 }
3328
3329 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3330 for (CustomAppWidget widget : customWidgets) {
3331 info = new LauncherAppWidgetProviderInfo(context, widget);
3332 sBgWidgetProviders.put(info.provider, info);
3333 }
3334 sWidgetProvidersDirty = false;
3335 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3336 }
3337 }
3338
3339 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3340 synchronized (sBgLock) {
3341 if (sBgWidgetProviders == null) {
3342 getWidgetProviders(ctx);
3343 }
3344 return sBgWidgetProviders.get(name);
3345 }
3346 }
3347
Michael Jurkac402cd92013-05-20 15:49:32 +02003348 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3349 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3350 PackageManager packageManager = context.getPackageManager();
3351 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003352 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003353 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3354 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003355 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003356 return widgetsAndShortcuts;
3357 }
3358
Kenny Guyed131872014-04-30 03:02:21 +01003359 private static boolean isPackageDisabled(Context context, String packageName,
3360 UserHandleCompat user) {
3361 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3362 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003363 }
Adam Cohen556f6132014-01-15 15:18:08 -08003364
Kenny Guyed131872014-04-30 03:02:21 +01003365 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3366 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003367 if (cn == null) {
3368 return false;
3369 }
Kenny Guyed131872014-04-30 03:02:21 +01003370 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3371 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003372 return false;
3373 }
Kenny Guyed131872014-04-30 03:02:21 +01003374 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003375 }
3376
Adam Cohena28b78e2014-05-20 17:03:04 -07003377 public static boolean isValidPackage(Context context, String packageName,
3378 UserHandleCompat user) {
3379 if (packageName == null) {
3380 return false;
3381 }
3382 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3383 return launcherApps.isPackageEnabledForProfile(packageName, user);
3384 }
3385
Joe Onorato9c1289c2009-08-17 11:03:03 -04003386 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003387 * Make an ShortcutInfo object for a restored application or shortcut item that points
3388 * to a package that is not yet installed on the system.
3389 */
Sunny Goyal34942622014-08-29 17:20:55 -07003390 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3391 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003392 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003393 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003394 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3395
3396 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3397 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3398 if (!TextUtils.isEmpty(title)) {
3399 info.title = title;
3400 }
3401 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3402 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3403 if (TextUtils.isEmpty(info.title)) {
3404 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3405 }
3406 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3407 } else {
3408 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3409 }
3410
Kenny Guyc2bd8102014-06-30 12:30:31 +01003411 info.contentDescription = mUserManager.getBadgedLabelForUser(
3412 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003413 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003414 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003415 return info;
3416 }
3417
3418 /**
3419 * Make an Intent object for a restored application or shortcut item that points
3420 * to the market page for the item.
3421 */
3422 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3423 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003424 return getMarketIntent(componentName.getPackageName());
3425 }
3426
3427 static Intent getMarketIntent(String packageName) {
3428 return new Intent(Intent.ACTION_VIEW)
3429 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003430 .scheme("market")
3431 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003432 .appendQueryParameter("id", packageName)
3433 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003434 }
3435
3436 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003437 * This is called from the code that adds shortcuts from the intent receiver. This
3438 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003439 */
Kenny Guyed131872014-04-30 03:02:21 +01003440 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3441 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003442 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003443 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003444
Joe Onorato56d82912010-03-07 14:32:10 -05003445 /**
3446 * Make an ShortcutInfo object for a shortcut that is an application.
3447 *
3448 * If c is not null, then it will be used to fill in missing data like the title and icon.
3449 */
Kenny Guyed131872014-04-30 03:02:21 +01003450 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3451 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003452 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003453 if (user == null) {
3454 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003455 return null;
3456 }
3457
Kenny Guyed131872014-04-30 03:02:21 +01003458 ComponentName componentName = intent.getComponent();
3459 if (componentName == null) {
3460 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3461 return null;
3462 }
3463
3464 Intent newIntent = new Intent(intent.getAction(), null);
3465 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3466 newIntent.setComponent(componentName);
3467 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003468 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003469 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3470 return null;
3471 }
3472
3473 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003474
Joe Onorato56d82912010-03-07 14:32:10 -05003475 // the resource -- This may implicitly give us back the fallback icon,
3476 // but don't worry about that. All we're doing with usingFallbackIcon is
3477 // to avoid saving lots of copies of that in the database, and most apps
3478 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003479 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003480
Joe Onorato56d82912010-03-07 14:32:10 -05003481 // the db
3482 if (icon == null) {
3483 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003484 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003485 }
3486 }
3487 // the fallback icon
3488 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003489 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003490 info.usingFallbackIcon = true;
3491 }
3492 info.setIcon(icon);
3493
Kenny Guyed131872014-04-30 03:02:21 +01003494 // From the cache.
3495 if (labelCache != null) {
3496 info.title = labelCache.get(componentName);
3497 }
3498
Joe Onorato56d82912010-03-07 14:32:10 -05003499 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003500 if (info.title == null && lai != null) {
3501 info.title = lai.getLabel();
3502 if (labelCache != null) {
3503 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003504 }
Joe Onorato56d82912010-03-07 14:32:10 -05003505 }
3506 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003507 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003508 if (c != null) {
3509 info.title = c.getString(titleIndex);
3510 }
3511 }
3512 // fall back to the class name of the activity
3513 if (info.title == null) {
3514 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003515 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003516 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003517 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003518 info.contentDescription = mUserManager.getBadgedLabelForUser(
3519 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003520 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003521 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003522
Winson Chung64359a52013-07-08 17:17:08 -07003523 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3524 ItemInfoFilter f) {
3525 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3526 for (ItemInfo i : infos) {
3527 if (i instanceof ShortcutInfo) {
3528 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003529 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003530 if (cn != null && f.filterItem(null, info, cn)) {
3531 filtered.add(info);
3532 }
3533 } else if (i instanceof FolderInfo) {
3534 FolderInfo info = (FolderInfo) i;
3535 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003536 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003537 if (cn != null && f.filterItem(info, s, cn)) {
3538 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003539 }
3540 }
Winson Chung64359a52013-07-08 17:17:08 -07003541 } else if (i instanceof LauncherAppWidgetInfo) {
3542 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3543 ComponentName cn = info.providerName;
3544 if (cn != null && f.filterItem(null, info, cn)) {
3545 filtered.add(info);
3546 }
Winson Chung8a435102012-08-30 17:16:53 -07003547 }
3548 }
Winson Chung64359a52013-07-08 17:17:08 -07003549 return new ArrayList<ItemInfo>(filtered);
3550 }
3551
Kenny Guyed131872014-04-30 03:02:21 +01003552 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3553 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003554 ItemInfoFilter filter = new ItemInfoFilter() {
3555 @Override
3556 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003557 if (info.user == null) {
3558 return cn.equals(cname);
3559 } else {
3560 return cn.equals(cname) && info.user.equals(user);
3561 }
Winson Chung64359a52013-07-08 17:17:08 -07003562 }
3563 };
3564 return filterItemInfos(sBgItemsIdMap.values(), filter);
3565 }
3566
Sunny Goyal1a745e82014-10-02 15:58:31 -07003567 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003568 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003569 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003570 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003571 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3572 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003573
Joe Onorato56d82912010-03-07 14:32:10 -05003574 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003575 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003576 // Non-app shortcuts are only supported for current user.
3577 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003578 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003579
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003580 // TODO: If there's an explicit component and we can't install that, delete it.
3581
Joe Onorato56d82912010-03-07 14:32:10 -05003582 info.title = c.getString(titleIndex);
3583
Joe Onorato9c1289c2009-08-17 11:03:03 -04003584 int iconType = c.getInt(iconTypeIndex);
3585 switch (iconType) {
3586 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3587 String packageName = c.getString(iconPackageIndex);
3588 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003589 info.customIcon = false;
3590 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003591 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003592 // the db
3593 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003594 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003595 }
3596 // the fallback icon
3597 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003598 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003599 info.usingFallbackIcon = true;
3600 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003601 break;
3602 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003603 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003604 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003605 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003606 info.customIcon = false;
3607 info.usingFallbackIcon = true;
3608 } else {
3609 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003610 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003611 break;
3612 default:
Kenny Guyed131872014-04-30 03:02:21 +01003613 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003614 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003615 info.customIcon = false;
3616 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003617 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003618 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003619 return info;
3620 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003621
Michael Jurka931dc972011-08-05 15:08:15 -07003622 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003623 @SuppressWarnings("all") // suppress dead code warning
3624 final boolean debug = false;
3625 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003626 Log.d(TAG, "getIconFromCursor app="
3627 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3628 }
3629 byte[] data = c.getBlob(iconIndex);
3630 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003631 return Utilities.createIconBitmap(
3632 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003633 } catch (Exception e) {
3634 return null;
3635 }
3636 }
3637
Sunny Goyal2350bc92014-10-14 16:42:54 -07003638 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003639 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3640 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3641 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3642
Adam Cohend9198822011-11-22 16:42:47 -08003643 if (intent == null) {
3644 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3645 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3646 return null;
3647 }
3648
Joe Onorato0589f0f2010-02-08 13:44:00 -08003649 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003650 boolean customIcon = false;
3651 ShortcutIconResource iconResource = null;
3652
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003653 if (bitmap instanceof Bitmap) {
3654 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003655 customIcon = true;
3656 } else {
3657 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003658 if (extra instanceof ShortcutIconResource) {
3659 iconResource = (ShortcutIconResource) extra;
3660 icon = Utilities.createIconBitmap(iconResource.packageName,
3661 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003662 }
3663 }
3664
Michael Jurkac9d95c52011-08-29 14:03:34 -07003665 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003666
Kenny Guyed131872014-04-30 03:02:21 +01003667 // Only support intents for current user for now. Intents sent from other
3668 // users wouldn't get here without intent forwarding anyway.
3669 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003670 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003671 icon = mIconCache.getDefaultIcon(info.user);
3672 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003673 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003674 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003675
Joe Onorato0589f0f2010-02-08 13:44:00 -08003676 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003677 info.contentDescription = mUserManager.getBadgedLabelForUser(
3678 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003679 info.intent = intent;
3680 info.customIcon = customIcon;
3681 info.iconResource = iconResource;
3682
3683 return info;
3684 }
3685
Winson Chungaac01e12011-08-17 10:37:13 -07003686 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3687 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003688 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003689 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003690 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003691 }
Joe Onorato56d82912010-03-07 14:32:10 -05003692 // If this icon doesn't have a custom icon, check to see
3693 // what's stored in the DB, and if it doesn't match what
3694 // we're going to show, store what we are going to show back
3695 // into the DB. We do this so when we're loading, if the
3696 // package manager can't find an icon (for example because
3697 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003698 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003699 cache.put(info, c.getBlob(iconIndex));
3700 return true;
3701 }
3702 return false;
3703 }
3704 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3705 boolean needSave = false;
3706 try {
3707 if (data != null) {
3708 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3709 Bitmap loaded = info.getIcon(mIconCache);
3710 needSave = !saved.sameAs(loaded);
3711 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003712 needSave = true;
3713 }
Winson Chungaac01e12011-08-17 10:37:13 -07003714 } catch (Exception e) {
3715 needSave = true;
3716 }
3717 if (needSave) {
3718 Log.d(TAG, "going to save icon bitmap for info=" + info);
3719 // This is slower than is ideal, but this only happens once
3720 // or when the app is updated with a new icon.
3721 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003722 }
3723 }
3724
Joe Onorato9c1289c2009-08-17 11:03:03 -04003725 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003726 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003727 * or make a new one.
3728 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003729 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003730 // See if a placeholder was created for us already
3731 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003732 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003733 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003734 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003735 folders.put(id, folderInfo);
3736 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003737 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003738 }
3739
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003740 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003741 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003742 return new Comparator<AppInfo>() {
3743 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003744 if (a.user.equals(b.user)) {
3745 int result = collator.compare(a.title.toString().trim(),
3746 b.title.toString().trim());
3747 if (result == 0) {
3748 result = a.componentName.compareTo(b.componentName);
3749 }
3750 return result;
3751 } else {
3752 // TODO Need to figure out rules for sorting
3753 // profiles, this puts work second.
3754 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003755 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003756 }
Winson Chung11904872012-09-17 16:58:46 -07003757 };
3758 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003759 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3760 = new Comparator<AppInfo>() {
3761 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003762 if (a.firstInstallTime < b.firstInstallTime) return 1;
3763 if (a.firstInstallTime > b.firstInstallTime) return -1;
3764 return 0;
3765 }
3766 };
Winson Chung5308f242011-08-18 12:12:41 -07003767 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3768 if (info.activityInfo != null) {
3769 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3770 } else {
3771 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3772 }
3773 }
Kenny Guyed131872014-04-30 03:02:21 +01003774 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003775 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003776 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003777 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003778 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003779 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003780 }
Kenny Guyed131872014-04-30 03:02:21 +01003781 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003782 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003783 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003784 }
Kenny Guyed131872014-04-30 03:02:21 +01003785 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003786 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003787 ComponentName keyA = a.getComponentName();
3788 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003789 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003790 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003791 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003792 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003793
Winson Chung5308f242011-08-18 12:12:41 -07003794 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003795 }
Winson Chung5308f242011-08-18 12:12:41 -07003796 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003797 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003798 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003799 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003800
Winson Chung5308f242011-08-18 12:12:41 -07003801 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003802 }
Winson Chung11904872012-09-17 16:58:46 -07003803 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003804 }
3805 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003806 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003807 private final AppWidgetManagerCompat mManager;
3808 private final PackageManager mPackageManager;
3809 private final HashMap<Object, String> mLabelCache;
3810 private final Collator mCollator;
3811
3812 WidgetAndShortcutNameComparator(Context context) {
3813 mManager = AppWidgetManagerCompat.getInstance(context);
3814 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003815 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003816 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003817 }
3818 public final int compare(Object a, Object b) {
3819 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003820 if (mLabelCache.containsKey(a)) {
3821 labelA = mLabelCache.get(a);
3822 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003823 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3824 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003825 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003826 mLabelCache.put(a, labelA);
3827 }
3828 if (mLabelCache.containsKey(b)) {
3829 labelB = mLabelCache.get(b);
3830 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003831 labelB = (b instanceof LauncherAppWidgetProviderInfo)
3832 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003833 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003834 mLabelCache.put(b, labelB);
3835 }
Winson Chung11904872012-09-17 16:58:46 -07003836 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003837 }
3838 };
Joe Onoratobe386092009-11-17 17:32:16 -08003839
Sunny Goyal651077b2014-06-30 14:15:31 -07003840 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3841 return (provider != null) && (provider.provider != null)
3842 && (provider.provider.getPackageName() != null);
3843 }
3844
Joe Onoratobe386092009-11-17 17:32:16 -08003845 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003846 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003847 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3848 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3849 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3850 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003851 if (mLoaderTask != null) {
3852 mLoaderTask.dumpState();
3853 } else {
3854 Log.d(TAG, "mLoaderTask=null");
3855 }
Joe Onoratobe386092009-11-17 17:32:16 -08003856 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003857
3858 public Callbacks getCallback() {
3859 return mCallbacks != null ? mCallbacks.get() : null;
3860 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003861}