blob: 2e879bcecf38184ff06811b35b71816a2bf05109 [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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
39import android.graphics.BitmapFactory;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080040import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import 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;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080052import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070053import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.LauncherActivityInfoCompat;
57import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070058import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070059import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010060import com.android.launcher3.compat.UserHandleCompat;
61import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080062
Michael Jurkac2f801e2011-07-12 14:19:46 -070063import java.lang.ref.WeakReference;
64import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070065import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070066import java.text.Collator;
67import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070068import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070069import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070070import java.util.Collections;
71import java.util.Comparator;
72import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070073import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070074import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070075import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070076import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077import java.util.Set;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
Sunny Goyale0f58d72014-11-10 18:05:31 -0800112 /**
113 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
114 */
115 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
116
Winson Chung81b52252012-08-27 15:34:29 -0700117 // Specific runnable types that are run on the main thread deferred handler, this allows us to
118 // clear all queued binding runnables when the Launcher activity is destroyed.
119 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
120 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
121
Jason Monkbbe1e242014-05-16 17:37:34 -0400122 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700123
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700124 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
125 static {
126 sWorkerThread.start();
127 }
128 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
129
Joe Onoratocc67f472010-06-08 10:54:30 -0700130 // We start off with everything not loaded. After that, we assume that
131 // our monitoring of the package manager provides all updates and we never
132 // need to do a requery. These are only ever touched from the loader thread.
133 private boolean mWorkspaceLoaded;
134 private boolean mAllAppsLoaded;
135
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700136 // When we are loading pages synchronously, we can't just post the binding of items on the side
137 // pages as this delays the rotation process. Instead, we wait for a callback from the first
138 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
139 // a normal load, we also clear this set of Runnables.
140 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
141
Joe Onorato9c1289c2009-08-17 11:03:03 -0400142 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800143
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700144 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700145 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800146
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700147 // The lock that must be acquired before referencing any static bg data structures. Unlike
148 // other locks, this one can generally be held long-term because we never expect any of these
149 // static data structures to be referenced outside of the worker thread except on the first
150 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700151 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700156
Adam Cohen487f7dd2012-06-28 18:12:10 -0700157 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
158 // created by LauncherModel that are directly on the home screen (however, no widgets or
159 // shortcuts within folders).
160 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
163 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700164 new ArrayList<LauncherAppWidgetInfo>();
165
Adam Cohen487f7dd2012-06-28 18:12:10 -0700166 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
167 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700168
Adam Cohen487f7dd2012-06-28 18:12:10 -0700169 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
170 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700171
172 // sBgWorkspaceScreens is the ordered set of workspace screens.
173 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
174
Adam Cohen59400422014-03-05 18:07:04 -0800175 // sBgWidgetProviders is the set of widget providers including custom internal widgets
176 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
177 public static boolean sWidgetProvidersDirty;
178
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700179 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700180 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
181 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700182
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700183 // </ only access in worker thread >
184
185 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186
Reena Lee99a73f32011-10-24 17:27:37 -0700187 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700188
Kenny Guyed131872014-04-30 03:02:21 +0100189 private final LauncherAppsCompat mLauncherApps;
190 private final UserManagerCompat mUserManager;
191
Joe Onorato9c1289c2009-08-17 11:03:03 -0400192 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700193 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 public int getCurrentWorkspaceScreen();
195 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700196 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
197 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700198 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700199 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500200 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700201 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400202 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200203 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700204 public void bindAppsAdded(ArrayList<Long> newScreens,
205 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700206 ArrayList<ItemInfo> addAnimated,
207 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200208 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700209 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
210 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
211 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700212 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700213 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700214 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700215 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200216 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100217 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700218 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700219 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700220 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800221 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
222 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400223 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224
Winson Chung64359a52013-07-08 17:17:08 -0700225 public interface ItemInfoFilter {
226 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
227 }
228
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800229 public interface ScreenPosProvider {
230 int getScreenIndex(ArrayList<Long> screenIDs);
231 }
232
Bjorn Bringert1307f632013-10-03 22:31:03 +0100233 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800234 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400235
Winson Chungee055712013-07-30 14:46:24 -0700236 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700237 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400238 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
239 // resource string.
240 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
241 ProviderInfo providerInfo =
242 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
243 ProviderInfo redirectProvider =
244 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700245
246 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400247 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700248
249 if (mOldContentProviderExists) {
250 Log.d(TAG, "Old launcher provider exists.");
251 } else {
252 Log.d(TAG, "Old launcher provider does not exist.");
253 }
254
Daniel Sandlere4f98912013-06-25 15:13:26 -0400255 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100256 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800257 mIconCache = iconCache;
258
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400259 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700260 Configuration config = res.getConfiguration();
261 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100262 mLauncherApps = LauncherAppsCompat.getInstance(context);
263 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800264 }
265
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700266 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
267 * posted on the main thread handler. */
268 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700269 runOnMainThread(r, 0);
270 }
271 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700272 if (sWorkerThread.getThreadId() == Process.myTid()) {
273 // If we are on the worker thread, post onto the main handler
274 mHandler.post(r);
275 } else {
276 r.run();
277 }
278 }
279
280 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
281 * posted on the worker thread handler. */
282 private static void runOnWorkerThread(Runnable r) {
283 if (sWorkerThread.getThreadId() == Process.myTid()) {
284 r.run();
285 } else {
286 // If we are not on the worker thread, then post to the worker handler
287 sWorker.post(r);
288 }
289 }
290
Winson Chunge43a1e72014-01-15 10:33:02 -0800291 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
292 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800293 }
294
Sunny Goyale755d462014-07-22 13:48:29 -0700295 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500296 // Process the updated package state
297 Runnable r = new Runnable() {
298 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800299 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500300 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700301 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500302 }
303 }
304 };
305 mHandler.post(r);
306 }
307
Sunny Goyala22666f2014-09-18 13:25:15 -0700308 public void updatePackageBadge(final String packageName) {
309 // Process the updated package badge
310 Runnable r = new Runnable() {
311 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800312 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700313 if (callbacks != null) {
314 callbacks.updatePackageBadge(packageName);
315 }
316 }
317 };
318 mHandler.post(r);
319 }
320
Adam Cohen76a47a12014-02-05 11:47:43 -0800321 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800322 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800323
324 if (allAppsApps == null) {
325 throw new RuntimeException("allAppsApps must not be null");
326 }
327 if (allAppsApps.isEmpty()) {
328 return;
329 }
330
331 // Process the newly added applications and add them to the database first
332 Runnable r = new Runnable() {
333 public void run() {
334 runOnMainThread(new Runnable() {
335 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800336 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800337 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500338 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800339 }
340 }
341 });
342 }
343 };
344 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700345 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800346
347 public void addAndBindAddedWorkspaceApps(final Context context,
348 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800349 addAndBindAddedWorkspaceApps(context, workspaceApps,
350 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800351
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800352 @Override
353 public int getScreenIndex(ArrayList<Long> screenIDs) {
354 return screenIDs.isEmpty() ? 0 : 1;
355 }
356 }, 1, false);
357 }
358
359 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
360 int[] xy, int spanX, int spanY) {
361 LauncherAppState app = LauncherAppState.getInstance();
362 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
363 final int xCount = (int) grid.numColumns;
364 final int yCount = (int) grid.numRows;
365 boolean[][] occupied = new boolean[xCount][yCount];
366 if (occupiedPos != null) {
367 for (Rect r : occupiedPos) {
368 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
369 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
370 occupied[x][y] = true;
371 }
372 }
373 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800374 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800375 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
376 }
377
378 /**
379 * Find a position on the screen for the given size or adds a new screen.
380 * @return screenId and the coordinates for the item.
381 */
382 private static Pair<Long, int[]> findSpaceForItem(
383 Context context,
384 ScreenPosProvider preferredScreen,
385 int fallbackStartScreen,
386 ArrayList<Long> workspaceScreens,
387 ArrayList<Long> addedWorkspaceScreensFinal,
388 int spanX, int spanY) {
389 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
390 // loadWorkspace() may not have been called.
391 final ContentResolver cr = context.getContentResolver();
392 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
393 new String[] {
394 LauncherSettings.Favorites.SCREEN,
395 LauncherSettings.Favorites.CELLX,
396 LauncherSettings.Favorites.CELLY,
397 LauncherSettings.Favorites.SPANX,
398 LauncherSettings.Favorites.SPANY,
399 LauncherSettings.Favorites.CONTAINER
400 },
401 "container=?",
402 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
403 null);
404
405 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
406 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
407 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
408 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
409 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
410 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
411 try {
412 while (c.moveToNext()) {
413 Rect rect = new Rect();
414 rect.left = c.getInt(cellXIndex);
415 rect.top = c.getInt(cellYIndex);
416 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
417 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
418
419 long screenId = c.getInt(screenIndex);
420 ArrayList<Rect> items = screenItems.get(screenId);
421 if (items == null) {
422 items = new ArrayList<Rect>();
423 screenItems.put(screenId, items);
424 }
425 items.add(rect);
426 }
427 } catch (Exception e) {
428 screenItems.clear();
429 } finally {
430 c.close();
431 }
432
433 // Find appropriate space for the item.
434 long screenId = 0;
435 int[] cordinates = new int[2];
436 boolean found = false;
437
438 int screenCount = workspaceScreens.size();
439 // First check the preferred screen.
440 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
441 if (preferredScreenIndex < screenCount) {
442 screenId = workspaceScreens.get(preferredScreenIndex);
443 found = findNextAvailableIconSpaceInScreen(
444 screenItems.get(screenId), cordinates, spanX, spanY);
445 }
446
447 if (!found) {
448 // Search on any of the screens.
449 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
450 screenId = workspaceScreens.get(screen);
451 if (findNextAvailableIconSpaceInScreen(
452 screenItems.get(screenId), cordinates, spanX, spanY)) {
453 // We found a space for it
454 found = true;
455 break;
456 }
457 }
458 }
459
460 if (!found) {
461 // Still no position found. Add a new screen to the end.
462 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
463
464 // Save the screen id for binding in the workspace
465 workspaceScreens.add(screenId);
466 addedWorkspaceScreensFinal.add(screenId);
467
468 // If we still can't find an empty space, then God help us all!!!
469 if (!findNextAvailableIconSpaceInScreen(
470 screenItems.get(screenId), cordinates, spanX, spanY)) {
471 throw new RuntimeException("Can't find space to add the item");
472 }
473 }
474 return Pair.create(screenId, cordinates);
475 }
476
477 /**
478 * Adds the provided items to the workspace.
479 * @param preferredScreen the screen where we should try to add the app first
480 * @param fallbackStartScreen the screen to start search for empty space if
481 * preferredScreen is not available.
482 */
483 public void addAndBindPendingItem(
484 final Context context,
485 final PendingAddItemInfo addInfo,
486 final ScreenPosProvider preferredScreen,
487 final int fallbackStartScreen) {
488 final Callbacks callbacks = getCallback();
489 // Process the newly added applications and add them to the database first
490 Runnable r = new Runnable() {
491 public void run() {
492 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800493 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800494
495 // Find appropriate space for the item.
496 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
497 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
498 addInfo.spanX,
499 addInfo.spanY);
500 final long screenId = coords.first;
501 final int[] cordinates = coords.second;
502
503 // Update the workspace screens
504 updateWorkspaceScreenOrder(context, workspaceScreens);
505 runOnMainThread(new Runnable() {
506 public void run() {
507 Callbacks cb = getCallback();
508 if (callbacks == cb && cb != null) {
509 cb.bindAddScreens(addedWorkspaceScreensFinal);
510 cb.bindAddPendingItem(addInfo,
511 LauncherSettings.Favorites.CONTAINER_DESKTOP,
512 screenId, cordinates, addInfo.spanX, addInfo.spanY);
513 }
514 }
515 });
516 }
517 };
518 runOnWorkerThread(r);
519 }
520
521 /**
522 * Adds the provided items to the workspace.
523 * @param preferredScreen the screen where we should try to add the app first
524 * @param fallbackStartScreen the screen to start search for empty space if
525 * preferredScreen is not available.
526 */
527 public void addAndBindAddedWorkspaceApps(final Context context,
528 final ArrayList<ItemInfo> workspaceApps,
529 final ScreenPosProvider preferredScreen,
530 final int fallbackStartScreen,
531 final boolean allowDuplicate) {
532 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800533 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700534 return;
Winson Chung997a9232013-07-24 15:33:46 -0700535 }
Winson Chung64359a52013-07-08 17:17:08 -0700536 // Process the newly added applications and add them to the database first
537 Runnable r = new Runnable() {
538 public void run() {
539 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
540 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
541
Winson Chung76828c82013-08-19 15:43:29 -0700542 // Get the list of workspace screens. We need to append to this list and
543 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
544 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800545 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700546 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800547 for (ItemInfo item : workspaceApps) {
548 if (!allowDuplicate) {
549 // Short-circuit this logic if the icon exists somewhere on the workspace
550 if (shortcutExists(context, item.title.toString(),
551 item.getIntent(), item.user)) {
552 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700553 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800554 }
Winson Chung76828c82013-08-19 15:43:29 -0700555
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800556 // Find appropriate space for the item.
557 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
558 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
559 1, 1);
560 long screenId = coords.first;
561 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700562
Winson Chung997a9232013-07-24 15:33:46 -0700563 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800564 if (item instanceof ShortcutInfo) {
565 shortcutInfo = (ShortcutInfo) item;
566 } else if (item instanceof AppInfo) {
567 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700568 } else {
569 throw new RuntimeException("Unexpected info type");
570 }
Winson Chung94d67682013-09-25 16:29:40 -0700571
Winson Chung64359a52013-07-08 17:17:08 -0700572 // Add the shortcut to the db
573 addItemToDatabase(context, shortcutInfo,
574 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800575 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700576 // Save the ShortcutInfo for binding in the workspace
577 addedShortcutsFinal.add(shortcutInfo);
578 }
579 }
580
Winson Chung76828c82013-08-19 15:43:29 -0700581 // Update the workspace screens
582 updateWorkspaceScreenOrder(context, workspaceScreens);
583
Adam Cohen76a47a12014-02-05 11:47:43 -0800584 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700585 runOnMainThread(new Runnable() {
586 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800587 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700588 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700589 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
590 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700591 if (!addedShortcutsFinal.isEmpty()) {
592 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
593 long lastScreenId = info.screenId;
594 for (ItemInfo i : addedShortcutsFinal) {
595 if (i.screenId == lastScreenId) {
596 addAnimated.add(i);
597 } else {
598 addNotAnimated.add(i);
599 }
Winson Chung997a9232013-07-24 15:33:46 -0700600 }
601 }
Winson Chungd64d1762013-08-20 14:37:16 -0700602 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800603 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700604 }
Winson Chung64359a52013-07-08 17:17:08 -0700605 }
Winson Chung997a9232013-07-24 15:33:46 -0700606 });
607 }
Winson Chung64359a52013-07-08 17:17:08 -0700608 }
609 };
610 runOnWorkerThread(r);
611 }
612
Winson Chung81b52252012-08-27 15:34:29 -0700613 public void unbindItemInfosAndClearQueuedBindRunnables() {
614 if (sWorkerThread.getThreadId() == Process.myTid()) {
615 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
616 "main thread");
617 }
618
619 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400620 synchronized (mDeferredBindRunnables) {
621 mDeferredBindRunnables.clear();
622 }
Winson Chung81b52252012-08-27 15:34:29 -0700623 // Remove any queued bind runnables
624 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
625 // Unbind all the workspace items
626 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700627 }
628
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700629 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700630 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700631 // Ensure that we don't use the same workspace items data structure on the main thread
632 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700633 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
634 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700635 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700636 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
637 tmpAppWidgets.addAll(sBgAppWidgets);
638 }
639 Runnable r = new Runnable() {
640 @Override
641 public void run() {
642 for (ItemInfo item : tmpWorkspaceItems) {
643 item.unbind();
644 }
645 for (ItemInfo item : tmpAppWidgets) {
646 item.unbind();
647 }
648 }
649 };
650 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700651 }
652
Joe Onorato9c1289c2009-08-17 11:03:03 -0400653 /**
654 * Adds an item to the DB if it was not created previously, or move it to a new
655 * <container, screen, cellX, cellY>
656 */
657 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400659 if (item.container == ItemInfo.NO_ID) {
660 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700661 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400662 } else {
663 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700664 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800665 }
666 }
667
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700668 static void checkItemInfoLocked(
669 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
670 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
671 if (modelItem != null && item != modelItem) {
672 // check all the data is consistent
673 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
674 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
675 ShortcutInfo shortcut = (ShortcutInfo) item;
676 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
677 modelShortcut.intent.filterEquals(shortcut.intent) &&
678 modelShortcut.id == shortcut.id &&
679 modelShortcut.itemType == shortcut.itemType &&
680 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700681 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700682 modelShortcut.cellX == shortcut.cellX &&
683 modelShortcut.cellY == shortcut.cellY &&
684 modelShortcut.spanX == shortcut.spanX &&
685 modelShortcut.spanY == shortcut.spanY &&
686 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
687 (modelShortcut.dropPos != null &&
688 shortcut.dropPos != null &&
689 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
690 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
691 // For all intents and purposes, this is the same object
692 return;
693 }
694 }
695
696 // the modelItem needs to match up perfectly with item if our model is
697 // to be consistent with the database-- for now, just require
698 // modelItem == item or the equality check above
699 String msg = "item: " + ((item != null) ? item.toString() : "null") +
700 "modelItem: " +
701 ((modelItem != null) ? modelItem.toString() : "null") +
702 "Error: ItemInfo passed to checkItemInfo doesn't match original";
703 RuntimeException e = new RuntimeException(msg);
704 if (stackTrace != null) {
705 e.setStackTrace(stackTrace);
706 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800707 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700708 }
709 }
710
Michael Jurka816474f2012-06-25 14:49:02 -0700711 static void checkItemInfo(final ItemInfo item) {
712 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
713 final long itemId = item.id;
714 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700715 public void run() {
716 synchronized (sBgLock) {
717 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700718 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700719 }
720 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700721 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700722 }
723
Michael Jurkac9d95c52011-08-29 14:03:34 -0700724 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
725 final ItemInfo item, final String callingFunction) {
726 final long itemId = item.id;
727 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
728 final ContentResolver cr = context.getContentResolver();
729
Adam Cohen487f7dd2012-06-28 18:12:10 -0700730 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700731 Runnable r = new Runnable() {
732 public void run() {
733 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700734 updateItemArrays(item, itemId, stackTrace);
735 }
736 };
737 runOnWorkerThread(r);
738 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700739
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700740 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
741 final ArrayList<ItemInfo> items, final String callingFunction) {
742 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700743
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700744 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
745 Runnable r = new Runnable() {
746 public void run() {
747 ArrayList<ContentProviderOperation> ops =
748 new ArrayList<ContentProviderOperation>();
749 int count = items.size();
750 for (int i = 0; i < count; i++) {
751 ItemInfo item = items.get(i);
752 final long itemId = item.id;
753 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
754 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700755
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700756 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
757 updateItemArrays(item, itemId, stackTrace);
758
759 }
760 try {
761 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
762 } catch (Exception e) {
763 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700764 }
765 }
766 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700767 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700768 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700769
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700770 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
771 // Lock on mBgLock *after* the db operation
772 synchronized (sBgLock) {
773 checkItemInfoLocked(itemId, item, stackTrace);
774
775 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
776 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
777 // Item is in a folder, make sure this folder exists
778 if (!sBgFolders.containsKey(item.container)) {
779 // An items container is being set to a that of an item which is not in
780 // the list of Folders.
781 String msg = "item: " + item + " container being set to: " +
782 item.container + ", not in the list of folders";
783 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700784 }
785 }
786
787 // Items are added/removed from the corresponding FolderInfo elsewhere, such
788 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
789 // that are on the desktop, as appropriate
790 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800791 if (modelItem != null &&
792 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
793 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700794 switch (modelItem.itemType) {
795 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
796 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
797 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
798 if (!sBgWorkspaceItems.contains(modelItem)) {
799 sBgWorkspaceItems.add(modelItem);
800 }
801 break;
802 default:
803 break;
804 }
805 } else {
806 sBgWorkspaceItems.remove(modelItem);
807 }
808 }
809 }
810
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800811 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400812 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700813 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700814 static void moveItemInDatabase(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) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400816 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400817 item.cellX = cellX;
818 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700819
Winson Chung3d503fb2011-07-13 17:25:49 -0700820 // We store hotseat items in canonical form which is this orientation invariant position
821 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700822 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700823 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700825 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700827 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400828
829 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400830 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700831 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
832 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800833 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700834 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400835
Michael Jurkac9d95c52011-08-29 14:03:34 -0700836 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700837 }
838
839 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700840 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
841 * cellX, cellY have already been updated on the ItemInfos.
842 */
843 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
844 final long container, final int screen) {
845
846 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
847 int count = items.size();
848
849 for (int i = 0; i < count; i++) {
850 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700851 item.container = container;
852
853 // We store hotseat items in canonical form which is this orientation invariant position
854 // in the hotseat
855 if (context instanceof Launcher && screen < 0 &&
856 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700857 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700858 item.cellY);
859 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700860 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700861 }
862
863 final ContentValues values = new ContentValues();
864 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
865 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
866 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800867 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700868 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700869
870 contentValues.add(values);
871 }
872 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
873 }
874
875 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700876 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800877 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700878 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700879 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700880 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800881 item.cellX = cellX;
882 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 item.spanX = spanX;
884 item.spanY = spanY;
885
886 // We store hotseat items in canonical form which is this orientation invariant position
887 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700888 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700889 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700890 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700891 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700892 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700893 }
Adam Cohend4844c32011-02-18 19:25:06 -0800894
Adam Cohend4844c32011-02-18 19:25:06 -0800895 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800896 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700897 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
898 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800899 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700900 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
901 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700902 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800903
Michael Jurka816474f2012-06-25 14:49:02 -0700904 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700905 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700906
907 /**
908 * Update an item to the database in a specified container.
909 */
910 static void updateItemInDatabase(Context context, final ItemInfo item) {
911 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100912 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700913 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800914 }
915
916 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400917 * Returns true if the shortcuts already exists in the database.
918 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800919 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800920 static boolean shortcutExists(Context context, String title, Intent intent,
921 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400922 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700923 final Intent intentWithPkg, intentWithoutPkg;
924
925 if (intent.getComponent() != null) {
926 // If component is not null, an intent with null package will produce
927 // the same result and should also be a match.
928 if (intent.getPackage() != null) {
929 intentWithPkg = intent;
930 intentWithoutPkg = new Intent(intent).setPackage(null);
931 } else {
932 intentWithPkg = new Intent(intent).setPackage(
933 intent.getComponent().getPackageName());
934 intentWithoutPkg = intent;
935 }
936 } else {
937 intentWithPkg = intent;
938 intentWithoutPkg = intent;
939 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800940 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
941 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400942 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800943 new String[] { "title", "intent", "profileId" },
944 "title=? and (intent=? or intent=?) and profileId=?",
945 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
946 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400947 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800948 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400949 } finally {
950 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800951 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700952 }
953
Joe Onorato9c1289c2009-08-17 11:03:03 -0400954 /**
955 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
956 */
957 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
958 final ContentResolver cr = context.getContentResolver();
959 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
960 "_id=? and (itemType=? or itemType=?)",
961 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700962 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700963
Joe Onorato9c1289c2009-08-17 11:03:03 -0400964 try {
965 if (c.moveToFirst()) {
966 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
967 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
968 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
969 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
970 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
971 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800972
Joe Onorato9c1289c2009-08-17 11:03:03 -0400973 FolderInfo folderInfo = null;
974 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700975 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
976 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400977 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700978 }
979
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980 folderInfo.title = c.getString(titleIndex);
981 folderInfo.id = id;
982 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700983 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700984 folderInfo.cellX = c.getInt(cellXIndex);
985 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400986
987 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700988 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989 } finally {
990 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700991 }
992
993 return null;
994 }
995
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996 /**
997 * Add an item to the database in a specified container. Sets the container, screen, cellX and
998 * cellY fields of the item. Also assigns an ID to the item.
999 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001000 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001002 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001003 item.cellX = cellX;
1004 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001005 // We store hotseat items in canonical form which is this orientation invariant position
1006 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001008 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001009 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001010 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001012 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013
1014 final ContentValues values = new ContentValues();
1015 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001016 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001017
Michael Jurka414300a2013-08-27 15:42:35 +02001018 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001019 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001020
Jason Monk8e19cf22014-03-20 15:06:57 -04001021 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001022 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001023 public void run() {
1024 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1025 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001026
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001027 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001028 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001029 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001030 sBgItemsIdMap.put(item.id, item);
1031 switch (item.itemType) {
1032 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1033 sBgFolders.put(item.id, (FolderInfo) item);
1034 // Fall through
1035 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1036 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1037 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1038 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1039 sBgWorkspaceItems.add(item);
1040 } else {
1041 if (!sBgFolders.containsKey(item.container)) {
1042 // Adding an item to a folder that doesn't exist.
1043 String msg = "adding item: " + item + " to a folder that " +
1044 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001045 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001046 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001047 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001048 break;
1049 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1050 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1051 break;
1052 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001053 }
1054 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001055 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001056 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001057 }
1058
Joe Onorato9c1289c2009-08-17 11:03:03 -04001059 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001060 * Creates a new unique child id, for a given cell span across all layouts.
1061 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001062 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001063 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001064 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001065 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001066 }
1067
Sunny Goyal34942622014-08-29 17:20:55 -07001068 private static ArrayList<ItemInfo> getItemsByPackageName(
1069 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001070 ItemInfoFilter filter = new ItemInfoFilter() {
1071 @Override
1072 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1073 return cn.getPackageName().equals(pn) && info.user.equals(user);
1074 }
1075 };
Sunny Goyal34942622014-08-29 17:20:55 -07001076 return filterItemInfos(sBgItemsIdMap.values(), filter);
1077 }
1078
1079 /**
1080 * Removes all the items from the database corresponding to the specified package.
1081 */
1082 static void deletePackageFromDatabase(Context context, final String pn,
1083 final UserHandleCompat user) {
1084 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001085 }
1086
1087 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001088 * Removes the specified item from the database
1089 * @param context
1090 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001091 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001092 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001093 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1094 items.add(item);
1095 deleteItemsFromDatabase(context, items);
1096 }
1097
1098 /**
1099 * Removes the specified items from the database
1100 * @param context
1101 * @param item
1102 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001103 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001104 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001105
Michael Jurka83df1882011-08-31 20:59:26 -07001106 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001107 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001108 for (ItemInfo item : items) {
1109 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1110 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001111
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001112 // Lock on mBgLock *after* the db operation
1113 synchronized (sBgLock) {
1114 switch (item.itemType) {
1115 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1116 sBgFolders.remove(item.id);
1117 for (ItemInfo info: sBgItemsIdMap.values()) {
1118 if (info.container == item.id) {
1119 // We are deleting a folder which still contains items that
1120 // think they are contained by that folder.
1121 String msg = "deleting a folder (" + item + ") which still " +
1122 "contains items (" + info + ")";
1123 Log.e(TAG, msg);
1124 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001125 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001126 sBgWorkspaceItems.remove(item);
1127 break;
1128 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1129 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1130 sBgWorkspaceItems.remove(item);
1131 break;
1132 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1133 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1134 break;
1135 }
1136 sBgItemsIdMap.remove(item.id);
1137 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001138 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001139 }
1140 }
Michael Jurka83df1882011-08-31 20:59:26 -07001141 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001142 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001143 }
1144
1145 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001146 * Update the order of the workspace screens in the database. The array list contains
1147 * a list of screen ids in the order that they should appear.
1148 */
Winson Chungc9168342013-06-26 14:54:55 -07001149 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001150 // Log to disk
1151 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1152 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1153
Winson Chung64359a52013-07-08 17:17:08 -07001154 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 final ContentResolver cr = context.getContentResolver();
1156 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1157
1158 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001159 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 while (iter.hasNext()) {
1161 long id = iter.next();
1162 if (id < 0) {
1163 iter.remove();
1164 }
1165 }
1166
1167 Runnable r = new Runnable() {
1168 @Override
1169 public void run() {
Yura085c8532014-02-11 15:15:29 +00001170 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001172 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001173 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001174 for (int i = 0; i < count; i++) {
1175 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001176 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001177 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1178 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001179 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001180 }
Yura085c8532014-02-11 15:15:29 +00001181
1182 try {
1183 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1184 } catch (Exception ex) {
1185 throw new RuntimeException(ex);
1186 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001187
Winson Chungba9c37f2013-08-30 14:11:37 -07001188 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001189 sBgWorkspaceScreens.clear();
1190 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001191 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001192 }
1193 };
1194 runOnWorkerThread(r);
1195 }
1196
1197 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001198 * Remove the contents of the specified folder from the database
1199 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001200 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001201 final ContentResolver cr = context.getContentResolver();
1202
Michael Jurkac9d95c52011-08-29 14:03:34 -07001203 Runnable r = new Runnable() {
1204 public void run() {
1205 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001206 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001207 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 sBgItemsIdMap.remove(info.id);
1209 sBgFolders.remove(info.id);
1210 sBgDbIconCache.remove(info);
1211 sBgWorkspaceItems.remove(info);
1212 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001213
Michael Jurkac9d95c52011-08-29 14:03:34 -07001214 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1215 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001216 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001217 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 for (ItemInfo childInfo : info.contents) {
1219 sBgItemsIdMap.remove(childInfo.id);
1220 sBgDbIconCache.remove(childInfo);
1221 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001222 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001223 }
1224 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001225 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001226 }
1227
1228 /**
1229 * Set this as the current Launcher activity object for the loader.
1230 */
1231 public void initialize(Callbacks callbacks) {
1232 synchronized (mLock) {
1233 mCallbacks = new WeakReference<Callbacks>(callbacks);
1234 }
1235 }
1236
Kenny Guyed131872014-04-30 03:02:21 +01001237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001239 int op = PackageUpdatedTask.OP_UPDATE;
1240 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1241 user));
1242 }
1243
1244 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001245 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001246 int op = PackageUpdatedTask.OP_REMOVE;
1247 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1248 user));
1249 }
1250
1251 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001252 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001253 int op = PackageUpdatedTask.OP_ADD;
1254 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1255 user));
1256 }
1257
1258 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001259 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001260 boolean replacing) {
1261 if (!replacing) {
1262 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1263 user));
1264 if (mAppsCanBeOnRemoveableStorage) {
1265 // Only rebind if we support removable storage. It catches the
1266 // case where
1267 // apps on the external sd card need to be reloaded
1268 startLoaderFromBackground();
1269 }
1270 } else {
1271 // If we are replacing then just update the packages in the list
1272 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1273 packageNames, user));
1274 }
1275 }
1276
1277 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001278 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001279 boolean replacing) {
1280 if (!replacing) {
1281 enqueuePackageUpdated(new PackageUpdatedTask(
1282 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1283 user));
1284 }
Kenny Guyed131872014-04-30 03:02:21 +01001285 }
1286
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001287 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001288 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1289 * ACTION_PACKAGE_CHANGED.
1290 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001291 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001292 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001293 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001294
Joe Onorato36115782010-06-17 13:28:48 -04001295 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001296 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001297 // If we have changed locale we need to clear out the labels in all apps/workspace.
1298 forceReload();
1299 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1300 // Check if configuration change was an mcc/mnc change which would affect app resources
1301 // and we would need to clear out the labels in all apps/workspace. Same handling as
1302 // above for ACTION_LOCALE_CHANGED
1303 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001304 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001305 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001306 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001307 forceReload();
1308 }
1309 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001310 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001311 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1312 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001313 Callbacks callbacks = getCallback();
1314 if (callbacks != null) {
1315 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001316 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001317 }
1318 }
1319
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001320 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001321 resetLoadedState(true, true);
1322
Reena Lee93f824a2011-09-23 17:20:28 -07001323 // Do this here because if the launcher activity is running it will be restarted.
1324 // If it's not running startLoaderFromBackground will merely tell it that it needs
1325 // to reload.
1326 startLoaderFromBackground();
1327 }
1328
Winson Chungf0c6ae02012-03-21 16:10:31 -07001329 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1330 synchronized (mLock) {
1331 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1332 // mWorkspaceLoaded to true later
1333 stopLoaderLocked();
1334 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1335 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1336 }
1337 }
1338
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001339 /**
1340 * When the launcher is in the background, it's possible for it to miss paired
1341 * configuration changes. So whenever we trigger the loader from the background
1342 * tell the launcher that it needs to re-run the loader when it comes back instead
1343 * of doing it now.
1344 */
1345 public void startLoaderFromBackground() {
1346 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001347 Callbacks callbacks = getCallback();
1348 if (callbacks != null) {
1349 // Only actually run the loader if they're not paused.
1350 if (!callbacks.setLoadOnResume()) {
1351 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001352 }
1353 }
1354 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001355 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001356 }
Joe Onorato36115782010-06-17 13:28:48 -04001357 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001358
Reena Lee93f824a2011-09-23 17:20:28 -07001359 // If there is already a loader task running, tell it to stop.
1360 // returns true if isLaunching() was true on the old task
1361 private boolean stopLoaderLocked() {
1362 boolean isLaunching = false;
1363 LoaderTask oldTask = mLoaderTask;
1364 if (oldTask != null) {
1365 if (oldTask.isLaunching()) {
1366 isLaunching = true;
1367 }
1368 oldTask.stopLocked();
1369 }
1370 return isLaunching;
1371 }
1372
Adam Cohen1a85c582014-09-30 09:48:49 -07001373 public boolean isCurrentCallbacks(Callbacks callbacks) {
1374 return (mCallbacks != null && mCallbacks.get() == callbacks);
1375 }
1376
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001377 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001378 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1379 }
1380
1381 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001382 synchronized (mLock) {
1383 if (DEBUG_LOADERS) {
1384 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1385 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001386
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 // Clear any deferred bind-runnables from the synchronized load process
1388 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001389 synchronized (mDeferredBindRunnables) {
1390 mDeferredBindRunnables.clear();
1391 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001392
Joe Onorato36115782010-06-17 13:28:48 -04001393 // Don't bother to start the thread if we know it's not going to do anything
1394 if (mCallbacks != null && mCallbacks.get() != null) {
1395 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001396 // also, don't downgrade isLaunching if we're already running
1397 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001398 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001399 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1400 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1402 } else {
1403 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1404 sWorker.post(mLoaderTask);
1405 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001406 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001407 }
1408 }
1409
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001410 void bindRemainingSynchronousPages() {
1411 // Post the remaining side pages to be loaded
1412 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001413 Runnable[] deferredBindRunnables = null;
1414 synchronized (mDeferredBindRunnables) {
1415 deferredBindRunnables = mDeferredBindRunnables.toArray(
1416 new Runnable[mDeferredBindRunnables.size()]);
1417 mDeferredBindRunnables.clear();
1418 }
1419 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001420 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001421 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001422 }
1423 }
1424
Joe Onorato36115782010-06-17 13:28:48 -04001425 public void stopLoader() {
1426 synchronized (mLock) {
1427 if (mLoaderTask != null) {
1428 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001429 }
1430 }
Joe Onorato36115782010-06-17 13:28:48 -04001431 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001432
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001433 /**
1434 * Loads the workspace screen ids in an ordered list.
1435 */
1436 private static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001437 final ContentResolver contentResolver = context.getContentResolver();
1438 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001439
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001440 // Get screens ordered by rank.
1441 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1442 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1443 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001444 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001445 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001446 while (sc.moveToNext()) {
1447 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001448 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001449 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001450 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1451 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001452 }
1453 }
1454 } finally {
1455 sc.close();
1456 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001457 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001458 }
1459
Michael Jurkac57b7a82011-08-09 22:02:20 -07001460 public boolean isAllAppsLoaded() {
1461 return mAllAppsLoaded;
1462 }
1463
Winson Chung36a62fe2012-05-06 18:04:42 -07001464 boolean isLoadingWorkspace() {
1465 synchronized (mLock) {
1466 if (mLoaderTask != null) {
1467 return mLoaderTask.isLoadingWorkspace();
1468 }
1469 }
1470 return false;
1471 }
1472
Joe Onorato36115782010-06-17 13:28:48 -04001473 /**
1474 * Runnable for the thread that loads the contents of the launcher:
1475 * - workspace icons
1476 * - widgets
1477 * - all apps icons
1478 */
1479 private class LoaderTask implements Runnable {
1480 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001481 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001482 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001483 private boolean mStopped;
1484 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001485 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001486
Winson Chungc3eecff2011-07-11 17:44:15 -07001487 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001488
Dan Sandlerd5024042014-01-09 15:01:33 -05001489 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001490 mContext = context;
1491 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001492 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001493 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001494 }
1495
Joe Onorato36115782010-06-17 13:28:48 -04001496 boolean isLaunching() {
1497 return mIsLaunching;
1498 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001499
Winson Chung36a62fe2012-05-06 18:04:42 -07001500 boolean isLoadingWorkspace() {
1501 return mIsLoadingAndBindingWorkspace;
1502 }
1503
Winson Chungc763c4e2013-07-19 13:49:06 -07001504 /** Returns whether this is an upgrade path */
1505 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001506 mIsLoadingAndBindingWorkspace = true;
1507
Joe Onorato36115782010-06-17 13:28:48 -04001508 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001509 if (DEBUG_LOADERS) {
1510 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001511 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001512
Winson Chungc763c4e2013-07-19 13:49:06 -07001513 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001514 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001515 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001516 synchronized (LoaderTask.this) {
1517 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001518 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001519 }
1520 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001521 }
1522 }
1523
Joe Onorato36115782010-06-17 13:28:48 -04001524 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001525 bindWorkspace(-1, isUpgradePath);
1526 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001527 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001528
Joe Onorato36115782010-06-17 13:28:48 -04001529 private void waitForIdle() {
1530 // Wait until the either we're stopped or the other threads are done.
1531 // This way we don't start loading all apps until the workspace has settled
1532 // down.
1533 synchronized (LoaderTask.this) {
1534 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001535
Joe Onorato36115782010-06-17 13:28:48 -04001536 mHandler.postIdle(new Runnable() {
1537 public void run() {
1538 synchronized (LoaderTask.this) {
1539 mLoadAndBindStepFinished = true;
1540 if (DEBUG_LOADERS) {
1541 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001542 }
Joe Onorato36115782010-06-17 13:28:48 -04001543 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001544 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001545 }
Joe Onorato36115782010-06-17 13:28:48 -04001546 });
1547
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001548 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001549 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001550 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1551 // wait no longer than 1sec at a time
1552 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001553 } catch (InterruptedException ex) {
1554 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001555 }
1556 }
Joe Onorato36115782010-06-17 13:28:48 -04001557 if (DEBUG_LOADERS) {
1558 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001559 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001560 + "ms for previous step to finish binding");
1561 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001562 }
Joe Onorato36115782010-06-17 13:28:48 -04001563 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001564
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001565 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001566 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001567 // Ensure that we have a valid page index to load synchronously
1568 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1569 "valid page index");
1570 }
1571 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1572 // Ensure that we don't try and bind a specified page when the pages have not been
1573 // loaded already (we should load everything asynchronously in that case)
1574 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1575 }
1576 synchronized (mLock) {
1577 if (mIsLoaderTaskRunning) {
1578 // Ensure that we are never running the background loading at this point since
1579 // we also touch the background collections
1580 throw new RuntimeException("Error! Background loading is already running");
1581 }
1582 }
1583
1584 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1585 // data structures, we can't allow any other thread to touch that data, but because
1586 // this call is synchronous, we can get away with not locking).
1587
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001588 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001589 // operations from the previous activity. We need to ensure that all queued operations
1590 // are executed before any synchronous binding work is done.
1591 mHandler.flush();
1592
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001593 // Divide the set of loaded items into those that we are binding synchronously, and
1594 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001595 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001596 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1597 // arise from that.
1598 onlyBindAllApps();
1599 }
1600
Joe Onorato36115782010-06-17 13:28:48 -04001601 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001602 boolean isUpgrade = false;
1603
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001604 synchronized (mLock) {
1605 mIsLoaderTaskRunning = true;
1606 }
Joe Onorato36115782010-06-17 13:28:48 -04001607 // Optimize for end-user experience: if the Launcher is up and // running with the
1608 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1609 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001610 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001611 // Elevate priority when Home launches for the first time to avoid
1612 // starving at boot time. Staring at a blank home is not cool.
1613 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001614 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1615 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001616 android.os.Process.setThreadPriority(mIsLaunching
1617 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1618 }
Winson Chung64359a52013-07-08 17:17:08 -07001619 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001620 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001621
Joe Onorato36115782010-06-17 13:28:48 -04001622 if (mStopped) {
1623 break keep_running;
1624 }
1625
1626 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1627 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001628 synchronized (mLock) {
1629 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001630 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001631 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1632 }
1633 }
Joe Onorato36115782010-06-17 13:28:48 -04001634 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001635
1636 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001637 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1638 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001639
1640 // Restore the default thread priority after we are done loading items
1641 synchronized (mLock) {
1642 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1643 }
Joe Onorato36115782010-06-17 13:28:48 -04001644 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001645
Winson Chungaac01e12011-08-17 10:37:13 -07001646 // Update the saved icons if necessary
1647 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001648 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001649 for (Object key : sBgDbIconCache.keySet()) {
1650 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1651 }
1652 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001653 }
Winson Chungaac01e12011-08-17 10:37:13 -07001654
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001655 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001656 // Ensure that all the applications that are in the system are
1657 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001658 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001659 verifyApplications();
1660 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001661 }
1662
Joe Onorato36115782010-06-17 13:28:48 -04001663 // Clear out this reference, otherwise we end up holding it until all of the
1664 // callback runnables are done.
1665 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001666
Joe Onorato36115782010-06-17 13:28:48 -04001667 synchronized (mLock) {
1668 // If we are still the last one to be scheduled, remove ourselves.
1669 if (mLoaderTask == this) {
1670 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001671 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001672 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001673 }
Joe Onorato36115782010-06-17 13:28:48 -04001674 }
1675
1676 public void stopLocked() {
1677 synchronized (LoaderTask.this) {
1678 mStopped = true;
1679 this.notify();
1680 }
1681 }
1682
1683 /**
1684 * Gets the callbacks object. If we've been stopped, or if the launcher object
1685 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1686 * object that was around when the deferred message was scheduled, and if there's
1687 * a new Callbacks object around then also return null. This will save us from
1688 * calling onto it with data that will be ignored.
1689 */
1690 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1691 synchronized (mLock) {
1692 if (mStopped) {
1693 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001694 }
Joe Onorato36115782010-06-17 13:28:48 -04001695
1696 if (mCallbacks == null) {
1697 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001698 }
Joe Onorato36115782010-06-17 13:28:48 -04001699
1700 final Callbacks callbacks = mCallbacks.get();
1701 if (callbacks != oldCallbacks) {
1702 return null;
1703 }
1704 if (callbacks == null) {
1705 Log.w(TAG, "no mCallbacks");
1706 return null;
1707 }
1708
1709 return callbacks;
1710 }
1711 }
1712
Winson Chungc763c4e2013-07-19 13:49:06 -07001713 private void verifyApplications() {
1714 final Context context = mApp.getContext();
1715
1716 // Cross reference all the applications in our apps list with items in the workspace
1717 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001718 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001719 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001720 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001721 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001722 if (tmpInfos.isEmpty()) {
1723 // We are missing an application icon, so add this to the workspace
1724 added.add(app);
1725 // This is a rare event, so lets log it
1726 Log.e(TAG, "Missing Application on load: " + app);
1727 }
1728 }
1729 }
1730 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001731 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001732 }
1733 }
1734
Joe Onorato36115782010-06-17 13:28:48 -04001735 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001736 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001737 LauncherAppState app = LauncherAppState.getInstance();
1738 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001739 final int countX = (int) grid.numColumns;
1740 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001741
Adam Cohendcd297f2013-06-18 13:13:40 -07001742 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001743 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001744 // Return early if we detect that an item is under the hotseat button
1745 if (mCallbacks == null ||
1746 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001747 Log.e(TAG, "Error loading shortcut into hotseat " + item
1748 + " into position (" + item.screenId + ":" + item.cellX + ","
1749 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001750 return false;
1751 }
1752
Dan Sandler295ae182013-12-10 16:05:47 -05001753 final ItemInfo[][] hotseatItems =
1754 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1755
Adam Cohenae4409d2013-11-26 10:34:59 -08001756 if (item.screenId >= grid.numHotseatIcons) {
1757 Log.e(TAG, "Error loading shortcut " + item
1758 + " into hotseat position " + item.screenId
1759 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1760 + ")");
1761 return false;
1762 }
1763
Dan Sandler295ae182013-12-10 16:05:47 -05001764 if (hotseatItems != null) {
1765 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 Log.e(TAG, "Error loading shortcut into hotseat " + item
1767 + " into position (" + item.screenId + ":" + item.cellX + ","
1768 + item.cellY + ") occupied by "
1769 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1770 [(int) item.screenId][0]);
1771 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001772 } else {
1773 hotseatItems[(int) item.screenId][0] = item;
1774 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001775 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001776 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001777 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001778 items[(int) item.screenId][0] = item;
1779 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001780 return true;
1781 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001782 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1783 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001784 return true;
1785 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001786
Adam Cohendcd297f2013-06-18 13:13:40 -07001787 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001788 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001789 occupied.put(item.screenId, items);
1790 }
1791
Dan Sandler295ae182013-12-10 16:05:47 -05001792 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001793 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1794 item.cellX < 0 || item.cellY < 0 ||
1795 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1796 Log.e(TAG, "Error loading shortcut " + item
1797 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1798 + item.cellX + "," + item.cellY
1799 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1800 return false;
1801 }
1802
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001803 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001804 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1805 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001806 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001807 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001808 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001809 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001810 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001811 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001812 return false;
1813 }
1814 }
1815 }
1816 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1817 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001818 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001819 }
1820 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001821
Joe Onorato36115782010-06-17 13:28:48 -04001822 return true;
1823 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001824
Winson Chungba9c37f2013-08-30 14:11:37 -07001825 /** Clears all the sBg data structures */
1826 private void clearSBgDataStructures() {
1827 synchronized (sBgLock) {
1828 sBgWorkspaceItems.clear();
1829 sBgAppWidgets.clear();
1830 sBgFolders.clear();
1831 sBgItemsIdMap.clear();
1832 sBgDbIconCache.clear();
1833 sBgWorkspaceScreens.clear();
1834 }
1835 }
1836
Dan Sandlerd5024042014-01-09 15:01:33 -05001837 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001838 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001839 // Log to disk
1840 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1841
Joe Onorato36115782010-06-17 13:28:48 -04001842 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001843
Joe Onorato36115782010-06-17 13:28:48 -04001844 final Context context = mContext;
1845 final ContentResolver contentResolver = context.getContentResolver();
1846 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001847 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001848 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1849 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001850 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001851
Winson Chung892c74d2013-08-22 16:15:50 -07001852 LauncherAppState app = LauncherAppState.getInstance();
1853 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1854 int countX = (int) grid.numColumns;
1855 int countY = (int) grid.numRows;
1856
Dan Sandlerd5024042014-01-09 15:01:33 -05001857 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1858 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1859 LauncherAppState.getLauncherProvider().deleteDatabase();
1860 }
1861
1862 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1863 // append the user's Launcher2 shortcuts
1864 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1865 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1866 } else {
1867 // Make sure the default workspace is loaded
1868 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001869 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001870 }
Adam Cohene25af792013-06-06 23:08:25 -07001871
Adam Cohen71483f42014-05-15 14:04:01 -07001872 // This code path is for our old migration code and should no longer be exercised
1873 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001874
Winson Chung9f9f00b2013-11-15 13:27:00 -08001875 // Log to disk
1876 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001877
Winson Chung2abf94d2012-07-18 18:16:38 -07001878 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001879 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001880 final HashSet<String> installingPkgs = PackageInstallerCompat
1881 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001882
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001884 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001885 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001886 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001887 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001888
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001889 // +1 for the hotseat (it can be larger than the workspace)
1890 // Load workspace in reverse order to ensure that latest items are loaded first (and
1891 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001892 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001893
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001894 try {
1895 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1896 final int intentIndex = c.getColumnIndexOrThrow
1897 (LauncherSettings.Favorites.INTENT);
1898 final int titleIndex = c.getColumnIndexOrThrow
1899 (LauncherSettings.Favorites.TITLE);
1900 final int iconTypeIndex = c.getColumnIndexOrThrow(
1901 LauncherSettings.Favorites.ICON_TYPE);
1902 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1903 final int iconPackageIndex = c.getColumnIndexOrThrow(
1904 LauncherSettings.Favorites.ICON_PACKAGE);
1905 final int iconResourceIndex = c.getColumnIndexOrThrow(
1906 LauncherSettings.Favorites.ICON_RESOURCE);
1907 final int containerIndex = c.getColumnIndexOrThrow(
1908 LauncherSettings.Favorites.CONTAINER);
1909 final int itemTypeIndex = c.getColumnIndexOrThrow(
1910 LauncherSettings.Favorites.ITEM_TYPE);
1911 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1912 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001913 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1914 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001915 final int screenIndex = c.getColumnIndexOrThrow(
1916 LauncherSettings.Favorites.SCREEN);
1917 final int cellXIndex = c.getColumnIndexOrThrow
1918 (LauncherSettings.Favorites.CELLX);
1919 final int cellYIndex = c.getColumnIndexOrThrow
1920 (LauncherSettings.Favorites.CELLY);
1921 final int spanXIndex = c.getColumnIndexOrThrow
1922 (LauncherSettings.Favorites.SPANX);
1923 final int spanYIndex = c.getColumnIndexOrThrow(
1924 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001925 final int rankIndex = c.getColumnIndexOrThrow(
1926 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001927 final int restoredIndex = c.getColumnIndexOrThrow(
1928 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001929 final int profileIdIndex = c.getColumnIndexOrThrow(
1930 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001931 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1932 //final int displayModeIndex = c.getColumnIndexOrThrow(
1933 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001934
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001935 ShortcutInfo info;
1936 String intentDescription;
1937 LauncherAppWidgetInfo appWidgetInfo;
1938 int container;
1939 long id;
1940 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001941 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001942
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001943 while (!mStopped && c.moveToNext()) {
1944 try {
1945 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001946 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001947 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001948
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001949 switch (itemType) {
1950 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1951 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001952 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001953 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001954 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001955 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001956 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001957 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001958 if (user == null) {
1959 // User has been deleted remove the item.
1960 itemsToRemove.add(id);
1961 continue;
1962 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001963 try {
1964 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001965 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001966 if (cn != null && cn.getPackageName() != null) {
1967 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1968 cn.getPackageName(), user);
1969 boolean validComponent = validPkg &&
1970 launcherApps.isActivityEnabledForProfile(cn, user);
1971
1972 if (validComponent) {
1973 if (restored) {
1974 // no special handling necessary for this item
1975 restoredRows.add(id);
1976 restored = false;
1977 }
1978 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001979 intent = null;
1980 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1981 // We allow auto install apps to have their intent
1982 // updated after an install.
1983 intent = manager.getLaunchIntentForPackage(
1984 cn.getPackageName());
1985 if (intent != null) {
1986 ContentValues values = new ContentValues();
1987 values.put(LauncherSettings.Favorites.INTENT,
1988 intent.toUri(0));
1989 String where = BaseColumns._ID + "= ?";
1990 String[] args = {Long.toString(id)};
1991 contentResolver.update(contentUri, values, where, args);
1992 }
1993 }
1994
1995 if (intent == null) {
1996 // The app is installed but the component is no
1997 // longer available.
1998 Launcher.addDumpLog(TAG,
1999 "Invalid component removed: " + cn, true);
2000 itemsToRemove.add(id);
2001 continue;
2002 } else {
2003 // no special handling necessary for this item
2004 restoredRows.add(id);
2005 restored = false;
2006 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002007 } else if (restored) {
2008 // Package is not yet available but might be
2009 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002010 Launcher.addDumpLog(TAG,
2011 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002012
2013 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2014 // Restore has started once.
2015 } else if (installingPkgs.contains(cn.getPackageName())) {
2016 // App restore has started. Update the flag
2017 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2018 ContentValues values = new ContentValues();
2019 values.put(LauncherSettings.Favorites.RESTORED,
2020 promiseType);
2021 String where = BaseColumns._ID + "= ?";
2022 String[] args = {Long.toString(id)};
2023 contentResolver.update(contentUri, values, where, args);
2024
2025 } else if (REMOVE_UNRESTORED_ICONS) {
2026 Launcher.addDumpLog(TAG,
2027 "Unrestored package removed: " + cn, true);
2028 itemsToRemove.add(id);
2029 continue;
2030 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002031 } else if (launcherApps.isAppEnabled(
2032 manager, cn.getPackageName(),
2033 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2034 // Package is present but not available.
2035 allowMissingTarget = true;
2036 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2037 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002038 // SdCard is not ready yet. Package might get available,
2039 // once it is ready.
2040 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2041 + " (check again later)", true);
2042 HashSet<String> pkgs = sPendingPackages.get(user);
2043 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002044 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002045 sPendingPackages.put(user, pkgs);
2046 }
2047 pkgs.add(cn.getPackageName());
2048 allowMissingTarget = true;
2049 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002050
2051 } else {
2052 // Do not wait for external media load anymore.
2053 // Log the invalid package, and remove it
2054 Launcher.addDumpLog(TAG,
2055 "Invalid package removed: " + cn, true);
2056 itemsToRemove.add(id);
2057 continue;
Winson Chungee055712013-07-30 14:46:24 -07002058 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002059 } else if (cn == null) {
2060 // For shortcuts with no component, keep them as they are
2061 restoredRows.add(id);
2062 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002063 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002064 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002065 Launcher.addDumpLog(TAG,
2066 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002067 continue;
2068 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002069
Chris Wrenf4d08112014-01-16 18:13:56 -05002070 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002071 if (user.equals(UserHandleCompat.myUserHandle())) {
2072 Launcher.addDumpLog(TAG,
2073 "constructing info for partially restored package",
2074 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002075 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002076 intent = getRestoredItemIntent(c, context, intent);
2077 } else {
2078 // Don't restore items for other profiles.
2079 itemsToRemove.add(id);
2080 continue;
2081 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002082 } else if (itemType ==
2083 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002084 info = getShortcutInfo(manager, intent, user, context, c,
2085 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 } else {
2087 info = getShortcutInfo(c, context, iconTypeIndex,
2088 iconPackageIndex, iconResourceIndex, iconIndex,
2089 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002090
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 // App shortcuts that used to be automatically added to Launcher
2092 // didn't always have the correct intent flags set, so do that
2093 // here
2094 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002095 intent.getCategories() != null &&
2096 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002097 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 intent.addFlags(
2099 Intent.FLAG_ACTIVITY_NEW_TASK |
2100 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2101 }
Michael Jurka96879562012-03-22 05:54:33 -07002102 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002103
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002104 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002105 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002106 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002107 container = c.getInt(containerIndex);
2108 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002109 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002110 info.cellX = c.getInt(cellXIndex);
2111 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002112 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002113 info.spanX = 1;
2114 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002115 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002116 info.isDisabled = disabledState;
2117 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2118 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2119 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002120
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002122 if (!checkItemPlacement(occupied, info)) {
2123 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002124 break;
2125 }
2126
2127 switch (container) {
2128 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2129 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2130 sBgWorkspaceItems.add(info);
2131 break;
2132 default:
2133 // Item is in a user folder
2134 FolderInfo folderInfo =
2135 findOrMakeFolder(sBgFolders, container);
2136 folderInfo.add(info);
2137 break;
2138 }
2139 sBgItemsIdMap.put(info.id, info);
2140
2141 // now that we've loaded everthing re-save it with the
2142 // icon in case it disappears somehow.
2143 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002144 } else {
2145 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 }
2147 break;
2148
2149 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2150 id = c.getLong(idIndex);
2151 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2152
2153 folderInfo.title = c.getString(titleIndex);
2154 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002155 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002156 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002157 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002158 folderInfo.cellX = c.getInt(cellXIndex);
2159 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002160 folderInfo.spanX = 1;
2161 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002162
Daniel Sandler8802e962010-05-26 16:28:16 -04002163 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002164 if (!checkItemPlacement(occupied, folderInfo)) {
2165 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002166 break;
2167 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002168
Joe Onorato9c1289c2009-08-17 11:03:03 -04002169 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2171 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2172 sBgWorkspaceItems.add(folderInfo);
2173 break;
Joe Onorato36115782010-06-17 13:28:48 -04002174 }
Joe Onorato17a89222011-02-08 17:26:11 -08002175
Chris Wrenf4d08112014-01-16 18:13:56 -05002176 if (restored) {
2177 // no special handling required for restored folders
2178 restoredRows.add(id);
2179 }
2180
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002181 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2182 sBgFolders.put(folderInfo.id, folderInfo);
2183 break;
2184
2185 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002186 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002188 boolean customWidget = itemType ==
2189 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2190
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002191 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002192 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002193 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002194 final ComponentName component =
2195 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002196
Sunny Goyal651077b2014-06-30 14:15:31 -07002197 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002198 final boolean isIdValid = (restoreStatus &
2199 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002200
Sunny Goyalff572272014-07-23 13:58:07 -07002201 final boolean wasProviderReady = (restoreStatus &
2202 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002203
Adam Cohen59400422014-03-05 18:07:04 -08002204 final LauncherAppWidgetProviderInfo provider =
2205 LauncherModel.getProviderInfo(context,
2206 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002207
2208 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002209 if (!isSafeMode && !customWidget &&
2210 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002212 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002213
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002214 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002215 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216 itemsToRemove.add(id);
2217 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002218 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002219 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2220 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002221
2222 if (!customWidget) {
2223 int[] minSpan =
2224 Launcher.getMinSpanForWidget(context, provider);
2225 appWidgetInfo.minSpanX = minSpan[0];
2226 appWidgetInfo.minSpanY = minSpan[1];
2227 }
Sunny Goyalff572272014-07-23 13:58:07 -07002228
2229 int status = restoreStatus;
2230 if (!wasProviderReady) {
2231 // If provider was not previously ready, update the
2232 // status and UI flag.
2233
2234 // Id would be valid only if the widget restore broadcast was received.
2235 if (isIdValid) {
2236 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2237 } else {
2238 status &= ~LauncherAppWidgetInfo
2239 .FLAG_PROVIDER_NOT_READY;
2240 }
2241 }
2242 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002243 } else {
2244 Log.v(TAG, "Widget restore pending id=" + id
2245 + " appWidgetId=" + appWidgetId
2246 + " status =" + restoreStatus);
2247 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002248 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002249 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002250
2251 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2252 // Restore has started once.
2253 } else if (installingPkgs.contains(component.getPackageName())) {
2254 // App restore has started. Update the flag
2255 appWidgetInfo.restoreStatus |=
2256 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002257 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002258 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002259 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002260 itemsToRemove.add(id);
2261 continue;
2262 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002263 }
Sunny Goyalff572272014-07-23 13:58:07 -07002264
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002265 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002266 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002267 appWidgetInfo.cellX = c.getInt(cellXIndex);
2268 appWidgetInfo.cellY = c.getInt(cellYIndex);
2269 appWidgetInfo.spanX = c.getInt(spanXIndex);
2270 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002271
Adam Cohen59400422014-03-05 18:07:04 -08002272 if (!customWidget) {
2273 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2274 appWidgetInfo.minSpanX = minSpan[0];
2275 appWidgetInfo.minSpanY = minSpan[1];
2276 }
2277
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002278 container = c.getInt(containerIndex);
2279 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2280 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2281 Log.e(TAG, "Widget found where container != " +
2282 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2283 continue;
2284 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285
Adam Cohene25af792013-06-06 23:08:25 -07002286 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002288 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2289 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002290 break;
2291 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002292
Adam Cohen59400422014-03-05 18:07:04 -08002293 if (!customWidget) {
2294 String providerName =
2295 appWidgetInfo.providerName.flattenToString();
2296 if (!providerName.equals(savedProvider) ||
2297 (appWidgetInfo.restoreStatus != restoreStatus)) {
2298 ContentValues values = new ContentValues();
2299 values.put(
2300 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2301 providerName);
2302 values.put(LauncherSettings.Favorites.RESTORED,
2303 appWidgetInfo.restoreStatus);
2304 String where = BaseColumns._ID + "= ?";
2305 String[] args = {Long.toString(id)};
2306 contentResolver.update(contentUri, values, where, args);
2307 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002308 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002309 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2310 sBgAppWidgets.add(appWidgetInfo);
2311 }
Joe Onorato36115782010-06-17 13:28:48 -04002312 break;
2313 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002314 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002315 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002316 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002317 }
2318 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002319 if (c != null) {
2320 c.close();
2321 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002322 }
2323
Winson Chungba9c37f2013-08-30 14:11:37 -07002324 // Break early if we've stopped loading
2325 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002326 clearSBgDataStructures();
2327 return false;
2328 }
2329
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002330 if (itemsToRemove.size() > 0) {
2331 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002332 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002333 // Remove dead items
2334 for (long id : itemsToRemove) {
2335 if (DEBUG_LOADERS) {
2336 Log.d(TAG, "Removed id = " + id);
2337 }
2338 // Don't notify content observers
2339 try {
2340 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2341 null, null);
2342 } catch (RemoteException e) {
2343 Log.w(TAG, "Could not remove id = " + id);
2344 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002345 }
2346 }
2347
Chris Wrenf4d08112014-01-16 18:13:56 -05002348 if (restoredRows.size() > 0) {
2349 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002350 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002351 // Update restored items that no longer require special handling
2352 try {
2353 StringBuilder selectionBuilder = new StringBuilder();
2354 selectionBuilder.append(LauncherSettings.Favorites._ID);
2355 selectionBuilder.append(" IN (");
2356 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2357 selectionBuilder.append(")");
2358 ContentValues values = new ContentValues();
2359 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002360 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002361 values, selectionBuilder.toString(), null);
2362 } catch (RemoteException e) {
2363 Log.w(TAG, "Could not update restored rows");
2364 }
2365 }
2366
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002367 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2368 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002369 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002370 null, sWorker);
2371 }
2372
Winson Chungc763c4e2013-07-19 13:49:06 -07002373 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002374 long maxScreenId = 0;
2375 // If we're importing we use the old screen order.
2376 for (ItemInfo item: sBgItemsIdMap.values()) {
2377 long screenId = item.screenId;
2378 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2379 !sBgWorkspaceScreens.contains(screenId)) {
2380 sBgWorkspaceScreens.add(screenId);
2381 if (screenId > maxScreenId) {
2382 maxScreenId = screenId;
2383 }
2384 }
2385 }
2386 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002387 // Log to disk
2388 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2389 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2390 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002391
Michael Jurka414300a2013-08-27 15:42:35 +02002392 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002393 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002394
2395 // Update the max item id after we load an old db
2396 long maxItemId = 0;
2397 // If we're importing we use the old screen order.
2398 for (ItemInfo item: sBgItemsIdMap.values()) {
2399 maxItemId = Math.max(maxItemId, item.id);
2400 }
Michael Jurka414300a2013-08-27 15:42:35 +02002401 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002402 } else {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08002403 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
Winson Chung9f9f00b2013-11-15 13:27:00 -08002404 // Log to disk
2405 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2406 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002407
2408 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002409 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002410 for (ItemInfo item: sBgItemsIdMap.values()) {
2411 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002412 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2413 unusedScreens.contains(screenId)) {
2414 unusedScreens.remove(screenId);
2415 }
2416 }
2417
2418 // If there are any empty screens remove them, and update.
2419 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002420 // Log to disk
2421 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2422 TextUtils.join(", ", unusedScreens), true);
2423
Winson Chung933bae62013-08-29 11:42:30 -07002424 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002425 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2426 }
2427 }
2428
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 if (DEBUG_LOADERS) {
2430 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2431 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002432 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002433 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002434 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002435
Daniel Sandler566da102013-06-25 23:43:45 -04002436 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002437 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002438 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002439 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 line += " | ";
2441 }
Winson Chung892c74d2013-08-22 16:15:50 -07002442 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002443 ItemInfo[][] screen = occupied.get(screenId);
2444 if (x < screen.length && y < screen[x].length) {
2445 line += (screen[x][y] != null) ? "#" : ".";
2446 } else {
2447 line += "!";
2448 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002449 }
Joe Onorato36115782010-06-17 13:28:48 -04002450 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002452 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002453 }
Joe Onorato36115782010-06-17 13:28:48 -04002454 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002455 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002456 }
2457
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002458 /** Filters the set of items who are directly or indirectly (via another container) on the
2459 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002460 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461 ArrayList<ItemInfo> allWorkspaceItems,
2462 ArrayList<ItemInfo> currentScreenItems,
2463 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002464 // Purge any null ItemInfos
2465 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2466 while (iter.hasNext()) {
2467 ItemInfo i = iter.next();
2468 if (i == null) {
2469 iter.remove();
2470 }
2471 }
2472
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473 // Order the set of items by their containers first, this allows use to walk through the
2474 // list sequentially, build up a list of containers that are in the specified screen,
2475 // as well as all items in those containers.
2476 Set<Long> itemsOnScreen = new HashSet<Long>();
2477 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2478 @Override
2479 public int compare(ItemInfo lhs, ItemInfo rhs) {
2480 return (int) (lhs.container - rhs.container);
2481 }
2482 });
2483 for (ItemInfo info : allWorkspaceItems) {
2484 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002485 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002486 currentScreenItems.add(info);
2487 itemsOnScreen.add(info.id);
2488 } else {
2489 otherScreenItems.add(info);
2490 }
2491 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2492 currentScreenItems.add(info);
2493 itemsOnScreen.add(info.id);
2494 } else {
2495 if (itemsOnScreen.contains(info.container)) {
2496 currentScreenItems.add(info);
2497 itemsOnScreen.add(info.id);
2498 } else {
2499 otherScreenItems.add(info);
2500 }
2501 }
2502 }
2503 }
2504
2505 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002506 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 ArrayList<LauncherAppWidgetInfo> appWidgets,
2508 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2509 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002510
2511 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002512 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002513 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002514 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002515 currentScreenWidgets.add(widget);
2516 } else {
2517 otherScreenWidgets.add(widget);
2518 }
2519 }
2520 }
2521
2522 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002523 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002524 HashMap<Long, ItemInfo> itemsIdMap,
2525 HashMap<Long, FolderInfo> folders,
2526 HashMap<Long, FolderInfo> currentScreenFolders,
2527 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002528
2529 for (long id : folders.keySet()) {
2530 ItemInfo info = itemsIdMap.get(id);
2531 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002532 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002534 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002535 currentScreenFolders.put(id, folder);
2536 } else {
2537 otherScreenFolders.put(id, folder);
2538 }
2539 }
2540 }
2541
2542 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2543 * right) */
2544 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002545 final LauncherAppState app = LauncherAppState.getInstance();
2546 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547 // XXX: review this
2548 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002549 @Override
2550 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002551 int cellCountX = (int) grid.numColumns;
2552 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002553 int screenOffset = cellCountX * cellCountY;
2554 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002555 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002556 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002557 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002558 rhs.cellY * cellCountX + rhs.cellX);
2559 return (int) (lr - rr);
2560 }
2561 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002563
Adam Cohendcd297f2013-06-18 13:13:40 -07002564 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2565 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002566 final Runnable r = new Runnable() {
2567 @Override
2568 public void run() {
2569 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2570 if (callbacks != null) {
2571 callbacks.bindScreens(orderedScreens);
2572 }
2573 }
2574 };
2575 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2576 }
2577
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002578 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2579 final ArrayList<ItemInfo> workspaceItems,
2580 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2581 final HashMap<Long, FolderInfo> folders,
2582 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002583
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584 final boolean postOnMainThread = (deferredBindRunnables != null);
2585
2586 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002587 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002588 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002589 final int start = i;
2590 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 final Runnable r = new Runnable() {
2592 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002593 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002594 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002595 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002596 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2597 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002598 }
2599 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002600 };
2601 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002602 synchronized (deferredBindRunnables) {
2603 deferredBindRunnables.add(r);
2604 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002605 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002606 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002607 }
Joe Onorato36115782010-06-17 13:28:48 -04002608 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002609
2610 // Bind the folders
2611 if (!folders.isEmpty()) {
2612 final Runnable r = new Runnable() {
2613 public void run() {
2614 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2615 if (callbacks != null) {
2616 callbacks.bindFolders(folders);
2617 }
2618 }
2619 };
2620 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002621 synchronized (deferredBindRunnables) {
2622 deferredBindRunnables.add(r);
2623 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002624 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002625 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002626 }
2627 }
2628
2629 // Bind the widgets, one at a time
2630 N = appWidgets.size();
2631 for (int i = 0; i < N; i++) {
2632 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2633 final Runnable r = new Runnable() {
2634 public void run() {
2635 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2636 if (callbacks != null) {
2637 callbacks.bindAppWidget(widget);
2638 }
2639 }
2640 };
2641 if (postOnMainThread) {
2642 deferredBindRunnables.add(r);
2643 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002644 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002645 }
2646 }
2647 }
2648
2649 /**
2650 * Binds all loaded data to actual views on the main thread.
2651 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002652 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 final long t = SystemClock.uptimeMillis();
2654 Runnable r;
2655
2656 // Don't use these two variables in any of the callback runnables.
2657 // Otherwise we hold a reference to them.
2658 final Callbacks oldCallbacks = mCallbacks.get();
2659 if (oldCallbacks == null) {
2660 // This launcher has exited and nobody bothered to tell us. Just bail.
2661 Log.w(TAG, "LoaderTask running with no launcher");
2662 return;
2663 }
2664
Winson Chung9b9fb962013-11-15 15:39:34 -08002665 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2667 ArrayList<LauncherAppWidgetInfo> appWidgets =
2668 new ArrayList<LauncherAppWidgetInfo>();
2669 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2670 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002671 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002672 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002673 workspaceItems.addAll(sBgWorkspaceItems);
2674 appWidgets.addAll(sBgAppWidgets);
2675 folders.putAll(sBgFolders);
2676 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002677 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002678 }
2679
Derek Prothro7aff3992013-12-10 14:00:37 -05002680 final boolean isLoadingSynchronously =
2681 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002682 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002683 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002684 if (currScreen >= orderedScreenIds.size()) {
2685 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002686 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002687 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002688 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002689 final long currentScreenId = currentScreen < 0
2690 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002691
2692 // Load all the items that are on the current page first (and in the process, unbind
2693 // all the existing workspace items before we call startBinding() below.
2694 unbindWorkspaceItemsOnMainThread();
2695
2696 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002697 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2698 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2699 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2700 new ArrayList<LauncherAppWidgetInfo>();
2701 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2702 new ArrayList<LauncherAppWidgetInfo>();
2703 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2704 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2705
Winson Chung9b9fb962013-11-15 15:39:34 -08002706 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002707 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002708 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002709 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002710 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002711 otherFolders);
2712 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2713 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2714
2715 // Tell the workspace that we're about to start binding items
2716 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002717 public void run() {
2718 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2719 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002720 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002721 }
2722 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002723 };
Winson Chung81b52252012-08-27 15:34:29 -07002724 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002725
Adam Cohendcd297f2013-06-18 13:13:40 -07002726 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2727
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002728 // Load items on the current page
2729 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2730 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002731 if (isLoadingSynchronously) {
2732 r = new Runnable() {
2733 public void run() {
2734 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002735 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002736 callbacks.onPageBoundSynchronously(currentScreen);
2737 }
2738 }
2739 };
Winson Chung81b52252012-08-27 15:34:29 -07002740 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002741 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002742
Winson Chung4a2afa32012-07-19 14:53:05 -07002743 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2744 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002745 synchronized (mDeferredBindRunnables) {
2746 mDeferredBindRunnables.clear();
2747 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002748 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002749 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002750
2751 // Tell the workspace that we're done binding items
2752 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002753 public void run() {
2754 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2755 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002756 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002757 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002758
Winson Chung98e030b2012-05-07 16:01:11 -07002759 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002760 if (DEBUG_LOADERS) {
2761 Log.d(TAG, "bound workspace in "
2762 + (SystemClock.uptimeMillis()-t) + "ms");
2763 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002764
2765 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002766 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002767 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002768 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002769 synchronized (mDeferredBindRunnables) {
2770 mDeferredBindRunnables.add(r);
2771 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002772 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002773 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002774 }
Joe Onorato36115782010-06-17 13:28:48 -04002775 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002776
Joe Onorato36115782010-06-17 13:28:48 -04002777 private void loadAndBindAllApps() {
2778 if (DEBUG_LOADERS) {
2779 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2780 }
2781 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002782 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002783 synchronized (LoaderTask.this) {
2784 if (mStopped) {
2785 return;
2786 }
2787 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002788 }
Joe Onorato36115782010-06-17 13:28:48 -04002789 } else {
2790 onlyBindAllApps();
2791 }
2792 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002793
Joe Onorato36115782010-06-17 13:28:48 -04002794 private void onlyBindAllApps() {
2795 final Callbacks oldCallbacks = mCallbacks.get();
2796 if (oldCallbacks == null) {
2797 // This launcher has exited and nobody bothered to tell us. Just bail.
2798 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2799 return;
2800 }
2801
2802 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002803 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002804 final ArrayList<AppInfo> list
2805 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002806 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002807 public void run() {
2808 final long t = SystemClock.uptimeMillis();
2809 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2810 if (callbacks != null) {
2811 callbacks.bindAllApplications(list);
2812 }
2813 if (DEBUG_LOADERS) {
2814 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2815 + (SystemClock.uptimeMillis()-t) + "ms");
2816 }
2817 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002818 };
2819 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002820 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002821 r.run();
2822 } else {
2823 mHandler.post(r);
2824 }
Joe Onorato36115782010-06-17 13:28:48 -04002825 }
2826
Winson Chung64359a52013-07-08 17:17:08 -07002827 private void loadAllApps() {
2828 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002829
Joe Onorato36115782010-06-17 13:28:48 -04002830 final Callbacks oldCallbacks = mCallbacks.get();
2831 if (oldCallbacks == null) {
2832 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002833 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002834 return;
2835 }
2836
2837 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2838 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2839
Kenny Guyed131872014-04-30 03:02:21 +01002840 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2841
Winson Chung64359a52013-07-08 17:17:08 -07002842 // Clear the list of apps
2843 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002844 SharedPreferences prefs = mContext.getSharedPreferences(
2845 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002846 for (UserHandleCompat user : profiles) {
2847 // Query for the set of apps
2848 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2849 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2850 if (DEBUG_LOADERS) {
2851 Log.d(TAG, "getActivityList took "
2852 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2853 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2854 }
2855 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002856 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002857 if (apps == null || apps.isEmpty()) {
2858 return;
2859 }
2860 // Sort the applications by name
2861 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2862 Collections.sort(apps,
2863 new LauncherModel.ShortcutNameComparator(mLabelCache));
2864 if (DEBUG_LOADERS) {
2865 Log.d(TAG, "sort took "
2866 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2867 }
Joe Onorato36115782010-06-17 13:28:48 -04002868
Kenny Guyed131872014-04-30 03:02:21 +01002869 // Create the ApplicationInfos
2870 for (int i = 0; i < apps.size(); i++) {
2871 LauncherActivityInfoCompat app = apps.get(i);
2872 // This builds the icon bitmaps.
2873 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2874 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002875
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002876 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002877 // Add shortcuts for packages which were installed while launcher was dead.
2878 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2879 + mUserManager.getSerialNumberForUser(user);
2880 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2881 HashSet<String> newPackageSet = new HashSet<String>();
2882
2883 for (LauncherActivityInfoCompat info : apps) {
2884 String packageName = info.getComponentName().getPackageName();
2885 if (!packagesAdded.contains(packageName)
2886 && !newPackageSet.contains(packageName)) {
2887 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2888 }
2889 newPackageSet.add(packageName);
2890 }
2891
2892 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2893 }
Winson Chung64359a52013-07-08 17:17:08 -07002894 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002895 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002896 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2897 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002898
2899 // Post callback on main thread
2900 mHandler.post(new Runnable() {
2901 public void run() {
2902 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002903 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002904 if (callbacks != null) {
2905 callbacks.bindAllApplications(added);
2906 if (DEBUG_LOADERS) {
2907 Log.d(TAG, "bound " + added.size() + " apps in "
2908 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2909 }
2910 } else {
2911 Log.i(TAG, "not binding apps: no Launcher activity");
2912 }
2913 }
2914 });
2915
Joe Onorato36115782010-06-17 13:28:48 -04002916 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002917 Log.d(TAG, "Icons processed in "
2918 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002919 }
2920 }
2921
2922 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002923 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002924 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2925 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2926 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2927 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2928 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2929 }
Joe Onorato36115782010-06-17 13:28:48 -04002930 }
2931 }
2932
2933 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002934 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002935 }
2936
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002937 private class AppsAvailabilityCheck extends BroadcastReceiver {
2938
2939 @Override
2940 public void onReceive(Context context, Intent intent) {
2941 synchronized (sBgLock) {
2942 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2943 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002944 final PackageManager manager = context.getPackageManager();
2945 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2946 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002947 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2948 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002949 packagesRemoved.clear();
2950 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002951 for (String pkg : entry.getValue()) {
2952 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002953 boolean packageOnSdcard = launcherApps.isAppEnabled(
2954 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2955 if (packageOnSdcard) {
2956 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2957 packagesUnavailable.add(pkg);
2958 } else {
2959 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2960 packagesRemoved.add(pkg);
2961 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002962 }
2963 }
2964 if (!packagesRemoved.isEmpty()) {
2965 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2966 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2967 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002968 if (!packagesUnavailable.isEmpty()) {
2969 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2970 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2971 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002972 }
Sunny Goyal34942622014-08-29 17:20:55 -07002973 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002974 }
2975 }
2976 }
2977
Joe Onorato36115782010-06-17 13:28:48 -04002978 private class PackageUpdatedTask implements Runnable {
2979 int mOp;
2980 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002981 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002982
2983 public static final int OP_NONE = 0;
2984 public static final int OP_ADD = 1;
2985 public static final int OP_UPDATE = 2;
2986 public static final int OP_REMOVE = 3; // uninstlled
2987 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2988
2989
Kenny Guyed131872014-04-30 03:02:21 +01002990 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002991 mOp = op;
2992 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002993 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002994 }
2995
2996 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002997 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002998
2999 final String[] packages = mPackages;
3000 final int N = packages.length;
3001 switch (mOp) {
3002 case OP_ADD:
3003 for (int i=0; i<N; i++) {
3004 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003005 mIconCache.remove(packages[i], mUser);
3006 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003007 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003008
3009 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003010 if (ADD_MANAGED_PROFILE_SHORTCUTS
3011 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003012 SharedPreferences prefs = context.getSharedPreferences(
3013 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3014 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3015 + mUserManager.getSerialNumberForUser(mUser);
3016 Set<String> shortcutSet = new HashSet<String>(
3017 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3018
3019 for (int i=0; i<N; i++) {
3020 if (!shortcutSet.contains(packages[i])) {
3021 shortcutSet.add(packages[i]);
3022 List<LauncherActivityInfoCompat> activities =
3023 mLauncherApps.getActivityList(packages[i], mUser);
3024 if (activities != null && !activities.isEmpty()) {
3025 InstallShortcutReceiver.queueInstallShortcut(
3026 activities.get(0), context);
3027 }
3028 }
3029 }
3030
3031 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3032 }
Joe Onorato36115782010-06-17 13:28:48 -04003033 break;
3034 case OP_UPDATE:
3035 for (int i=0; i<N; i++) {
3036 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003037 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003038 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003039 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003040 }
3041 break;
3042 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003043 // Remove the packageName for the set of auto-installed shortcuts. This
3044 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003045 if (ADD_MANAGED_PROFILE_SHORTCUTS
3046 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003047 SharedPreferences prefs = context.getSharedPreferences(
3048 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3049 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3050 + mUserManager.getSerialNumberForUser(mUser);
3051 HashSet<String> shortcutSet = new HashSet<String>(
3052 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3053 shortcutSet.removeAll(Arrays.asList(mPackages));
3054 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3055 }
3056 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003057 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003058 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003059 for (int i=0; i<N; i++) {
3060 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003061 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003062 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003063 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003064 }
3065 break;
3066 }
3067
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003068 ArrayList<AppInfo> added = null;
3069 ArrayList<AppInfo> modified = null;
3070 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003071
Adam Cohen487f7dd2012-06-28 18:12:10 -07003072 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003073 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003074 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003075 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003076 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003077 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003078 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003079 }
Winson Chung5d55f332012-07-16 20:45:03 -07003080 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003081 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003082 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003083 }
3084
Sunny Goyale0f58d72014-11-10 18:05:31 -08003085 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003086 if (callbacks == null) {
3087 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3088 return;
3089 }
3090
Sunny Goyal4390ace2014-10-13 11:33:11 -07003091 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3092 new HashMap<ComponentName, AppInfo>();
3093
Joe Onorato36115782010-06-17 13:28:48 -04003094 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003095 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003096 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003097 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003098 addAndBindAddedWorkspaceApps(context, addedInfos);
3099 } else {
3100 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003101 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003102 for (AppInfo ai : added) {
3103 addedOrUpdatedApps.put(ai.componentName, ai);
3104 }
Joe Onorato36115782010-06-17 13:28:48 -04003105 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003106
Joe Onorato36115782010-06-17 13:28:48 -04003107 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003108 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003109 for (AppInfo ai : modified) {
3110 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003111 }
3112
Joe Onorato36115782010-06-17 13:28:48 -04003113 mHandler.post(new Runnable() {
3114 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003115 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003116 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003117 callbacks.bindAppsUpdated(modifiedFinal);
3118 }
3119 }
3120 });
3121 }
Winson Chung83892cc2013-05-01 16:53:33 -07003122
Sunny Goyal4390ace2014-10-13 11:33:11 -07003123 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003124 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003125 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3126 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3127 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3128
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003129 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003130 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003131 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003132 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3133 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003134 boolean infoUpdated = false;
3135 boolean shortcutUpdated = false;
3136
3137 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003138 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003139 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003140 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3141 si.iconResource.resourceName, mIconCache, context);
3142 if (icon != null) {
3143 si.setIcon(icon);
3144 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003145 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003146 }
3147 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003148
3149 ComponentName cn = si.getTargetComponent();
3150 if (cn != null && packageSet.contains(cn.getPackageName())) {
3151 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3152
3153 if (si.isPromise()) {
3154 mIconCache.deletePreloadedIcon(cn, mUser);
3155 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3156 // Auto install icon
3157 PackageManager pm = context.getPackageManager();
3158 ResolveInfo matched = pm.resolveActivity(
3159 new Intent(Intent.ACTION_MAIN)
3160 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3161 PackageManager.MATCH_DEFAULT_ONLY);
3162 if (matched == null) {
3163 // Try to find the best match activity.
3164 Intent intent = pm.getLaunchIntentForPackage(
3165 cn.getPackageName());
3166 if (intent != null) {
3167 cn = intent.getComponent();
3168 appInfo = addedOrUpdatedApps.get(cn);
3169 }
3170
3171 if ((intent == null) || (appInfo == null)) {
3172 removedShortcuts.add(si);
3173 continue;
3174 }
3175 si.promisedIntent = intent;
3176 }
3177 }
3178
3179 // Restore the shortcut.
3180 si.intent = si.promisedIntent;
3181 si.promisedIntent = null;
3182 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3183 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3184 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3185
3186 infoUpdated = true;
3187 si.updateIcon(mIconCache);
3188 }
3189
3190 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3191 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3192 si.updateIcon(mIconCache);
3193 si.title = appInfo.title.toString();
3194 si.contentDescription = appInfo.contentDescription;
3195 infoUpdated = true;
3196 }
3197
3198 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3199 // Since package was just updated, the target must be available now.
3200 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3201 shortcutUpdated = true;
3202 }
3203 }
3204
3205 if (infoUpdated || shortcutUpdated) {
3206 updatedShortcuts.add(si);
3207 }
3208 if (infoUpdated) {
3209 updateItemInDatabase(context, si);
3210 }
3211 } else if (info instanceof LauncherAppWidgetInfo) {
3212 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3213 if (mUser.equals(widgetInfo.user)
3214 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3215 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3216 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3217 widgets.add(widgetInfo);
3218 updateItemInDatabase(context, widgetInfo);
3219 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003220 }
3221 }
3222 }
3223
Sunny Goyal4390ace2014-10-13 11:33:11 -07003224 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3225 mHandler.post(new Runnable() {
3226
3227 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003228 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003229 if (callbacks == cb && cb != null) {
3230 callbacks.bindShortcutsChanged(
3231 updatedShortcuts, removedShortcuts, mUser);
3232 }
3233 }
3234 });
3235 if (!removedShortcuts.isEmpty()) {
3236 deleteItemsFromDatabase(context, removedShortcuts);
3237 }
3238 }
3239 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003240 mHandler.post(new Runnable() {
3241 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003242 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003243 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003244 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003245 }
3246 }
3247 });
3248 }
3249 }
3250
Winson Chungdf95eb12013-10-16 14:57:07 -07003251 final ArrayList<String> removedPackageNames =
3252 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003253 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003254 // Mark all packages in the broadcast to be removed
3255 removedPackageNames.addAll(Arrays.asList(packages));
3256 } else if (mOp == OP_UPDATE) {
3257 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003258 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003259 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003260 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003261 }
3262 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003263 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003264
Winson Chungdf95eb12013-10-16 14:57:07 -07003265 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003266 final int removeReason;
3267 if (mOp == OP_UNAVAILABLE) {
3268 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3269 } else {
3270 // Remove all the components associated with this package
3271 for (String pn : removedPackageNames) {
3272 deletePackageFromDatabase(context, pn, mUser);
3273 }
3274 // Remove all the specific components
3275 for (AppInfo a : removedApps) {
3276 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3277 deleteItemsFromDatabase(context, infos);
3278 }
3279 removeReason = 0;
3280 }
3281
Winson Chungdf95eb12013-10-16 14:57:07 -07003282 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003283 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003284 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003285 mHandler.post(new Runnable() {
3286 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003287 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003288 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003289 callbacks.bindComponentsRemoved(
3290 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003291 }
3292 }
3293 });
Joe Onoratobe386092009-11-17 17:32:16 -08003294 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003295
Michael Jurkac402cd92013-05-20 15:49:32 +02003296 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003297 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003298 mHandler.post(new Runnable() {
3299 @Override
3300 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003301 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003302 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003303 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003304 }
3305 }
3306 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003307
3308 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003309 mHandler.post(new Runnable() {
3310 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003311 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003312 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003313 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003314 }
3315 }
3316 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003317 }
3318 }
3319
Adam Cohen59400422014-03-05 18:07:04 -08003320 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3321 synchronized (sBgLock) {
3322 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3323 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3324 }
3325 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3326 List<AppWidgetProviderInfo> widgets =
3327 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3328 LauncherAppWidgetProviderInfo info;
3329 for (AppWidgetProviderInfo pInfo : widgets) {
3330 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3331 sBgWidgetProviders.put(info.provider, info);
3332 }
3333
3334 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3335 for (CustomAppWidget widget : customWidgets) {
3336 info = new LauncherAppWidgetProviderInfo(context, widget);
3337 sBgWidgetProviders.put(info.provider, info);
3338 }
3339 sWidgetProvidersDirty = false;
3340 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3341 }
3342 }
3343
3344 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3345 synchronized (sBgLock) {
3346 if (sBgWidgetProviders == null) {
3347 getWidgetProviders(ctx);
3348 }
3349 return sBgWidgetProviders.get(name);
3350 }
3351 }
3352
Michael Jurkac402cd92013-05-20 15:49:32 +02003353 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3354 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3355 PackageManager packageManager = context.getPackageManager();
3356 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003357 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003358 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3359 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003360 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003361 return widgetsAndShortcuts;
3362 }
3363
Kenny Guyed131872014-04-30 03:02:21 +01003364 private static boolean isPackageDisabled(Context context, String packageName,
3365 UserHandleCompat user) {
3366 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3367 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003368 }
Adam Cohen556f6132014-01-15 15:18:08 -08003369
Kenny Guyed131872014-04-30 03:02:21 +01003370 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3371 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003372 if (cn == null) {
3373 return false;
3374 }
Kenny Guyed131872014-04-30 03:02:21 +01003375 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3376 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003377 return false;
3378 }
Kenny Guyed131872014-04-30 03:02:21 +01003379 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003380 }
3381
Adam Cohena28b78e2014-05-20 17:03:04 -07003382 public static boolean isValidPackage(Context context, String packageName,
3383 UserHandleCompat user) {
3384 if (packageName == null) {
3385 return false;
3386 }
3387 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3388 return launcherApps.isPackageEnabledForProfile(packageName, user);
3389 }
3390
Joe Onorato9c1289c2009-08-17 11:03:03 -04003391 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003392 * Make an ShortcutInfo object for a restored application or shortcut item that points
3393 * to a package that is not yet installed on the system.
3394 */
Sunny Goyal34942622014-08-29 17:20:55 -07003395 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3396 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003397 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003398 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003399 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3400
3401 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3402 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3403 if (!TextUtils.isEmpty(title)) {
3404 info.title = title;
3405 }
3406 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3407 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3408 if (TextUtils.isEmpty(info.title)) {
3409 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3410 }
3411 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3412 } else {
3413 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3414 }
3415
Kenny Guyc2bd8102014-06-30 12:30:31 +01003416 info.contentDescription = mUserManager.getBadgedLabelForUser(
3417 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003418 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003419 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003420 return info;
3421 }
3422
3423 /**
3424 * Make an Intent object for a restored application or shortcut item that points
3425 * to the market page for the item.
3426 */
3427 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3428 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003429 return getMarketIntent(componentName.getPackageName());
3430 }
3431
3432 static Intent getMarketIntent(String packageName) {
3433 return new Intent(Intent.ACTION_VIEW)
3434 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003435 .scheme("market")
3436 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003437 .appendQueryParameter("id", packageName)
3438 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003439 }
3440
3441 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003442 * This is called from the code that adds shortcuts from the intent receiver. This
3443 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003444 */
Kenny Guyed131872014-04-30 03:02:21 +01003445 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3446 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003447 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003448 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003449
Joe Onorato56d82912010-03-07 14:32:10 -05003450 /**
3451 * Make an ShortcutInfo object for a shortcut that is an application.
3452 *
3453 * If c is not null, then it will be used to fill in missing data like the title and icon.
3454 */
Kenny Guyed131872014-04-30 03:02:21 +01003455 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3456 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003457 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003458 if (user == null) {
3459 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003460 return null;
3461 }
3462
Kenny Guyed131872014-04-30 03:02:21 +01003463 ComponentName componentName = intent.getComponent();
3464 if (componentName == null) {
3465 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3466 return null;
3467 }
3468
3469 Intent newIntent = new Intent(intent.getAction(), null);
3470 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3471 newIntent.setComponent(componentName);
3472 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003473 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003474 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3475 return null;
3476 }
3477
3478 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003479
Joe Onorato56d82912010-03-07 14:32:10 -05003480 // the resource -- This may implicitly give us back the fallback icon,
3481 // but don't worry about that. All we're doing with usingFallbackIcon is
3482 // to avoid saving lots of copies of that in the database, and most apps
3483 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003484 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003485
Joe Onorato56d82912010-03-07 14:32:10 -05003486 // the db
3487 if (icon == null) {
3488 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003489 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003490 }
3491 }
3492 // the fallback icon
3493 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003494 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003495 info.usingFallbackIcon = true;
3496 }
3497 info.setIcon(icon);
3498
Kenny Guyed131872014-04-30 03:02:21 +01003499 // From the cache.
3500 if (labelCache != null) {
3501 info.title = labelCache.get(componentName);
3502 }
3503
Joe Onorato56d82912010-03-07 14:32:10 -05003504 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003505 if (info.title == null && lai != null) {
3506 info.title = lai.getLabel();
3507 if (labelCache != null) {
3508 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003509 }
Joe Onorato56d82912010-03-07 14:32:10 -05003510 }
3511 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003512 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003513 if (c != null) {
3514 info.title = c.getString(titleIndex);
3515 }
3516 }
3517 // fall back to the class name of the activity
3518 if (info.title == null) {
3519 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003520 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003521 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003522 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003523 info.contentDescription = mUserManager.getBadgedLabelForUser(
3524 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003525 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003526 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003527
Winson Chung64359a52013-07-08 17:17:08 -07003528 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3529 ItemInfoFilter f) {
3530 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3531 for (ItemInfo i : infos) {
3532 if (i instanceof ShortcutInfo) {
3533 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003534 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003535 if (cn != null && f.filterItem(null, info, cn)) {
3536 filtered.add(info);
3537 }
3538 } else if (i instanceof FolderInfo) {
3539 FolderInfo info = (FolderInfo) i;
3540 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003541 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003542 if (cn != null && f.filterItem(info, s, cn)) {
3543 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003544 }
3545 }
Winson Chung64359a52013-07-08 17:17:08 -07003546 } else if (i instanceof LauncherAppWidgetInfo) {
3547 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3548 ComponentName cn = info.providerName;
3549 if (cn != null && f.filterItem(null, info, cn)) {
3550 filtered.add(info);
3551 }
Winson Chung8a435102012-08-30 17:16:53 -07003552 }
3553 }
Winson Chung64359a52013-07-08 17:17:08 -07003554 return new ArrayList<ItemInfo>(filtered);
3555 }
3556
Kenny Guyed131872014-04-30 03:02:21 +01003557 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3558 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003559 ItemInfoFilter filter = new ItemInfoFilter() {
3560 @Override
3561 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003562 if (info.user == null) {
3563 return cn.equals(cname);
3564 } else {
3565 return cn.equals(cname) && info.user.equals(user);
3566 }
Winson Chung64359a52013-07-08 17:17:08 -07003567 }
3568 };
3569 return filterItemInfos(sBgItemsIdMap.values(), filter);
3570 }
3571
Sunny Goyal1a745e82014-10-02 15:58:31 -07003572 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003573 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003574 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003575 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003576 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3577 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003578
Joe Onorato56d82912010-03-07 14:32:10 -05003579 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003580 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003581 // Non-app shortcuts are only supported for current user.
3582 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003583 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003584
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003585 // TODO: If there's an explicit component and we can't install that, delete it.
3586
Joe Onorato56d82912010-03-07 14:32:10 -05003587 info.title = c.getString(titleIndex);
3588
Joe Onorato9c1289c2009-08-17 11:03:03 -04003589 int iconType = c.getInt(iconTypeIndex);
3590 switch (iconType) {
3591 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3592 String packageName = c.getString(iconPackageIndex);
3593 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003594 info.customIcon = false;
3595 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003596 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003597 // the db
3598 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003599 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003600 }
3601 // the fallback icon
3602 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003603 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003604 info.usingFallbackIcon = true;
3605 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003606 break;
3607 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003608 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003609 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003610 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003611 info.customIcon = false;
3612 info.usingFallbackIcon = true;
3613 } else {
3614 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003615 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003616 break;
3617 default:
Kenny Guyed131872014-04-30 03:02:21 +01003618 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003619 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003620 info.customIcon = false;
3621 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003622 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003623 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003624 return info;
3625 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003626
Michael Jurka931dc972011-08-05 15:08:15 -07003627 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003628 @SuppressWarnings("all") // suppress dead code warning
3629 final boolean debug = false;
3630 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003631 Log.d(TAG, "getIconFromCursor app="
3632 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3633 }
3634 byte[] data = c.getBlob(iconIndex);
3635 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003636 return Utilities.createIconBitmap(
3637 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003638 } catch (Exception e) {
3639 return null;
3640 }
3641 }
3642
Sunny Goyal2350bc92014-10-14 16:42:54 -07003643 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003644 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3645 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3646 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3647
Adam Cohend9198822011-11-22 16:42:47 -08003648 if (intent == null) {
3649 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3650 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3651 return null;
3652 }
3653
Joe Onorato0589f0f2010-02-08 13:44:00 -08003654 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003655 boolean customIcon = false;
3656 ShortcutIconResource iconResource = null;
3657
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003658 if (bitmap instanceof Bitmap) {
3659 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003660 customIcon = true;
3661 } else {
3662 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003663 if (extra instanceof ShortcutIconResource) {
3664 iconResource = (ShortcutIconResource) extra;
3665 icon = Utilities.createIconBitmap(iconResource.packageName,
3666 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003667 }
3668 }
3669
Michael Jurkac9d95c52011-08-29 14:03:34 -07003670 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003671
Kenny Guyed131872014-04-30 03:02:21 +01003672 // Only support intents for current user for now. Intents sent from other
3673 // users wouldn't get here without intent forwarding anyway.
3674 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003675 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003676 icon = mIconCache.getDefaultIcon(info.user);
3677 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003678 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003679 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003680
Joe Onorato0589f0f2010-02-08 13:44:00 -08003681 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003682 info.contentDescription = mUserManager.getBadgedLabelForUser(
3683 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003684 info.intent = intent;
3685 info.customIcon = customIcon;
3686 info.iconResource = iconResource;
3687
3688 return info;
3689 }
3690
Winson Chungaac01e12011-08-17 10:37:13 -07003691 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3692 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003693 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003694 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003695 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003696 }
Joe Onorato56d82912010-03-07 14:32:10 -05003697 // If this icon doesn't have a custom icon, check to see
3698 // what's stored in the DB, and if it doesn't match what
3699 // we're going to show, store what we are going to show back
3700 // into the DB. We do this so when we're loading, if the
3701 // package manager can't find an icon (for example because
3702 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003703 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003704 cache.put(info, c.getBlob(iconIndex));
3705 return true;
3706 }
3707 return false;
3708 }
3709 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3710 boolean needSave = false;
3711 try {
3712 if (data != null) {
3713 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3714 Bitmap loaded = info.getIcon(mIconCache);
3715 needSave = !saved.sameAs(loaded);
3716 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003717 needSave = true;
3718 }
Winson Chungaac01e12011-08-17 10:37:13 -07003719 } catch (Exception e) {
3720 needSave = true;
3721 }
3722 if (needSave) {
3723 Log.d(TAG, "going to save icon bitmap for info=" + info);
3724 // This is slower than is ideal, but this only happens once
3725 // or when the app is updated with a new icon.
3726 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003727 }
3728 }
3729
Joe Onorato9c1289c2009-08-17 11:03:03 -04003730 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003731 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003732 * or make a new one.
3733 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003734 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003735 // See if a placeholder was created for us already
3736 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003737 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003738 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003739 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003740 folders.put(id, folderInfo);
3741 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003742 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003743 }
3744
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003745 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003746 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003747 return new Comparator<AppInfo>() {
3748 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003749 if (a.user.equals(b.user)) {
3750 int result = collator.compare(a.title.toString().trim(),
3751 b.title.toString().trim());
3752 if (result == 0) {
3753 result = a.componentName.compareTo(b.componentName);
3754 }
3755 return result;
3756 } else {
3757 // TODO Need to figure out rules for sorting
3758 // profiles, this puts work second.
3759 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003760 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003761 }
Winson Chung11904872012-09-17 16:58:46 -07003762 };
3763 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003764 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3765 = new Comparator<AppInfo>() {
3766 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003767 if (a.firstInstallTime < b.firstInstallTime) return 1;
3768 if (a.firstInstallTime > b.firstInstallTime) return -1;
3769 return 0;
3770 }
3771 };
Winson Chung5308f242011-08-18 12:12:41 -07003772 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3773 if (info.activityInfo != null) {
3774 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3775 } else {
3776 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3777 }
3778 }
Kenny Guyed131872014-04-30 03:02:21 +01003779 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003780 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003781 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003782 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003783 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003784 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003785 }
Kenny Guyed131872014-04-30 03:02:21 +01003786 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003787 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003788 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003789 }
Kenny Guyed131872014-04-30 03:02:21 +01003790 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003791 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003792 ComponentName keyA = a.getComponentName();
3793 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003794 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003795 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003796 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003797 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003798
Winson Chung5308f242011-08-18 12:12:41 -07003799 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003800 }
Winson Chung5308f242011-08-18 12:12:41 -07003801 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003802 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003803 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003804 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003805
Winson Chung5308f242011-08-18 12:12:41 -07003806 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003807 }
Winson Chung11904872012-09-17 16:58:46 -07003808 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003809 }
3810 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003811 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003812 private final AppWidgetManagerCompat mManager;
3813 private final PackageManager mPackageManager;
3814 private final HashMap<Object, String> mLabelCache;
3815 private final Collator mCollator;
3816
3817 WidgetAndShortcutNameComparator(Context context) {
3818 mManager = AppWidgetManagerCompat.getInstance(context);
3819 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003820 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003821 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003822 }
3823 public final int compare(Object a, Object b) {
3824 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003825 if (mLabelCache.containsKey(a)) {
3826 labelA = mLabelCache.get(a);
3827 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003828 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3829 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003830 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003831 mLabelCache.put(a, labelA);
3832 }
3833 if (mLabelCache.containsKey(b)) {
3834 labelB = mLabelCache.get(b);
3835 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003836 labelB = (b instanceof LauncherAppWidgetProviderInfo)
3837 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003838 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003839 mLabelCache.put(b, labelB);
3840 }
Winson Chung11904872012-09-17 16:58:46 -07003841 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003842 }
3843 };
Joe Onoratobe386092009-11-17 17:32:16 -08003844
Sunny Goyal651077b2014-06-30 14:15:31 -07003845 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3846 return (provider != null) && (provider.provider != null)
3847 && (provider.provider.getPackageName() != null);
3848 }
3849
Joe Onoratobe386092009-11-17 17:32:16 -08003850 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003851 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003852 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3853 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3854 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3855 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003856 if (mLoaderTask != null) {
3857 mLoaderTask.dumpState();
3858 } else {
3859 Log.d(TAG, "mLoaderTask=null");
3860 }
Joe Onoratobe386092009-11-17 17:32:16 -08003861 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003862
3863 public Callbacks getCallback() {
3864 return mCallbacks != null ? mCallbacks.get() : null;
3865 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003866}