blob: 78790688ad4c48428db84d3e6d286007eac6ed7d [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;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001958 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001959 if (user == null) {
1960 // User has been deleted remove the item.
1961 itemsToRemove.add(id);
1962 continue;
1963 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001964 try {
1965 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001966 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001967 if (cn != null && cn.getPackageName() != null) {
1968 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1969 cn.getPackageName(), user);
1970 boolean validComponent = validPkg &&
1971 launcherApps.isActivityEnabledForProfile(cn, user);
1972
1973 if (validComponent) {
1974 if (restored) {
1975 // no special handling necessary for this item
1976 restoredRows.add(id);
1977 restored = false;
1978 }
1979 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001980 intent = null;
1981 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1982 // We allow auto install apps to have their intent
1983 // updated after an install.
1984 intent = manager.getLaunchIntentForPackage(
1985 cn.getPackageName());
1986 if (intent != null) {
1987 ContentValues values = new ContentValues();
1988 values.put(LauncherSettings.Favorites.INTENT,
1989 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001990 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001991 }
1992 }
1993
1994 if (intent == null) {
1995 // The app is installed but the component is no
1996 // longer available.
1997 Launcher.addDumpLog(TAG,
1998 "Invalid component removed: " + cn, true);
1999 itemsToRemove.add(id);
2000 continue;
2001 } else {
2002 // no special handling necessary for this item
2003 restoredRows.add(id);
2004 restored = false;
2005 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002006 } else if (restored) {
2007 // Package is not yet available but might be
2008 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002009 Launcher.addDumpLog(TAG,
2010 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002011
2012 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2013 // Restore has started once.
2014 } else if (installingPkgs.contains(cn.getPackageName())) {
2015 // App restore has started. Update the flag
2016 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2017 ContentValues values = new ContentValues();
2018 values.put(LauncherSettings.Favorites.RESTORED,
2019 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002020 updateItem(id, values);
2021 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
2022 // This is a common app. Try to replace this.
2023 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
2024 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
2025 if (parser.findDefaultApp()) {
2026 // Default app found. Replace it.
2027 intent = parser.parsedIntent;
2028 cn = intent.getComponent();
2029 ContentValues values = parser.parsedValues;
2030 values.put(LauncherSettings.Favorites.RESTORED, 0);
2031 updateItem(id, values);
2032 restored = false;
2033 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07002034
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002035 } else if (REMOVE_UNRESTORED_ICONS) {
2036 Launcher.addDumpLog(TAG,
2037 "Unrestored package removed: " + cn, true);
2038 itemsToRemove.add(id);
2039 continue;
2040 }
Sunny Goyal94485362014-09-18 16:13:58 -07002041 } else if (REMOVE_UNRESTORED_ICONS) {
2042 Launcher.addDumpLog(TAG,
2043 "Unrestored package removed: " + cn, true);
2044 itemsToRemove.add(id);
2045 continue;
2046 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002047 } else if (launcherApps.isAppEnabled(
2048 manager, cn.getPackageName(),
2049 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2050 // Package is present but not available.
2051 allowMissingTarget = true;
2052 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2053 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002054 // SdCard is not ready yet. Package might get available,
2055 // once it is ready.
2056 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2057 + " (check again later)", true);
2058 HashSet<String> pkgs = sPendingPackages.get(user);
2059 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002060 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002061 sPendingPackages.put(user, pkgs);
2062 }
2063 pkgs.add(cn.getPackageName());
2064 allowMissingTarget = true;
2065 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002066
2067 } else {
2068 // Do not wait for external media load anymore.
2069 // Log the invalid package, and remove it
2070 Launcher.addDumpLog(TAG,
2071 "Invalid package removed: " + cn, true);
2072 itemsToRemove.add(id);
2073 continue;
Winson Chungee055712013-07-30 14:46:24 -07002074 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002075 } else if (cn == null) {
2076 // For shortcuts with no component, keep them as they are
2077 restoredRows.add(id);
2078 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002079 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002080 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002081 Launcher.addDumpLog(TAG,
2082 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 continue;
2084 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002085
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002086 if (itemReplaced) {
2087 if (user.equals(UserHandleCompat.myUserHandle())) {
2088 info = getShortcutInfo(manager, intent, user, context, null,
2089 iconIndex, titleIndex, mLabelCache, false);
2090 } else {
2091 // Don't replace items for other profiles.
2092 itemsToRemove.add(id);
2093 continue;
2094 }
2095 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002096 if (user.equals(UserHandleCompat.myUserHandle())) {
2097 Launcher.addDumpLog(TAG,
2098 "constructing info for partially restored package",
2099 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002100 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002101 intent = getRestoredItemIntent(c, context, intent);
2102 } else {
2103 // Don't restore items for other profiles.
2104 itemsToRemove.add(id);
2105 continue;
2106 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002107 } else if (itemType ==
2108 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002109 info = getShortcutInfo(manager, intent, user, context, c,
2110 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 } else {
2112 info = getShortcutInfo(c, context, iconTypeIndex,
2113 iconPackageIndex, iconResourceIndex, iconIndex,
2114 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002115
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 // App shortcuts that used to be automatically added to Launcher
2117 // didn't always have the correct intent flags set, so do that
2118 // here
2119 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002120 intent.getCategories() != null &&
2121 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002122 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002123 intent.addFlags(
2124 Intent.FLAG_ACTIVITY_NEW_TASK |
2125 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2126 }
Michael Jurka96879562012-03-22 05:54:33 -07002127 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002128
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002130 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002132 container = c.getInt(containerIndex);
2133 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002134 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002135 info.cellX = c.getInt(cellXIndex);
2136 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002137 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002138 info.spanX = 1;
2139 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002140 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002141 info.isDisabled = disabledState;
2142 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2143 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2144 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002145
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002147 if (!checkItemPlacement(occupied, info)) {
2148 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002149 break;
2150 }
2151
2152 switch (container) {
2153 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2154 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2155 sBgWorkspaceItems.add(info);
2156 break;
2157 default:
2158 // Item is in a user folder
2159 FolderInfo folderInfo =
2160 findOrMakeFolder(sBgFolders, container);
2161 folderInfo.add(info);
2162 break;
2163 }
2164 sBgItemsIdMap.put(info.id, info);
2165
2166 // now that we've loaded everthing re-save it with the
2167 // icon in case it disappears somehow.
2168 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002169 } else {
2170 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002171 }
2172 break;
2173
2174 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2175 id = c.getLong(idIndex);
2176 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2177
2178 folderInfo.title = c.getString(titleIndex);
2179 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002180 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002181 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002182 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002183 folderInfo.cellX = c.getInt(cellXIndex);
2184 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002185 folderInfo.spanX = 1;
2186 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002187
Daniel Sandler8802e962010-05-26 16:28:16 -04002188 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002189 if (!checkItemPlacement(occupied, folderInfo)) {
2190 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002191 break;
2192 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002193
Joe Onorato9c1289c2009-08-17 11:03:03 -04002194 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002195 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2196 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2197 sBgWorkspaceItems.add(folderInfo);
2198 break;
Joe Onorato36115782010-06-17 13:28:48 -04002199 }
Joe Onorato17a89222011-02-08 17:26:11 -08002200
Chris Wrenf4d08112014-01-16 18:13:56 -05002201 if (restored) {
2202 // no special handling required for restored folders
2203 restoredRows.add(id);
2204 }
2205
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002206 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2207 sBgFolders.put(folderInfo.id, folderInfo);
2208 break;
2209
2210 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002211 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002212 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002213 boolean customWidget = itemType ==
2214 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2215
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002216 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002217 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002218 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002219 final ComponentName component =
2220 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002221
Sunny Goyal651077b2014-06-30 14:15:31 -07002222 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002223 final boolean isIdValid = (restoreStatus &
2224 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002225
Sunny Goyalff572272014-07-23 13:58:07 -07002226 final boolean wasProviderReady = (restoreStatus &
2227 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002228
Adam Cohen59400422014-03-05 18:07:04 -08002229 final LauncherAppWidgetProviderInfo provider =
2230 LauncherModel.getProviderInfo(context,
2231 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002232
2233 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002234 if (!isSafeMode && !customWidget &&
2235 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002236 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002237 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002238
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002239 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002240 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002241 itemsToRemove.add(id);
2242 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002243 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002244 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2245 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002246
2247 if (!customWidget) {
2248 int[] minSpan =
2249 Launcher.getMinSpanForWidget(context, provider);
2250 appWidgetInfo.minSpanX = minSpan[0];
2251 appWidgetInfo.minSpanY = minSpan[1];
2252 }
Sunny Goyalff572272014-07-23 13:58:07 -07002253
2254 int status = restoreStatus;
2255 if (!wasProviderReady) {
2256 // If provider was not previously ready, update the
2257 // status and UI flag.
2258
2259 // Id would be valid only if the widget restore broadcast was received.
2260 if (isIdValid) {
2261 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2262 } else {
2263 status &= ~LauncherAppWidgetInfo
2264 .FLAG_PROVIDER_NOT_READY;
2265 }
2266 }
2267 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002268 } else {
2269 Log.v(TAG, "Widget restore pending id=" + id
2270 + " appWidgetId=" + appWidgetId
2271 + " status =" + restoreStatus);
2272 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002273 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002274 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002275
2276 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2277 // Restore has started once.
2278 } else if (installingPkgs.contains(component.getPackageName())) {
2279 // App restore has started. Update the flag
2280 appWidgetInfo.restoreStatus |=
2281 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002282 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002283 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002284 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002285 itemsToRemove.add(id);
2286 continue;
2287 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002288 }
Sunny Goyalff572272014-07-23 13:58:07 -07002289
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002290 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002291 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002292 appWidgetInfo.cellX = c.getInt(cellXIndex);
2293 appWidgetInfo.cellY = c.getInt(cellYIndex);
2294 appWidgetInfo.spanX = c.getInt(spanXIndex);
2295 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002296
Adam Cohen59400422014-03-05 18:07:04 -08002297 if (!customWidget) {
2298 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2299 appWidgetInfo.minSpanX = minSpan[0];
2300 appWidgetInfo.minSpanY = minSpan[1];
2301 }
2302
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002303 container = c.getInt(containerIndex);
2304 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2305 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2306 Log.e(TAG, "Widget found where container != " +
2307 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2308 continue;
2309 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002310
Adam Cohene25af792013-06-06 23:08:25 -07002311 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002313 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2314 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002315 break;
2316 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002317
Adam Cohen59400422014-03-05 18:07:04 -08002318 if (!customWidget) {
2319 String providerName =
2320 appWidgetInfo.providerName.flattenToString();
2321 if (!providerName.equals(savedProvider) ||
2322 (appWidgetInfo.restoreStatus != restoreStatus)) {
2323 ContentValues values = new ContentValues();
2324 values.put(
2325 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2326 providerName);
2327 values.put(LauncherSettings.Favorites.RESTORED,
2328 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002329 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002330 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002331 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002332 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2333 sBgAppWidgets.add(appWidgetInfo);
2334 }
Joe Onorato36115782010-06-17 13:28:48 -04002335 break;
2336 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002337 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002338 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002339 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002340 }
2341 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002342 if (c != null) {
2343 c.close();
2344 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002345 }
2346
Winson Chungba9c37f2013-08-30 14:11:37 -07002347 // Break early if we've stopped loading
2348 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002349 clearSBgDataStructures();
2350 return false;
2351 }
2352
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002353 if (itemsToRemove.size() > 0) {
2354 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002355 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002356 // Remove dead items
2357 for (long id : itemsToRemove) {
2358 if (DEBUG_LOADERS) {
2359 Log.d(TAG, "Removed id = " + id);
2360 }
2361 // Don't notify content observers
2362 try {
2363 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2364 null, null);
2365 } catch (RemoteException e) {
2366 Log.w(TAG, "Could not remove id = " + id);
2367 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002368 }
2369 }
2370
Chris Wrenf4d08112014-01-16 18:13:56 -05002371 if (restoredRows.size() > 0) {
2372 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002373 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002374 // Update restored items that no longer require special handling
2375 try {
2376 StringBuilder selectionBuilder = new StringBuilder();
2377 selectionBuilder.append(LauncherSettings.Favorites._ID);
2378 selectionBuilder.append(" IN (");
2379 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2380 selectionBuilder.append(")");
2381 ContentValues values = new ContentValues();
2382 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002383 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002384 values, selectionBuilder.toString(), null);
2385 } catch (RemoteException e) {
2386 Log.w(TAG, "Could not update restored rows");
2387 }
2388 }
2389
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002390 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2391 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002392 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002393 null, sWorker);
2394 }
2395
Winson Chungc763c4e2013-07-19 13:49:06 -07002396 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002397 long maxScreenId = 0;
2398 // If we're importing we use the old screen order.
2399 for (ItemInfo item: sBgItemsIdMap.values()) {
2400 long screenId = item.screenId;
2401 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2402 !sBgWorkspaceScreens.contains(screenId)) {
2403 sBgWorkspaceScreens.add(screenId);
2404 if (screenId > maxScreenId) {
2405 maxScreenId = screenId;
2406 }
2407 }
2408 }
2409 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002410 // Log to disk
2411 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2412 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2413 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002414
Michael Jurka414300a2013-08-27 15:42:35 +02002415 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002416 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002417
2418 // Update the max item id after we load an old db
2419 long maxItemId = 0;
2420 // If we're importing we use the old screen order.
2421 for (ItemInfo item: sBgItemsIdMap.values()) {
2422 maxItemId = Math.max(maxItemId, item.id);
2423 }
Michael Jurka414300a2013-08-27 15:42:35 +02002424 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002425 } else {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08002426 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
Winson Chung9f9f00b2013-11-15 13:27:00 -08002427 // Log to disk
2428 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2429 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002430
2431 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002432 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002433 for (ItemInfo item: sBgItemsIdMap.values()) {
2434 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002435 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2436 unusedScreens.contains(screenId)) {
2437 unusedScreens.remove(screenId);
2438 }
2439 }
2440
2441 // If there are any empty screens remove them, and update.
2442 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002443 // Log to disk
2444 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2445 TextUtils.join(", ", unusedScreens), true);
2446
Winson Chung933bae62013-08-29 11:42:30 -07002447 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002448 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2449 }
2450 }
2451
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 if (DEBUG_LOADERS) {
2453 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2454 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002455 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002456 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002458
Daniel Sandler566da102013-06-25 23:43:45 -04002459 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002460 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002461 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002462 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002463 line += " | ";
2464 }
Winson Chung892c74d2013-08-22 16:15:50 -07002465 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002466 ItemInfo[][] screen = occupied.get(screenId);
2467 if (x < screen.length && y < screen[x].length) {
2468 line += (screen[x][y] != null) ? "#" : ".";
2469 } else {
2470 line += "!";
2471 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002472 }
Joe Onorato36115782010-06-17 13:28:48 -04002473 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002475 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002476 }
Joe Onorato36115782010-06-17 13:28:48 -04002477 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002478 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002479 }
2480
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002481 /**
2482 * Partially updates the item without any notification. Must be called on the worker thread.
2483 */
2484 private void updateItem(long itemId, ContentValues update) {
2485 mContext.getContentResolver().update(
2486 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2487 update,
2488 BaseColumns._ID + "= ?",
2489 new String[]{Long.toString(itemId)});
2490 }
2491
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 /** Filters the set of items who are directly or indirectly (via another container) on the
2493 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002494 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002495 ArrayList<ItemInfo> allWorkspaceItems,
2496 ArrayList<ItemInfo> currentScreenItems,
2497 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002498 // Purge any null ItemInfos
2499 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2500 while (iter.hasNext()) {
2501 ItemInfo i = iter.next();
2502 if (i == null) {
2503 iter.remove();
2504 }
2505 }
2506
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 // Order the set of items by their containers first, this allows use to walk through the
2508 // list sequentially, build up a list of containers that are in the specified screen,
2509 // as well as all items in those containers.
2510 Set<Long> itemsOnScreen = new HashSet<Long>();
2511 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2512 @Override
2513 public int compare(ItemInfo lhs, ItemInfo rhs) {
2514 return (int) (lhs.container - rhs.container);
2515 }
2516 });
2517 for (ItemInfo info : allWorkspaceItems) {
2518 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002519 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520 currentScreenItems.add(info);
2521 itemsOnScreen.add(info.id);
2522 } else {
2523 otherScreenItems.add(info);
2524 }
2525 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2526 currentScreenItems.add(info);
2527 itemsOnScreen.add(info.id);
2528 } else {
2529 if (itemsOnScreen.contains(info.container)) {
2530 currentScreenItems.add(info);
2531 itemsOnScreen.add(info.id);
2532 } else {
2533 otherScreenItems.add(info);
2534 }
2535 }
2536 }
2537 }
2538
2539 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002540 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002541 ArrayList<LauncherAppWidgetInfo> appWidgets,
2542 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2543 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544
2545 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002546 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002548 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 currentScreenWidgets.add(widget);
2550 } else {
2551 otherScreenWidgets.add(widget);
2552 }
2553 }
2554 }
2555
2556 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002557 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 HashMap<Long, ItemInfo> itemsIdMap,
2559 HashMap<Long, FolderInfo> folders,
2560 HashMap<Long, FolderInfo> currentScreenFolders,
2561 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562
2563 for (long id : folders.keySet()) {
2564 ItemInfo info = itemsIdMap.get(id);
2565 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002566 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002567 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002568 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569 currentScreenFolders.put(id, folder);
2570 } else {
2571 otherScreenFolders.put(id, folder);
2572 }
2573 }
2574 }
2575
2576 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2577 * right) */
2578 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002579 final LauncherAppState app = LauncherAppState.getInstance();
2580 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002581 // XXX: review this
2582 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002583 @Override
2584 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002585 int cellCountX = (int) grid.numColumns;
2586 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002587 int screenOffset = cellCountX * cellCountY;
2588 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002589 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002590 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002591 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002592 rhs.cellY * cellCountX + rhs.cellX);
2593 return (int) (lr - rr);
2594 }
2595 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002596 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002597
Adam Cohendcd297f2013-06-18 13:13:40 -07002598 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2599 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002600 final Runnable r = new Runnable() {
2601 @Override
2602 public void run() {
2603 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2604 if (callbacks != null) {
2605 callbacks.bindScreens(orderedScreens);
2606 }
2607 }
2608 };
2609 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2610 }
2611
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002612 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2613 final ArrayList<ItemInfo> workspaceItems,
2614 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2615 final HashMap<Long, FolderInfo> folders,
2616 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002617
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002618 final boolean postOnMainThread = (deferredBindRunnables != null);
2619
2620 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002621 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002622 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002623 final int start = i;
2624 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002625 final Runnable r = new Runnable() {
2626 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002627 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002628 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002629 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002630 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2631 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002632 }
2633 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002634 };
2635 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002636 synchronized (deferredBindRunnables) {
2637 deferredBindRunnables.add(r);
2638 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002639 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002640 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002641 }
Joe Onorato36115782010-06-17 13:28:48 -04002642 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002643
2644 // Bind the folders
2645 if (!folders.isEmpty()) {
2646 final Runnable r = new Runnable() {
2647 public void run() {
2648 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2649 if (callbacks != null) {
2650 callbacks.bindFolders(folders);
2651 }
2652 }
2653 };
2654 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002655 synchronized (deferredBindRunnables) {
2656 deferredBindRunnables.add(r);
2657 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002659 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002660 }
2661 }
2662
2663 // Bind the widgets, one at a time
2664 N = appWidgets.size();
2665 for (int i = 0; i < N; i++) {
2666 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2667 final Runnable r = new Runnable() {
2668 public void run() {
2669 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2670 if (callbacks != null) {
2671 callbacks.bindAppWidget(widget);
2672 }
2673 }
2674 };
2675 if (postOnMainThread) {
2676 deferredBindRunnables.add(r);
2677 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002678 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002679 }
2680 }
2681 }
2682
2683 /**
2684 * Binds all loaded data to actual views on the main thread.
2685 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002686 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002687 final long t = SystemClock.uptimeMillis();
2688 Runnable r;
2689
2690 // Don't use these two variables in any of the callback runnables.
2691 // Otherwise we hold a reference to them.
2692 final Callbacks oldCallbacks = mCallbacks.get();
2693 if (oldCallbacks == null) {
2694 // This launcher has exited and nobody bothered to tell us. Just bail.
2695 Log.w(TAG, "LoaderTask running with no launcher");
2696 return;
2697 }
2698
Winson Chung9b9fb962013-11-15 15:39:34 -08002699 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002700 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2701 ArrayList<LauncherAppWidgetInfo> appWidgets =
2702 new ArrayList<LauncherAppWidgetInfo>();
2703 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2704 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002705 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002706 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002707 workspaceItems.addAll(sBgWorkspaceItems);
2708 appWidgets.addAll(sBgAppWidgets);
2709 folders.putAll(sBgFolders);
2710 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002711 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002712 }
2713
Derek Prothro7aff3992013-12-10 14:00:37 -05002714 final boolean isLoadingSynchronously =
2715 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002716 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002717 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002718 if (currScreen >= orderedScreenIds.size()) {
2719 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002720 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002721 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002722 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002723 final long currentScreenId = currentScreen < 0
2724 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002725
2726 // Load all the items that are on the current page first (and in the process, unbind
2727 // all the existing workspace items before we call startBinding() below.
2728 unbindWorkspaceItemsOnMainThread();
2729
2730 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002731 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2732 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2733 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2734 new ArrayList<LauncherAppWidgetInfo>();
2735 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2736 new ArrayList<LauncherAppWidgetInfo>();
2737 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2738 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2739
Winson Chung9b9fb962013-11-15 15:39:34 -08002740 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002741 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002742 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002743 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002744 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002745 otherFolders);
2746 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2747 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2748
2749 // Tell the workspace that we're about to start binding items
2750 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002751 public void run() {
2752 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2753 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002754 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002755 }
2756 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002757 };
Winson Chung81b52252012-08-27 15:34:29 -07002758 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002759
Adam Cohendcd297f2013-06-18 13:13:40 -07002760 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2761
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002762 // Load items on the current page
2763 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2764 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002765 if (isLoadingSynchronously) {
2766 r = new Runnable() {
2767 public void run() {
2768 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002769 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002770 callbacks.onPageBoundSynchronously(currentScreen);
2771 }
2772 }
2773 };
Winson Chung81b52252012-08-27 15:34:29 -07002774 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002775 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002776
Winson Chung4a2afa32012-07-19 14:53:05 -07002777 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2778 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002779 synchronized (mDeferredBindRunnables) {
2780 mDeferredBindRunnables.clear();
2781 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002782 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002783 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002784
2785 // Tell the workspace that we're done binding items
2786 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002787 public void run() {
2788 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2789 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002790 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002791 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002792
Winson Chung98e030b2012-05-07 16:01:11 -07002793 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002794 if (DEBUG_LOADERS) {
2795 Log.d(TAG, "bound workspace in "
2796 + (SystemClock.uptimeMillis()-t) + "ms");
2797 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002798
2799 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002800 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002801 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002802 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002803 synchronized (mDeferredBindRunnables) {
2804 mDeferredBindRunnables.add(r);
2805 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002806 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002807 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002808 }
Joe Onorato36115782010-06-17 13:28:48 -04002809 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002810
Joe Onorato36115782010-06-17 13:28:48 -04002811 private void loadAndBindAllApps() {
2812 if (DEBUG_LOADERS) {
2813 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2814 }
2815 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002816 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002817 synchronized (LoaderTask.this) {
2818 if (mStopped) {
2819 return;
2820 }
2821 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002822 }
Joe Onorato36115782010-06-17 13:28:48 -04002823 } else {
2824 onlyBindAllApps();
2825 }
2826 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002827
Joe Onorato36115782010-06-17 13:28:48 -04002828 private void onlyBindAllApps() {
2829 final Callbacks oldCallbacks = mCallbacks.get();
2830 if (oldCallbacks == null) {
2831 // This launcher has exited and nobody bothered to tell us. Just bail.
2832 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2833 return;
2834 }
2835
2836 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002837 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002838 final ArrayList<AppInfo> list
2839 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002840 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002841 public void run() {
2842 final long t = SystemClock.uptimeMillis();
2843 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2844 if (callbacks != null) {
2845 callbacks.bindAllApplications(list);
2846 }
2847 if (DEBUG_LOADERS) {
2848 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2849 + (SystemClock.uptimeMillis()-t) + "ms");
2850 }
2851 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002852 };
2853 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002854 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002855 r.run();
2856 } else {
2857 mHandler.post(r);
2858 }
Joe Onorato36115782010-06-17 13:28:48 -04002859 }
2860
Winson Chung64359a52013-07-08 17:17:08 -07002861 private void loadAllApps() {
2862 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002863
Joe Onorato36115782010-06-17 13:28:48 -04002864 final Callbacks oldCallbacks = mCallbacks.get();
2865 if (oldCallbacks == null) {
2866 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002867 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002868 return;
2869 }
2870
2871 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2872 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2873
Kenny Guyed131872014-04-30 03:02:21 +01002874 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2875
Winson Chung64359a52013-07-08 17:17:08 -07002876 // Clear the list of apps
2877 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002878 SharedPreferences prefs = mContext.getSharedPreferences(
2879 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002880 for (UserHandleCompat user : profiles) {
2881 // Query for the set of apps
2882 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2883 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2884 if (DEBUG_LOADERS) {
2885 Log.d(TAG, "getActivityList took "
2886 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2887 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2888 }
2889 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002890 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002891 if (apps == null || apps.isEmpty()) {
2892 return;
2893 }
2894 // Sort the applications by name
2895 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2896 Collections.sort(apps,
2897 new LauncherModel.ShortcutNameComparator(mLabelCache));
2898 if (DEBUG_LOADERS) {
2899 Log.d(TAG, "sort took "
2900 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2901 }
Joe Onorato36115782010-06-17 13:28:48 -04002902
Kenny Guyed131872014-04-30 03:02:21 +01002903 // Create the ApplicationInfos
2904 for (int i = 0; i < apps.size(); i++) {
2905 LauncherActivityInfoCompat app = apps.get(i);
2906 // This builds the icon bitmaps.
2907 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2908 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002909
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002910 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002911 // Add shortcuts for packages which were installed while launcher was dead.
2912 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2913 + mUserManager.getSerialNumberForUser(user);
2914 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2915 HashSet<String> newPackageSet = new HashSet<String>();
2916
2917 for (LauncherActivityInfoCompat info : apps) {
2918 String packageName = info.getComponentName().getPackageName();
2919 if (!packagesAdded.contains(packageName)
2920 && !newPackageSet.contains(packageName)) {
2921 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2922 }
2923 newPackageSet.add(packageName);
2924 }
2925
2926 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2927 }
Winson Chung64359a52013-07-08 17:17:08 -07002928 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002929 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002930 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2931 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002932
2933 // Post callback on main thread
2934 mHandler.post(new Runnable() {
2935 public void run() {
2936 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002937 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002938 if (callbacks != null) {
2939 callbacks.bindAllApplications(added);
2940 if (DEBUG_LOADERS) {
2941 Log.d(TAG, "bound " + added.size() + " apps in "
2942 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2943 }
2944 } else {
2945 Log.i(TAG, "not binding apps: no Launcher activity");
2946 }
2947 }
2948 });
2949
Joe Onorato36115782010-06-17 13:28:48 -04002950 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002951 Log.d(TAG, "Icons processed in "
2952 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002953 }
2954 }
2955
2956 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002957 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002958 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2959 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2960 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2961 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2962 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2963 }
Joe Onorato36115782010-06-17 13:28:48 -04002964 }
2965 }
2966
2967 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002968 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002969 }
2970
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002971 private class AppsAvailabilityCheck extends BroadcastReceiver {
2972
2973 @Override
2974 public void onReceive(Context context, Intent intent) {
2975 synchronized (sBgLock) {
2976 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2977 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002978 final PackageManager manager = context.getPackageManager();
2979 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2980 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002981 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2982 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002983 packagesRemoved.clear();
2984 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002985 for (String pkg : entry.getValue()) {
2986 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002987 boolean packageOnSdcard = launcherApps.isAppEnabled(
2988 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2989 if (packageOnSdcard) {
2990 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2991 packagesUnavailable.add(pkg);
2992 } else {
2993 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2994 packagesRemoved.add(pkg);
2995 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002996 }
2997 }
2998 if (!packagesRemoved.isEmpty()) {
2999 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
3000 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
3001 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003002 if (!packagesUnavailable.isEmpty()) {
3003 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
3004 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
3005 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003006 }
Sunny Goyal34942622014-08-29 17:20:55 -07003007 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003008 }
3009 }
3010 }
3011
Joe Onorato36115782010-06-17 13:28:48 -04003012 private class PackageUpdatedTask implements Runnable {
3013 int mOp;
3014 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01003015 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04003016
3017 public static final int OP_NONE = 0;
3018 public static final int OP_ADD = 1;
3019 public static final int OP_UPDATE = 2;
3020 public static final int OP_REMOVE = 3; // uninstlled
3021 public static final int OP_UNAVAILABLE = 4; // external media unmounted
3022
3023
Kenny Guyed131872014-04-30 03:02:21 +01003024 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04003025 mOp = op;
3026 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01003027 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04003028 }
3029
3030 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04003031 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04003032
3033 final String[] packages = mPackages;
3034 final int N = packages.length;
3035 switch (mOp) {
3036 case OP_ADD:
3037 for (int i=0; i<N; i++) {
3038 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003039 mIconCache.remove(packages[i], mUser);
3040 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003041 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003042
3043 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003044 if (ADD_MANAGED_PROFILE_SHORTCUTS
3045 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003046 SharedPreferences prefs = context.getSharedPreferences(
3047 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3048 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3049 + mUserManager.getSerialNumberForUser(mUser);
3050 Set<String> shortcutSet = new HashSet<String>(
3051 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3052
3053 for (int i=0; i<N; i++) {
3054 if (!shortcutSet.contains(packages[i])) {
3055 shortcutSet.add(packages[i]);
3056 List<LauncherActivityInfoCompat> activities =
3057 mLauncherApps.getActivityList(packages[i], mUser);
3058 if (activities != null && !activities.isEmpty()) {
3059 InstallShortcutReceiver.queueInstallShortcut(
3060 activities.get(0), context);
3061 }
3062 }
3063 }
3064
3065 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3066 }
Joe Onorato36115782010-06-17 13:28:48 -04003067 break;
3068 case OP_UPDATE:
3069 for (int i=0; i<N; i++) {
3070 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003071 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003072 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003073 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003074 }
3075 break;
3076 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003077 // Remove the packageName for the set of auto-installed shortcuts. This
3078 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003079 if (ADD_MANAGED_PROFILE_SHORTCUTS
3080 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003081 SharedPreferences prefs = context.getSharedPreferences(
3082 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3083 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3084 + mUserManager.getSerialNumberForUser(mUser);
3085 HashSet<String> shortcutSet = new HashSet<String>(
3086 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3087 shortcutSet.removeAll(Arrays.asList(mPackages));
3088 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3089 }
3090 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003091 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003092 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003093 for (int i=0; i<N; i++) {
3094 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003095 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003096 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003097 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003098 }
3099 break;
3100 }
3101
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003102 ArrayList<AppInfo> added = null;
3103 ArrayList<AppInfo> modified = null;
3104 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003105
Adam Cohen487f7dd2012-06-28 18:12:10 -07003106 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003107 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003108 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003109 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003110 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003111 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003112 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003113 }
Winson Chung5d55f332012-07-16 20:45:03 -07003114 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003115 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003116 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003117 }
3118
Sunny Goyale0f58d72014-11-10 18:05:31 -08003119 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003120 if (callbacks == null) {
3121 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3122 return;
3123 }
3124
Sunny Goyal4390ace2014-10-13 11:33:11 -07003125 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3126 new HashMap<ComponentName, AppInfo>();
3127
Joe Onorato36115782010-06-17 13:28:48 -04003128 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003129 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003130 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003131 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003132 addAndBindAddedWorkspaceApps(context, addedInfos);
3133 } else {
3134 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003135 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003136 for (AppInfo ai : added) {
3137 addedOrUpdatedApps.put(ai.componentName, ai);
3138 }
Joe Onorato36115782010-06-17 13:28:48 -04003139 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003140
Joe Onorato36115782010-06-17 13:28:48 -04003141 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003142 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003143 for (AppInfo ai : modified) {
3144 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003145 }
3146
Joe Onorato36115782010-06-17 13:28:48 -04003147 mHandler.post(new Runnable() {
3148 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003149 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003150 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003151 callbacks.bindAppsUpdated(modifiedFinal);
3152 }
3153 }
3154 });
3155 }
Winson Chung83892cc2013-05-01 16:53:33 -07003156
Sunny Goyal4390ace2014-10-13 11:33:11 -07003157 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003158 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003159 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3160 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3161 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3162
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003163 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003164 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003165 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003166 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3167 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003168 boolean infoUpdated = false;
3169 boolean shortcutUpdated = false;
3170
3171 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003172 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003173 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003174 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3175 si.iconResource.resourceName, mIconCache, context);
3176 if (icon != null) {
3177 si.setIcon(icon);
3178 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003179 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003180 }
3181 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003182
3183 ComponentName cn = si.getTargetComponent();
3184 if (cn != null && packageSet.contains(cn.getPackageName())) {
3185 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3186
3187 if (si.isPromise()) {
3188 mIconCache.deletePreloadedIcon(cn, mUser);
3189 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3190 // Auto install icon
3191 PackageManager pm = context.getPackageManager();
3192 ResolveInfo matched = pm.resolveActivity(
3193 new Intent(Intent.ACTION_MAIN)
3194 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3195 PackageManager.MATCH_DEFAULT_ONLY);
3196 if (matched == null) {
3197 // Try to find the best match activity.
3198 Intent intent = pm.getLaunchIntentForPackage(
3199 cn.getPackageName());
3200 if (intent != null) {
3201 cn = intent.getComponent();
3202 appInfo = addedOrUpdatedApps.get(cn);
3203 }
3204
3205 if ((intent == null) || (appInfo == null)) {
3206 removedShortcuts.add(si);
3207 continue;
3208 }
3209 si.promisedIntent = intent;
3210 }
3211 }
3212
3213 // Restore the shortcut.
3214 si.intent = si.promisedIntent;
3215 si.promisedIntent = null;
3216 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3217 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3218 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3219
3220 infoUpdated = true;
3221 si.updateIcon(mIconCache);
3222 }
3223
3224 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3225 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3226 si.updateIcon(mIconCache);
3227 si.title = appInfo.title.toString();
3228 si.contentDescription = appInfo.contentDescription;
3229 infoUpdated = true;
3230 }
3231
3232 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3233 // Since package was just updated, the target must be available now.
3234 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3235 shortcutUpdated = true;
3236 }
3237 }
3238
3239 if (infoUpdated || shortcutUpdated) {
3240 updatedShortcuts.add(si);
3241 }
3242 if (infoUpdated) {
3243 updateItemInDatabase(context, si);
3244 }
3245 } else if (info instanceof LauncherAppWidgetInfo) {
3246 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3247 if (mUser.equals(widgetInfo.user)
3248 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3249 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3250 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3251 widgets.add(widgetInfo);
3252 updateItemInDatabase(context, widgetInfo);
3253 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003254 }
3255 }
3256 }
3257
Sunny Goyal4390ace2014-10-13 11:33:11 -07003258 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3259 mHandler.post(new Runnable() {
3260
3261 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003262 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003263 if (callbacks == cb && cb != null) {
3264 callbacks.bindShortcutsChanged(
3265 updatedShortcuts, removedShortcuts, mUser);
3266 }
3267 }
3268 });
3269 if (!removedShortcuts.isEmpty()) {
3270 deleteItemsFromDatabase(context, removedShortcuts);
3271 }
3272 }
3273 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003274 mHandler.post(new Runnable() {
3275 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003276 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003277 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003278 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003279 }
3280 }
3281 });
3282 }
3283 }
3284
Winson Chungdf95eb12013-10-16 14:57:07 -07003285 final ArrayList<String> removedPackageNames =
3286 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003287 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003288 // Mark all packages in the broadcast to be removed
3289 removedPackageNames.addAll(Arrays.asList(packages));
3290 } else if (mOp == OP_UPDATE) {
3291 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003292 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003293 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003294 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003295 }
3296 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003297 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003298
Winson Chungdf95eb12013-10-16 14:57:07 -07003299 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003300 final int removeReason;
3301 if (mOp == OP_UNAVAILABLE) {
3302 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3303 } else {
3304 // Remove all the components associated with this package
3305 for (String pn : removedPackageNames) {
3306 deletePackageFromDatabase(context, pn, mUser);
3307 }
3308 // Remove all the specific components
3309 for (AppInfo a : removedApps) {
3310 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3311 deleteItemsFromDatabase(context, infos);
3312 }
3313 removeReason = 0;
3314 }
3315
Winson Chungdf95eb12013-10-16 14:57:07 -07003316 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003317 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003318 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003319 mHandler.post(new Runnable() {
3320 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003321 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003322 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003323 callbacks.bindComponentsRemoved(
3324 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003325 }
3326 }
3327 });
Joe Onoratobe386092009-11-17 17:32:16 -08003328 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003329
Michael Jurkac402cd92013-05-20 15:49:32 +02003330 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003331 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003332 mHandler.post(new Runnable() {
3333 @Override
3334 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003335 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003336 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003337 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003338 }
3339 }
3340 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003341
3342 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003343 mHandler.post(new Runnable() {
3344 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003345 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003346 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003347 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003348 }
3349 }
3350 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003351 }
3352 }
3353
Adam Cohen59400422014-03-05 18:07:04 -08003354 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3355 synchronized (sBgLock) {
3356 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3357 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3358 }
3359 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3360 List<AppWidgetProviderInfo> widgets =
3361 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3362 LauncherAppWidgetProviderInfo info;
3363 for (AppWidgetProviderInfo pInfo : widgets) {
3364 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3365 sBgWidgetProviders.put(info.provider, info);
3366 }
3367
3368 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3369 for (CustomAppWidget widget : customWidgets) {
3370 info = new LauncherAppWidgetProviderInfo(context, widget);
3371 sBgWidgetProviders.put(info.provider, info);
3372 }
3373 sWidgetProvidersDirty = false;
3374 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3375 }
3376 }
3377
3378 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3379 synchronized (sBgLock) {
3380 if (sBgWidgetProviders == null) {
3381 getWidgetProviders(ctx);
3382 }
3383 return sBgWidgetProviders.get(name);
3384 }
3385 }
3386
Michael Jurkac402cd92013-05-20 15:49:32 +02003387 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3388 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3389 PackageManager packageManager = context.getPackageManager();
3390 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003391 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003392 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3393 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003394 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003395 return widgetsAndShortcuts;
3396 }
3397
Kenny Guyed131872014-04-30 03:02:21 +01003398 private static boolean isPackageDisabled(Context context, String packageName,
3399 UserHandleCompat user) {
3400 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3401 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003402 }
Adam Cohen556f6132014-01-15 15:18:08 -08003403
Kenny Guyed131872014-04-30 03:02:21 +01003404 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3405 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003406 if (cn == null) {
3407 return false;
3408 }
Kenny Guyed131872014-04-30 03:02:21 +01003409 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3410 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003411 return false;
3412 }
Kenny Guyed131872014-04-30 03:02:21 +01003413 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003414 }
3415
Adam Cohena28b78e2014-05-20 17:03:04 -07003416 public static boolean isValidPackage(Context context, String packageName,
3417 UserHandleCompat user) {
3418 if (packageName == null) {
3419 return false;
3420 }
3421 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3422 return launcherApps.isPackageEnabledForProfile(packageName, user);
3423 }
3424
Joe Onorato9c1289c2009-08-17 11:03:03 -04003425 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003426 * Make an ShortcutInfo object for a restored application or shortcut item that points
3427 * to a package that is not yet installed on the system.
3428 */
Sunny Goyal34942622014-08-29 17:20:55 -07003429 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3430 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003431 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003432 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003433 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3434
3435 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3436 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3437 if (!TextUtils.isEmpty(title)) {
3438 info.title = title;
3439 }
3440 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3441 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3442 if (TextUtils.isEmpty(info.title)) {
3443 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3444 }
3445 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3446 } else {
3447 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3448 }
3449
Kenny Guyc2bd8102014-06-30 12:30:31 +01003450 info.contentDescription = mUserManager.getBadgedLabelForUser(
3451 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003452 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003453 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003454 return info;
3455 }
3456
3457 /**
3458 * Make an Intent object for a restored application or shortcut item that points
3459 * to the market page for the item.
3460 */
3461 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3462 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003463 return getMarketIntent(componentName.getPackageName());
3464 }
3465
3466 static Intent getMarketIntent(String packageName) {
3467 return new Intent(Intent.ACTION_VIEW)
3468 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003469 .scheme("market")
3470 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003471 .appendQueryParameter("id", packageName)
3472 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003473 }
3474
3475 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003476 * This is called from the code that adds shortcuts from the intent receiver. This
3477 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003478 */
Kenny Guyed131872014-04-30 03:02:21 +01003479 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3480 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003481 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003482 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003483
Joe Onorato56d82912010-03-07 14:32:10 -05003484 /**
3485 * Make an ShortcutInfo object for a shortcut that is an application.
3486 *
3487 * If c is not null, then it will be used to fill in missing data like the title and icon.
3488 */
Kenny Guyed131872014-04-30 03:02:21 +01003489 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3490 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003491 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003492 if (user == null) {
3493 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003494 return null;
3495 }
3496
Kenny Guyed131872014-04-30 03:02:21 +01003497 ComponentName componentName = intent.getComponent();
3498 if (componentName == null) {
3499 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3500 return null;
3501 }
3502
3503 Intent newIntent = new Intent(intent.getAction(), null);
3504 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3505 newIntent.setComponent(componentName);
3506 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003507 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003508 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3509 return null;
3510 }
3511
3512 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003513
Joe Onorato56d82912010-03-07 14:32:10 -05003514 // the resource -- This may implicitly give us back the fallback icon,
3515 // but don't worry about that. All we're doing with usingFallbackIcon is
3516 // to avoid saving lots of copies of that in the database, and most apps
3517 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003518 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003519
Joe Onorato56d82912010-03-07 14:32:10 -05003520 // the db
3521 if (icon == null) {
3522 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003523 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003524 }
3525 }
3526 // the fallback icon
3527 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003528 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003529 info.usingFallbackIcon = true;
3530 }
3531 info.setIcon(icon);
3532
Kenny Guyed131872014-04-30 03:02:21 +01003533 // From the cache.
3534 if (labelCache != null) {
3535 info.title = labelCache.get(componentName);
3536 }
3537
Joe Onorato56d82912010-03-07 14:32:10 -05003538 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003539 if (info.title == null && lai != null) {
3540 info.title = lai.getLabel();
3541 if (labelCache != null) {
3542 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003543 }
Joe Onorato56d82912010-03-07 14:32:10 -05003544 }
3545 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003546 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003547 if (c != null) {
3548 info.title = c.getString(titleIndex);
3549 }
3550 }
3551 // fall back to the class name of the activity
3552 if (info.title == null) {
3553 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003554 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003555 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003556 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003557 info.contentDescription = mUserManager.getBadgedLabelForUser(
3558 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003559 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003560 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003561
Winson Chung64359a52013-07-08 17:17:08 -07003562 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3563 ItemInfoFilter f) {
3564 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3565 for (ItemInfo i : infos) {
3566 if (i instanceof ShortcutInfo) {
3567 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003568 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003569 if (cn != null && f.filterItem(null, info, cn)) {
3570 filtered.add(info);
3571 }
3572 } else if (i instanceof FolderInfo) {
3573 FolderInfo info = (FolderInfo) i;
3574 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003575 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003576 if (cn != null && f.filterItem(info, s, cn)) {
3577 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003578 }
3579 }
Winson Chung64359a52013-07-08 17:17:08 -07003580 } else if (i instanceof LauncherAppWidgetInfo) {
3581 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3582 ComponentName cn = info.providerName;
3583 if (cn != null && f.filterItem(null, info, cn)) {
3584 filtered.add(info);
3585 }
Winson Chung8a435102012-08-30 17:16:53 -07003586 }
3587 }
Winson Chung64359a52013-07-08 17:17:08 -07003588 return new ArrayList<ItemInfo>(filtered);
3589 }
3590
Kenny Guyed131872014-04-30 03:02:21 +01003591 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3592 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003593 ItemInfoFilter filter = new ItemInfoFilter() {
3594 @Override
3595 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003596 if (info.user == null) {
3597 return cn.equals(cname);
3598 } else {
3599 return cn.equals(cname) && info.user.equals(user);
3600 }
Winson Chung64359a52013-07-08 17:17:08 -07003601 }
3602 };
3603 return filterItemInfos(sBgItemsIdMap.values(), filter);
3604 }
3605
Sunny Goyal1a745e82014-10-02 15:58:31 -07003606 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003607 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003608 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003609 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003610 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3611 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003612
Joe Onorato56d82912010-03-07 14:32:10 -05003613 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003614 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003615 // Non-app shortcuts are only supported for current user.
3616 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003617 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003618
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003619 // TODO: If there's an explicit component and we can't install that, delete it.
3620
Joe Onorato56d82912010-03-07 14:32:10 -05003621 info.title = c.getString(titleIndex);
3622
Joe Onorato9c1289c2009-08-17 11:03:03 -04003623 int iconType = c.getInt(iconTypeIndex);
3624 switch (iconType) {
3625 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3626 String packageName = c.getString(iconPackageIndex);
3627 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003628 info.customIcon = false;
3629 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003630 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003631 // the db
3632 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003633 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003634 }
3635 // the fallback icon
3636 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003637 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003638 info.usingFallbackIcon = true;
3639 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003640 break;
3641 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003642 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003643 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003644 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003645 info.customIcon = false;
3646 info.usingFallbackIcon = true;
3647 } else {
3648 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003649 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003650 break;
3651 default:
Kenny Guyed131872014-04-30 03:02:21 +01003652 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003653 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003654 info.customIcon = false;
3655 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003656 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003657 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003658 return info;
3659 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003660
Michael Jurka931dc972011-08-05 15:08:15 -07003661 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003662 @SuppressWarnings("all") // suppress dead code warning
3663 final boolean debug = false;
3664 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003665 Log.d(TAG, "getIconFromCursor app="
3666 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3667 }
3668 byte[] data = c.getBlob(iconIndex);
3669 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003670 return Utilities.createIconBitmap(
3671 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003672 } catch (Exception e) {
3673 return null;
3674 }
3675 }
3676
Sunny Goyal2350bc92014-10-14 16:42:54 -07003677 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003678 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3679 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3680 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3681
Adam Cohend9198822011-11-22 16:42:47 -08003682 if (intent == null) {
3683 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3684 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3685 return null;
3686 }
3687
Joe Onorato0589f0f2010-02-08 13:44:00 -08003688 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003689 boolean customIcon = false;
3690 ShortcutIconResource iconResource = null;
3691
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003692 if (bitmap instanceof Bitmap) {
3693 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003694 customIcon = true;
3695 } else {
3696 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003697 if (extra instanceof ShortcutIconResource) {
3698 iconResource = (ShortcutIconResource) extra;
3699 icon = Utilities.createIconBitmap(iconResource.packageName,
3700 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003701 }
3702 }
3703
Michael Jurkac9d95c52011-08-29 14:03:34 -07003704 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003705
Kenny Guyed131872014-04-30 03:02:21 +01003706 // Only support intents for current user for now. Intents sent from other
3707 // users wouldn't get here without intent forwarding anyway.
3708 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003709 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003710 icon = mIconCache.getDefaultIcon(info.user);
3711 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003712 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003713 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003714
Joe Onorato0589f0f2010-02-08 13:44:00 -08003715 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003716 info.contentDescription = mUserManager.getBadgedLabelForUser(
3717 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003718 info.intent = intent;
3719 info.customIcon = customIcon;
3720 info.iconResource = iconResource;
3721
3722 return info;
3723 }
3724
Winson Chungaac01e12011-08-17 10:37:13 -07003725 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3726 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003727 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003728 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003729 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003730 }
Joe Onorato56d82912010-03-07 14:32:10 -05003731 // If this icon doesn't have a custom icon, check to see
3732 // what's stored in the DB, and if it doesn't match what
3733 // we're going to show, store what we are going to show back
3734 // into the DB. We do this so when we're loading, if the
3735 // package manager can't find an icon (for example because
3736 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003737 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003738 cache.put(info, c.getBlob(iconIndex));
3739 return true;
3740 }
3741 return false;
3742 }
3743 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3744 boolean needSave = false;
3745 try {
3746 if (data != null) {
3747 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3748 Bitmap loaded = info.getIcon(mIconCache);
3749 needSave = !saved.sameAs(loaded);
3750 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003751 needSave = true;
3752 }
Winson Chungaac01e12011-08-17 10:37:13 -07003753 } catch (Exception e) {
3754 needSave = true;
3755 }
3756 if (needSave) {
3757 Log.d(TAG, "going to save icon bitmap for info=" + info);
3758 // This is slower than is ideal, but this only happens once
3759 // or when the app is updated with a new icon.
3760 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003761 }
3762 }
3763
Joe Onorato9c1289c2009-08-17 11:03:03 -04003764 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003765 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003766 * or make a new one.
3767 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003768 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003769 // See if a placeholder was created for us already
3770 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003771 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003772 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003773 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003774 folders.put(id, folderInfo);
3775 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003776 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003777 }
3778
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003779 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003780 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003781 return new Comparator<AppInfo>() {
3782 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003783 if (a.user.equals(b.user)) {
3784 int result = collator.compare(a.title.toString().trim(),
3785 b.title.toString().trim());
3786 if (result == 0) {
3787 result = a.componentName.compareTo(b.componentName);
3788 }
3789 return result;
3790 } else {
3791 // TODO Need to figure out rules for sorting
3792 // profiles, this puts work second.
3793 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003794 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003795 }
Winson Chung11904872012-09-17 16:58:46 -07003796 };
3797 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003798 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3799 = new Comparator<AppInfo>() {
3800 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003801 if (a.firstInstallTime < b.firstInstallTime) return 1;
3802 if (a.firstInstallTime > b.firstInstallTime) return -1;
3803 return 0;
3804 }
3805 };
Winson Chung5308f242011-08-18 12:12:41 -07003806 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3807 if (info.activityInfo != null) {
3808 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3809 } else {
3810 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3811 }
3812 }
Kenny Guyed131872014-04-30 03:02:21 +01003813 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003814 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003815 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003816 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003817 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003818 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003819 }
Kenny Guyed131872014-04-30 03:02:21 +01003820 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003821 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003822 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003823 }
Kenny Guyed131872014-04-30 03:02:21 +01003824 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003825 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003826 ComponentName keyA = a.getComponentName();
3827 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003828 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003829 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003830 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003831 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003832
Winson Chung5308f242011-08-18 12:12:41 -07003833 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003834 }
Winson Chung5308f242011-08-18 12:12:41 -07003835 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003836 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003837 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003838 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003839
Winson Chung5308f242011-08-18 12:12:41 -07003840 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003841 }
Winson Chung11904872012-09-17 16:58:46 -07003842 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003843 }
3844 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003845 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003846 private final AppWidgetManagerCompat mManager;
3847 private final PackageManager mPackageManager;
3848 private final HashMap<Object, String> mLabelCache;
3849 private final Collator mCollator;
3850
3851 WidgetAndShortcutNameComparator(Context context) {
3852 mManager = AppWidgetManagerCompat.getInstance(context);
3853 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003854 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003855 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003856 }
3857 public final int compare(Object a, Object b) {
3858 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003859 if (mLabelCache.containsKey(a)) {
3860 labelA = mLabelCache.get(a);
3861 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003862 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3863 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003864 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003865 mLabelCache.put(a, labelA);
3866 }
3867 if (mLabelCache.containsKey(b)) {
3868 labelB = mLabelCache.get(b);
3869 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003870 labelB = (b instanceof LauncherAppWidgetProviderInfo)
3871 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003872 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003873 mLabelCache.put(b, labelB);
3874 }
Winson Chung11904872012-09-17 16:58:46 -07003875 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003876 }
3877 };
Joe Onoratobe386092009-11-17 17:32:16 -08003878
Sunny Goyal651077b2014-06-30 14:15:31 -07003879 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3880 return (provider != null) && (provider.provider != null)
3881 && (provider.provider.getPackageName() != null);
3882 }
3883
Joe Onoratobe386092009-11-17 17:32:16 -08003884 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003885 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003886 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3887 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3888 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3889 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003890 if (mLoaderTask != null) {
3891 mLoaderTask.dumpState();
3892 } else {
3893 Log.d(TAG, "mLoaderTask=null");
3894 }
Joe Onoratobe386092009-11-17 17:32:16 -08003895 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003896
3897 public Callbacks getCallback() {
3898 return mCallbacks != null ? mCallbacks.get() : null;
3899 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003900}