blob: 7b5f8466a8d2287398efac8585bac6c62c308776 [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;
Adam Cohendcd297f2013-06-18 13:13:40 -070078import java.util.TreeMap;
Michael Jurkac2f801e2011-07-12 14:19:46 -070079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080/**
81 * Maintains in-memory state of the Launcher. It is expected that there should be only one
82 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070083 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 */
Kenny Guyed131872014-04-30 03:02:21 +010085public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010086 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040088 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070089 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080090 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040091
Joe Onorato9c1289c2009-08-17 11:03:03 -040092 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070093
Daniel Sandler8707e0f2013-08-15 15:54:18 -070094 // true = use a "More Apps" folder for non-workspace apps on upgrade
95 // false = strew non-workspace apps across the workspace on upgrade
96 public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
Dan Sandlerd5024042014-01-09 15:01:33 -050097 public static final int LOADER_FLAG_NONE = 0;
98 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
99 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
100
Joe Onorato36115782010-06-17 13:28:48 -0400101 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500102 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800103
Winson Chungee055712013-07-30 14:46:24 -0700104 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800105 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400106
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400107 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400108 private final Object mLock = new Object();
109 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400110 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700111 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Sunny Goyale0f58d72014-11-10 18:05:31 -0800113 /**
114 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
115 */
116 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
117
Winson Chung81b52252012-08-27 15:34:29 -0700118 // Specific runnable types that are run on the main thread deferred handler, this allows us to
119 // clear all queued binding runnables when the Launcher activity is destroyed.
120 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
121 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
122
Jason Monkbbe1e242014-05-16 17:37:34 -0400123 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700124
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700125 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
126 static {
127 sWorkerThread.start();
128 }
129 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
130
Joe Onoratocc67f472010-06-08 10:54:30 -0700131 // We start off with everything not loaded. After that, we assume that
132 // our monitoring of the package manager provides all updates and we never
133 // need to do a requery. These are only ever touched from the loader thread.
134 private boolean mWorkspaceLoaded;
135 private boolean mAllAppsLoaded;
136
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700137 // When we are loading pages synchronously, we can't just post the binding of items on the side
138 // pages as this delays the rotation process. Instead, we wait for a callback from the first
139 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
140 // a normal load, we also clear this set of Runnables.
141 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
142
Joe Onorato9c1289c2009-08-17 11:03:03 -0400143 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800144
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700146 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800147
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148 // The lock that must be acquired before referencing any static bg data structures. Unlike
149 // other locks, this one can generally be held long-term because we never expect any of these
150 // static data structures to be referenced outside of the worker thread except on the first
151 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700152 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700153
Adam Cohen487f7dd2012-06-28 18:12:10 -0700154 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700156 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
159 // created by LauncherModel that are directly on the home screen (however, no widgets or
160 // shortcuts within folders).
161 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
164 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700165 new ArrayList<LauncherAppWidgetInfo>();
166
Adam Cohen487f7dd2012-06-28 18:12:10 -0700167 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
168 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700169
Adam Cohen487f7dd2012-06-28 18:12:10 -0700170 // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
171 static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700172
173 // sBgWorkspaceScreens is the ordered set of workspace screens.
174 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
175
Adam Cohen59400422014-03-05 18:07:04 -0800176 // sBgWidgetProviders is the set of widget providers including custom internal widgets
177 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
178 public static boolean sWidgetProvidersDirty;
179
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700180 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700181 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
182 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700183
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 // </ only access in worker thread >
185
186 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187
Reena Lee99a73f32011-10-24 17:27:37 -0700188 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700189
Kenny Guyed131872014-04-30 03:02:21 +0100190 private final LauncherAppsCompat mLauncherApps;
191 private final UserManagerCompat mUserManager;
192
Joe Onorato9c1289c2009-08-17 11:03:03 -0400193 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700194 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400195 public int getCurrentWorkspaceScreen();
196 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700197 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
198 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700199 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700200 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500201 public void bindFolders(HashMap<Long,FolderInfo> folders);
Adam Cohene25af792013-06-06 23:08:25 -0700202 public void finishBindingItems(boolean upgradePath);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400203 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200204 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700205 public void bindAppsAdded(ArrayList<Long> newScreens,
206 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700207 ArrayList<ItemInfo> addAnimated,
208 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200209 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700210 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
211 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
212 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700213 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700214 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700215 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700216 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200217 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100218 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700219 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700220 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700221 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800222 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
223 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400224 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225
Winson Chung64359a52013-07-08 17:17:08 -0700226 public interface ItemInfoFilter {
227 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
228 }
229
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800230 public interface ScreenPosProvider {
231 int getScreenIndex(ArrayList<Long> screenIDs);
232 }
233
Bjorn Bringert1307f632013-10-03 22:31:03 +0100234 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800235 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400236
Winson Chungee055712013-07-30 14:46:24 -0700237 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700238 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400239 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
240 // resource string.
241 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
242 ProviderInfo providerInfo =
243 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
244 ProviderInfo redirectProvider =
245 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700246
247 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400248 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700249
250 if (mOldContentProviderExists) {
251 Log.d(TAG, "Old launcher provider exists.");
252 } else {
253 Log.d(TAG, "Old launcher provider does not exist.");
254 }
255
Daniel Sandlere4f98912013-06-25 15:13:26 -0400256 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100257 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800258 mIconCache = iconCache;
259
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400260 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700261 Configuration config = res.getConfiguration();
262 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100263 mLauncherApps = LauncherAppsCompat.getInstance(context);
264 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800265 }
266
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700267 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
268 * posted on the main thread handler. */
269 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700270 runOnMainThread(r, 0);
271 }
272 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700273 if (sWorkerThread.getThreadId() == Process.myTid()) {
274 // If we are on the worker thread, post onto the main handler
275 mHandler.post(r);
276 } else {
277 r.run();
278 }
279 }
280
281 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
282 * posted on the worker thread handler. */
283 private static void runOnWorkerThread(Runnable r) {
284 if (sWorkerThread.getThreadId() == Process.myTid()) {
285 r.run();
286 } else {
287 // If we are not on the worker thread, then post to the worker handler
288 sWorker.post(r);
289 }
290 }
291
Winson Chunge43a1e72014-01-15 10:33:02 -0800292 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
293 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800294 }
295
Sunny Goyale755d462014-07-22 13:48:29 -0700296 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500297 // Process the updated package state
298 Runnable r = new Runnable() {
299 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800300 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500301 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700302 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500303 }
304 }
305 };
306 mHandler.post(r);
307 }
308
Sunny Goyala22666f2014-09-18 13:25:15 -0700309 public void updatePackageBadge(final String packageName) {
310 // Process the updated package badge
311 Runnable r = new Runnable() {
312 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800313 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700314 if (callbacks != null) {
315 callbacks.updatePackageBadge(packageName);
316 }
317 }
318 };
319 mHandler.post(r);
320 }
321
Adam Cohen76a47a12014-02-05 11:47:43 -0800322 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800323 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800324
325 if (allAppsApps == null) {
326 throw new RuntimeException("allAppsApps must not be null");
327 }
328 if (allAppsApps.isEmpty()) {
329 return;
330 }
331
332 // Process the newly added applications and add them to the database first
333 Runnable r = new Runnable() {
334 public void run() {
335 runOnMainThread(new Runnable() {
336 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800337 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800338 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500339 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800340 }
341 }
342 });
343 }
344 };
345 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700346 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800347
348 public void addAndBindAddedWorkspaceApps(final Context context,
349 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800350 addAndBindAddedWorkspaceApps(context, workspaceApps,
351 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800352
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800353 @Override
354 public int getScreenIndex(ArrayList<Long> screenIDs) {
355 return screenIDs.isEmpty() ? 0 : 1;
356 }
357 }, 1, false);
358 }
359
360 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
361 int[] xy, int spanX, int spanY) {
362 LauncherAppState app = LauncherAppState.getInstance();
363 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
364 final int xCount = (int) grid.numColumns;
365 final int yCount = (int) grid.numRows;
366 boolean[][] occupied = new boolean[xCount][yCount];
367 if (occupiedPos != null) {
368 for (Rect r : occupiedPos) {
369 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
370 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
371 occupied[x][y] = true;
372 }
373 }
374 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800375 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800376 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
377 }
378
379 /**
380 * Find a position on the screen for the given size or adds a new screen.
381 * @return screenId and the coordinates for the item.
382 */
383 private static Pair<Long, int[]> findSpaceForItem(
384 Context context,
385 ScreenPosProvider preferredScreen,
386 int fallbackStartScreen,
387 ArrayList<Long> workspaceScreens,
388 ArrayList<Long> addedWorkspaceScreensFinal,
389 int spanX, int spanY) {
390 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
391 // loadWorkspace() may not have been called.
392 final ContentResolver cr = context.getContentResolver();
393 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
394 new String[] {
395 LauncherSettings.Favorites.SCREEN,
396 LauncherSettings.Favorites.CELLX,
397 LauncherSettings.Favorites.CELLY,
398 LauncherSettings.Favorites.SPANX,
399 LauncherSettings.Favorites.SPANY,
400 LauncherSettings.Favorites.CONTAINER
401 },
402 "container=?",
403 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
404 null);
405
406 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
407 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
408 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
409 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
410 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
411 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
412 try {
413 while (c.moveToNext()) {
414 Rect rect = new Rect();
415 rect.left = c.getInt(cellXIndex);
416 rect.top = c.getInt(cellYIndex);
417 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
418 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
419
420 long screenId = c.getInt(screenIndex);
421 ArrayList<Rect> items = screenItems.get(screenId);
422 if (items == null) {
423 items = new ArrayList<Rect>();
424 screenItems.put(screenId, items);
425 }
426 items.add(rect);
427 }
428 } catch (Exception e) {
429 screenItems.clear();
430 } finally {
431 c.close();
432 }
433
434 // Find appropriate space for the item.
435 long screenId = 0;
436 int[] cordinates = new int[2];
437 boolean found = false;
438
439 int screenCount = workspaceScreens.size();
440 // First check the preferred screen.
441 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
442 if (preferredScreenIndex < screenCount) {
443 screenId = workspaceScreens.get(preferredScreenIndex);
444 found = findNextAvailableIconSpaceInScreen(
445 screenItems.get(screenId), cordinates, spanX, spanY);
446 }
447
448 if (!found) {
449 // Search on any of the screens.
450 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
451 screenId = workspaceScreens.get(screen);
452 if (findNextAvailableIconSpaceInScreen(
453 screenItems.get(screenId), cordinates, spanX, spanY)) {
454 // We found a space for it
455 found = true;
456 break;
457 }
458 }
459 }
460
461 if (!found) {
462 // Still no position found. Add a new screen to the end.
463 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
464
465 // Save the screen id for binding in the workspace
466 workspaceScreens.add(screenId);
467 addedWorkspaceScreensFinal.add(screenId);
468
469 // If we still can't find an empty space, then God help us all!!!
470 if (!findNextAvailableIconSpaceInScreen(
471 screenItems.get(screenId), cordinates, spanX, spanY)) {
472 throw new RuntimeException("Can't find space to add the item");
473 }
474 }
475 return Pair.create(screenId, cordinates);
476 }
477
478 /**
479 * Adds the provided items to the workspace.
480 * @param preferredScreen the screen where we should try to add the app first
481 * @param fallbackStartScreen the screen to start search for empty space if
482 * preferredScreen is not available.
483 */
484 public void addAndBindPendingItem(
485 final Context context,
486 final PendingAddItemInfo addInfo,
487 final ScreenPosProvider preferredScreen,
488 final int fallbackStartScreen) {
489 final Callbacks callbacks = getCallback();
490 // Process the newly added applications and add them to the database first
491 Runnable r = new Runnable() {
492 public void run() {
493 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
494
495 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
496 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
497 for (Integer i : orderedScreens.keySet()) {
498 long screenId = orderedScreens.get(i);
499 workspaceScreens.add(screenId);
500 }
501
502 // Find appropriate space for the item.
503 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
504 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
505 addInfo.spanX,
506 addInfo.spanY);
507 final long screenId = coords.first;
508 final int[] cordinates = coords.second;
509
510 // Update the workspace screens
511 updateWorkspaceScreenOrder(context, workspaceScreens);
512 runOnMainThread(new Runnable() {
513 public void run() {
514 Callbacks cb = getCallback();
515 if (callbacks == cb && cb != null) {
516 cb.bindAddScreens(addedWorkspaceScreensFinal);
517 cb.bindAddPendingItem(addInfo,
518 LauncherSettings.Favorites.CONTAINER_DESKTOP,
519 screenId, cordinates, addInfo.spanX, addInfo.spanY);
520 }
521 }
522 });
523 }
524 };
525 runOnWorkerThread(r);
526 }
527
528 /**
529 * Adds the provided items to the workspace.
530 * @param preferredScreen the screen where we should try to add the app first
531 * @param fallbackStartScreen the screen to start search for empty space if
532 * preferredScreen is not available.
533 */
534 public void addAndBindAddedWorkspaceApps(final Context context,
535 final ArrayList<ItemInfo> workspaceApps,
536 final ScreenPosProvider preferredScreen,
537 final int fallbackStartScreen,
538 final boolean allowDuplicate) {
539 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800540 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700541 return;
Winson Chung997a9232013-07-24 15:33:46 -0700542 }
Winson Chung64359a52013-07-08 17:17:08 -0700543 // Process the newly added applications and add them to the database first
544 Runnable r = new Runnable() {
545 public void run() {
546 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
547 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
548
Winson Chung76828c82013-08-19 15:43:29 -0700549 // Get the list of workspace screens. We need to append to this list and
550 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
551 // called.
552 ArrayList<Long> workspaceScreens = new ArrayList<Long>();
553 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
554 for (Integer i : orderedScreens.keySet()) {
555 long screenId = orderedScreens.get(i);
556 workspaceScreens.add(screenId);
557 }
558
Winson Chung64359a52013-07-08 17:17:08 -0700559 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800560 for (ItemInfo item : workspaceApps) {
561 if (!allowDuplicate) {
562 // Short-circuit this logic if the icon exists somewhere on the workspace
563 if (shortcutExists(context, item.title.toString(),
564 item.getIntent(), item.user)) {
565 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700566 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800567 }
Winson Chung76828c82013-08-19 15:43:29 -0700568
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800569 // Find appropriate space for the item.
570 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
571 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
572 1, 1);
573 long screenId = coords.first;
574 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700575
Winson Chung997a9232013-07-24 15:33:46 -0700576 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800577 if (item instanceof ShortcutInfo) {
578 shortcutInfo = (ShortcutInfo) item;
579 } else if (item instanceof AppInfo) {
580 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700581 } else {
582 throw new RuntimeException("Unexpected info type");
583 }
Winson Chung94d67682013-09-25 16:29:40 -0700584
Winson Chung64359a52013-07-08 17:17:08 -0700585 // Add the shortcut to the db
586 addItemToDatabase(context, shortcutInfo,
587 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800588 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700589 // Save the ShortcutInfo for binding in the workspace
590 addedShortcutsFinal.add(shortcutInfo);
591 }
592 }
593
Winson Chung76828c82013-08-19 15:43:29 -0700594 // Update the workspace screens
595 updateWorkspaceScreenOrder(context, workspaceScreens);
596
Adam Cohen76a47a12014-02-05 11:47:43 -0800597 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700598 runOnMainThread(new Runnable() {
599 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800600 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700601 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700602 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
603 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700604 if (!addedShortcutsFinal.isEmpty()) {
605 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
606 long lastScreenId = info.screenId;
607 for (ItemInfo i : addedShortcutsFinal) {
608 if (i.screenId == lastScreenId) {
609 addAnimated.add(i);
610 } else {
611 addNotAnimated.add(i);
612 }
Winson Chung997a9232013-07-24 15:33:46 -0700613 }
614 }
Winson Chungd64d1762013-08-20 14:37:16 -0700615 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800616 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700617 }
Winson Chung64359a52013-07-08 17:17:08 -0700618 }
Winson Chung997a9232013-07-24 15:33:46 -0700619 });
620 }
Winson Chung64359a52013-07-08 17:17:08 -0700621 }
622 };
623 runOnWorkerThread(r);
624 }
625
Winson Chung81b52252012-08-27 15:34:29 -0700626 public void unbindItemInfosAndClearQueuedBindRunnables() {
627 if (sWorkerThread.getThreadId() == Process.myTid()) {
628 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
629 "main thread");
630 }
631
632 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400633 synchronized (mDeferredBindRunnables) {
634 mDeferredBindRunnables.clear();
635 }
Winson Chung81b52252012-08-27 15:34:29 -0700636 // Remove any queued bind runnables
637 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
638 // Unbind all the workspace items
639 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700640 }
641
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700642 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700643 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700644 // Ensure that we don't use the same workspace items data structure on the main thread
645 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700646 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
647 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700648 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700649 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
650 tmpAppWidgets.addAll(sBgAppWidgets);
651 }
652 Runnable r = new Runnable() {
653 @Override
654 public void run() {
655 for (ItemInfo item : tmpWorkspaceItems) {
656 item.unbind();
657 }
658 for (ItemInfo item : tmpAppWidgets) {
659 item.unbind();
660 }
661 }
662 };
663 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700664 }
665
Joe Onorato9c1289c2009-08-17 11:03:03 -0400666 /**
667 * Adds an item to the DB if it was not created previously, or move it to a new
668 * <container, screen, cellX, cellY>
669 */
670 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700671 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400672 if (item.container == ItemInfo.NO_ID) {
673 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700674 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400675 } else {
676 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700677 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 }
679 }
680
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700681 static void checkItemInfoLocked(
682 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
683 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
684 if (modelItem != null && item != modelItem) {
685 // check all the data is consistent
686 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
687 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
688 ShortcutInfo shortcut = (ShortcutInfo) item;
689 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
690 modelShortcut.intent.filterEquals(shortcut.intent) &&
691 modelShortcut.id == shortcut.id &&
692 modelShortcut.itemType == shortcut.itemType &&
693 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700694 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700695 modelShortcut.cellX == shortcut.cellX &&
696 modelShortcut.cellY == shortcut.cellY &&
697 modelShortcut.spanX == shortcut.spanX &&
698 modelShortcut.spanY == shortcut.spanY &&
699 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
700 (modelShortcut.dropPos != null &&
701 shortcut.dropPos != null &&
702 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
703 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
704 // For all intents and purposes, this is the same object
705 return;
706 }
707 }
708
709 // the modelItem needs to match up perfectly with item if our model is
710 // to be consistent with the database-- for now, just require
711 // modelItem == item or the equality check above
712 String msg = "item: " + ((item != null) ? item.toString() : "null") +
713 "modelItem: " +
714 ((modelItem != null) ? modelItem.toString() : "null") +
715 "Error: ItemInfo passed to checkItemInfo doesn't match original";
716 RuntimeException e = new RuntimeException(msg);
717 if (stackTrace != null) {
718 e.setStackTrace(stackTrace);
719 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800720 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700721 }
722 }
723
Michael Jurka816474f2012-06-25 14:49:02 -0700724 static void checkItemInfo(final ItemInfo item) {
725 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
726 final long itemId = item.id;
727 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700728 public void run() {
729 synchronized (sBgLock) {
730 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700731 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700732 }
733 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700734 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700735 }
736
Michael Jurkac9d95c52011-08-29 14:03:34 -0700737 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
738 final ItemInfo item, final String callingFunction) {
739 final long itemId = item.id;
740 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
741 final ContentResolver cr = context.getContentResolver();
742
Adam Cohen487f7dd2012-06-28 18:12:10 -0700743 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700744 Runnable r = new Runnable() {
745 public void run() {
746 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700747 updateItemArrays(item, itemId, stackTrace);
748 }
749 };
750 runOnWorkerThread(r);
751 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700752
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700753 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
754 final ArrayList<ItemInfo> items, final String callingFunction) {
755 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700756
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700757 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
758 Runnable r = new Runnable() {
759 public void run() {
760 ArrayList<ContentProviderOperation> ops =
761 new ArrayList<ContentProviderOperation>();
762 int count = items.size();
763 for (int i = 0; i < count; i++) {
764 ItemInfo item = items.get(i);
765 final long itemId = item.id;
766 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
767 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700768
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700769 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
770 updateItemArrays(item, itemId, stackTrace);
771
772 }
773 try {
774 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
775 } catch (Exception e) {
776 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700777 }
778 }
779 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700780 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700781 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700782
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700783 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
784 // Lock on mBgLock *after* the db operation
785 synchronized (sBgLock) {
786 checkItemInfoLocked(itemId, item, stackTrace);
787
788 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
789 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
790 // Item is in a folder, make sure this folder exists
791 if (!sBgFolders.containsKey(item.container)) {
792 // An items container is being set to a that of an item which is not in
793 // the list of Folders.
794 String msg = "item: " + item + " container being set to: " +
795 item.container + ", not in the list of folders";
796 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700797 }
798 }
799
800 // Items are added/removed from the corresponding FolderInfo elsewhere, such
801 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
802 // that are on the desktop, as appropriate
803 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800804 if (modelItem != null &&
805 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
806 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700807 switch (modelItem.itemType) {
808 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
809 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
810 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
811 if (!sBgWorkspaceItems.contains(modelItem)) {
812 sBgWorkspaceItems.add(modelItem);
813 }
814 break;
815 default:
816 break;
817 }
818 } else {
819 sBgWorkspaceItems.remove(modelItem);
820 }
821 }
822 }
823
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400825 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700826 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700827 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400829 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400830 item.cellX = cellX;
831 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700832
Winson Chung3d503fb2011-07-13 17:25:49 -0700833 // We store hotseat items in canonical form which is this orientation invariant position
834 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700835 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700836 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700837 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700838 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700839 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700840 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400841
842 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400843 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700844 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
845 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800846 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700847 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400848
Michael Jurkac9d95c52011-08-29 14:03:34 -0700849 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700850 }
851
852 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700853 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
854 * cellX, cellY have already been updated on the ItemInfos.
855 */
856 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
857 final long container, final int screen) {
858
859 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
860 int count = items.size();
861
862 for (int i = 0; i < count; i++) {
863 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700864 item.container = container;
865
866 // We store hotseat items in canonical form which is this orientation invariant position
867 // in the hotseat
868 if (context instanceof Launcher && screen < 0 &&
869 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700870 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700871 item.cellY);
872 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700873 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700874 }
875
876 final ContentValues values = new ContentValues();
877 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
878 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
879 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800880 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700881 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700882
883 contentValues.add(values);
884 }
885 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
886 }
887
888 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700889 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800890 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700891 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700892 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700893 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800894 item.cellX = cellX;
895 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700896 item.spanX = spanX;
897 item.spanY = spanY;
898
899 // We store hotseat items in canonical form which is this orientation invariant position
900 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700901 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700902 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700903 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700904 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700905 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700906 }
Adam Cohend4844c32011-02-18 19:25:06 -0800907
Adam Cohend4844c32011-02-18 19:25:06 -0800908 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800909 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700910 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
911 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800912 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700913 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
914 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700915 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800916
Michael Jurka816474f2012-06-25 14:49:02 -0700917 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700918 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700919
920 /**
921 * Update an item to the database in a specified container.
922 */
923 static void updateItemInDatabase(Context context, final ItemInfo item) {
924 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100925 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700926 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800927 }
928
929 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400930 * Returns true if the shortcuts already exists in the database.
931 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800932 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800933 static boolean shortcutExists(Context context, String title, Intent intent,
934 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400935 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700936 final Intent intentWithPkg, intentWithoutPkg;
937
938 if (intent.getComponent() != null) {
939 // If component is not null, an intent with null package will produce
940 // the same result and should also be a match.
941 if (intent.getPackage() != null) {
942 intentWithPkg = intent;
943 intentWithoutPkg = new Intent(intent).setPackage(null);
944 } else {
945 intentWithPkg = new Intent(intent).setPackage(
946 intent.getComponent().getPackageName());
947 intentWithoutPkg = intent;
948 }
949 } else {
950 intentWithPkg = intent;
951 intentWithoutPkg = intent;
952 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800953 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
954 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400955 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800956 new String[] { "title", "intent", "profileId" },
957 "title=? and (intent=? or intent=?) and profileId=?",
958 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
959 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400960 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800961 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400962 } finally {
963 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800964 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700965 }
966
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 /**
968 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
969 */
970 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
971 final ContentResolver cr = context.getContentResolver();
972 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
973 "_id=? and (itemType=? or itemType=?)",
974 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700975 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700976
Joe Onorato9c1289c2009-08-17 11:03:03 -0400977 try {
978 if (c.moveToFirst()) {
979 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
980 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
981 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
982 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
983 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
984 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800985
Joe Onorato9c1289c2009-08-17 11:03:03 -0400986 FolderInfo folderInfo = null;
987 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700988 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
989 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700991 }
992
Joe Onorato9c1289c2009-08-17 11:03:03 -0400993 folderInfo.title = c.getString(titleIndex);
994 folderInfo.id = id;
995 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700997 folderInfo.cellX = c.getInt(cellXIndex);
998 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999
1000 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001001 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001002 } finally {
1003 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001004 }
1005
1006 return null;
1007 }
1008
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009 /**
1010 * Add an item to the database in a specified container. Sets the container, screen, cellX and
1011 * cellY fields of the item. Also assigns an ID to the item.
1012 */
Winson Chung3d503fb2011-07-13 17:25:49 -07001013 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -07001014 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001015 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001016 item.cellX = cellX;
1017 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001018 // We store hotseat items in canonical form which is this orientation invariant position
1019 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001020 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001021 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001023 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001024 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001025 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001026
1027 final ContentValues values = new ContentValues();
1028 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001029 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001030
Michael Jurka414300a2013-08-27 15:42:35 +02001031 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001032 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001033
Jason Monk8e19cf22014-03-20 15:06:57 -04001034 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001035 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036 public void run() {
1037 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1038 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001039
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001041 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001042 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001043 sBgItemsIdMap.put(item.id, item);
1044 switch (item.itemType) {
1045 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1046 sBgFolders.put(item.id, (FolderInfo) item);
1047 // Fall through
1048 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1049 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1050 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1051 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1052 sBgWorkspaceItems.add(item);
1053 } else {
1054 if (!sBgFolders.containsKey(item.container)) {
1055 // Adding an item to a folder that doesn't exist.
1056 String msg = "adding item: " + item + " to a folder that " +
1057 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001058 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001059 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001060 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001061 break;
1062 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1063 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1064 break;
1065 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001066 }
1067 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001068 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001069 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001070 }
1071
Joe Onorato9c1289c2009-08-17 11:03:03 -04001072 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001073 * Creates a new unique child id, for a given cell span across all layouts.
1074 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001075 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001077 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001078 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001079 }
1080
Sunny Goyal34942622014-08-29 17:20:55 -07001081 private static ArrayList<ItemInfo> getItemsByPackageName(
1082 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001083 ItemInfoFilter filter = new ItemInfoFilter() {
1084 @Override
1085 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1086 return cn.getPackageName().equals(pn) && info.user.equals(user);
1087 }
1088 };
Sunny Goyal34942622014-08-29 17:20:55 -07001089 return filterItemInfos(sBgItemsIdMap.values(), filter);
1090 }
1091
1092 /**
1093 * Removes all the items from the database corresponding to the specified package.
1094 */
1095 static void deletePackageFromDatabase(Context context, final String pn,
1096 final UserHandleCompat user) {
1097 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001098 }
1099
1100 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001101 * Removes the specified item from the database
1102 * @param context
1103 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001104 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001105 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001106 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1107 items.add(item);
1108 deleteItemsFromDatabase(context, items);
1109 }
1110
1111 /**
1112 * Removes the specified items from the database
1113 * @param context
1114 * @param item
1115 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001116 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001117 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001118
Michael Jurka83df1882011-08-31 20:59:26 -07001119 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001120 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001121 for (ItemInfo item : items) {
1122 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1123 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001124
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001125 // Lock on mBgLock *after* the db operation
1126 synchronized (sBgLock) {
1127 switch (item.itemType) {
1128 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1129 sBgFolders.remove(item.id);
1130 for (ItemInfo info: sBgItemsIdMap.values()) {
1131 if (info.container == item.id) {
1132 // We are deleting a folder which still contains items that
1133 // think they are contained by that folder.
1134 String msg = "deleting a folder (" + item + ") which still " +
1135 "contains items (" + info + ")";
1136 Log.e(TAG, msg);
1137 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001138 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001139 sBgWorkspaceItems.remove(item);
1140 break;
1141 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1142 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1143 sBgWorkspaceItems.remove(item);
1144 break;
1145 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1146 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1147 break;
1148 }
1149 sBgItemsIdMap.remove(item.id);
1150 sBgDbIconCache.remove(item);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001151 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001152 }
1153 }
Michael Jurka83df1882011-08-31 20:59:26 -07001154 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001155 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001156 }
1157
1158 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001159 * Update the order of the workspace screens in the database. The array list contains
1160 * a list of screen ids in the order that they should appear.
1161 */
Winson Chungc9168342013-06-26 14:54:55 -07001162 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001163 // Log to disk
1164 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1165 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1166
Winson Chung64359a52013-07-08 17:17:08 -07001167 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 final ContentResolver cr = context.getContentResolver();
1169 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1170
1171 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001172 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001173 while (iter.hasNext()) {
1174 long id = iter.next();
1175 if (id < 0) {
1176 iter.remove();
1177 }
1178 }
1179
1180 Runnable r = new Runnable() {
1181 @Override
1182 public void run() {
Yura085c8532014-02-11 15:15:29 +00001183 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001184 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001185 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001186 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001187 for (int i = 0; i < count; i++) {
1188 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001189 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001190 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1191 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001192 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001193 }
Yura085c8532014-02-11 15:15:29 +00001194
1195 try {
1196 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1197 } catch (Exception ex) {
1198 throw new RuntimeException(ex);
1199 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001200
Winson Chungba9c37f2013-08-30 14:11:37 -07001201 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001202 sBgWorkspaceScreens.clear();
1203 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001204 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001205 }
1206 };
1207 runOnWorkerThread(r);
1208 }
1209
1210 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001211 * Remove the contents of the specified folder from the database
1212 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001213 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001214 final ContentResolver cr = context.getContentResolver();
1215
Michael Jurkac9d95c52011-08-29 14:03:34 -07001216 Runnable r = new Runnable() {
1217 public void run() {
1218 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001219 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001220 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001221 sBgItemsIdMap.remove(info.id);
1222 sBgFolders.remove(info.id);
1223 sBgDbIconCache.remove(info);
1224 sBgWorkspaceItems.remove(info);
1225 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001226
Michael Jurkac9d95c52011-08-29 14:03:34 -07001227 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1228 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001229 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001230 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001231 for (ItemInfo childInfo : info.contents) {
1232 sBgItemsIdMap.remove(childInfo.id);
1233 sBgDbIconCache.remove(childInfo);
1234 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001235 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001236 }
1237 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001238 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001239 }
1240
1241 /**
1242 * Set this as the current Launcher activity object for the loader.
1243 */
1244 public void initialize(Callbacks callbacks) {
1245 synchronized (mLock) {
1246 mCallbacks = new WeakReference<Callbacks>(callbacks);
1247 }
1248 }
1249
Kenny Guyed131872014-04-30 03:02:21 +01001250 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001251 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001252 int op = PackageUpdatedTask.OP_UPDATE;
1253 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1254 user));
1255 }
1256
1257 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001258 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001259 int op = PackageUpdatedTask.OP_REMOVE;
1260 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1261 user));
1262 }
1263
1264 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001265 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001266 int op = PackageUpdatedTask.OP_ADD;
1267 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1268 user));
1269 }
1270
1271 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001272 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001273 boolean replacing) {
1274 if (!replacing) {
1275 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1276 user));
1277 if (mAppsCanBeOnRemoveableStorage) {
1278 // Only rebind if we support removable storage. It catches the
1279 // case where
1280 // apps on the external sd card need to be reloaded
1281 startLoaderFromBackground();
1282 }
1283 } else {
1284 // If we are replacing then just update the packages in the list
1285 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1286 packageNames, user));
1287 }
1288 }
1289
1290 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001291 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001292 boolean replacing) {
1293 if (!replacing) {
1294 enqueuePackageUpdated(new PackageUpdatedTask(
1295 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1296 user));
1297 }
Kenny Guyed131872014-04-30 03:02:21 +01001298 }
1299
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001300 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001301 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1302 * ACTION_PACKAGE_CHANGED.
1303 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001304 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001305 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001306 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001307
Joe Onorato36115782010-06-17 13:28:48 -04001308 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001309 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001310 // If we have changed locale we need to clear out the labels in all apps/workspace.
1311 forceReload();
1312 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1313 // Check if configuration change was an mcc/mnc change which would affect app resources
1314 // and we would need to clear out the labels in all apps/workspace. Same handling as
1315 // above for ACTION_LOCALE_CHANGED
1316 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001317 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001318 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001319 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001320 forceReload();
1321 }
1322 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001323 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001324 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1325 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001326 Callbacks callbacks = getCallback();
1327 if (callbacks != null) {
1328 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001329 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001330 }
1331 }
1332
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001333 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001334 resetLoadedState(true, true);
1335
Reena Lee93f824a2011-09-23 17:20:28 -07001336 // Do this here because if the launcher activity is running it will be restarted.
1337 // If it's not running startLoaderFromBackground will merely tell it that it needs
1338 // to reload.
1339 startLoaderFromBackground();
1340 }
1341
Winson Chungf0c6ae02012-03-21 16:10:31 -07001342 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1343 synchronized (mLock) {
1344 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1345 // mWorkspaceLoaded to true later
1346 stopLoaderLocked();
1347 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1348 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1349 }
1350 }
1351
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001352 /**
1353 * When the launcher is in the background, it's possible for it to miss paired
1354 * configuration changes. So whenever we trigger the loader from the background
1355 * tell the launcher that it needs to re-run the loader when it comes back instead
1356 * of doing it now.
1357 */
1358 public void startLoaderFromBackground() {
1359 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001360 Callbacks callbacks = getCallback();
1361 if (callbacks != null) {
1362 // Only actually run the loader if they're not paused.
1363 if (!callbacks.setLoadOnResume()) {
1364 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001365 }
1366 }
1367 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001368 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001369 }
Joe Onorato36115782010-06-17 13:28:48 -04001370 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001371
Reena Lee93f824a2011-09-23 17:20:28 -07001372 // If there is already a loader task running, tell it to stop.
1373 // returns true if isLaunching() was true on the old task
1374 private boolean stopLoaderLocked() {
1375 boolean isLaunching = false;
1376 LoaderTask oldTask = mLoaderTask;
1377 if (oldTask != null) {
1378 if (oldTask.isLaunching()) {
1379 isLaunching = true;
1380 }
1381 oldTask.stopLocked();
1382 }
1383 return isLaunching;
1384 }
1385
Adam Cohen1a85c582014-09-30 09:48:49 -07001386 public boolean isCurrentCallbacks(Callbacks callbacks) {
1387 return (mCallbacks != null && mCallbacks.get() == callbacks);
1388 }
1389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001391 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1392 }
1393
1394 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001395 synchronized (mLock) {
1396 if (DEBUG_LOADERS) {
1397 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1398 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001399
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001400 // Clear any deferred bind-runnables from the synchronized load process
1401 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001402 synchronized (mDeferredBindRunnables) {
1403 mDeferredBindRunnables.clear();
1404 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001405
Joe Onorato36115782010-06-17 13:28:48 -04001406 // Don't bother to start the thread if we know it's not going to do anything
1407 if (mCallbacks != null && mCallbacks.get() != null) {
1408 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001409 // also, don't downgrade isLaunching if we're already running
1410 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001411 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001412 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1413 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001414 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1415 } else {
1416 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1417 sWorker.post(mLoaderTask);
1418 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001419 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001420 }
1421 }
1422
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001423 void bindRemainingSynchronousPages() {
1424 // Post the remaining side pages to be loaded
1425 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001426 Runnable[] deferredBindRunnables = null;
1427 synchronized (mDeferredBindRunnables) {
1428 deferredBindRunnables = mDeferredBindRunnables.toArray(
1429 new Runnable[mDeferredBindRunnables.size()]);
1430 mDeferredBindRunnables.clear();
1431 }
1432 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001433 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001434 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001435 }
1436 }
1437
Joe Onorato36115782010-06-17 13:28:48 -04001438 public void stopLoader() {
1439 synchronized (mLock) {
1440 if (mLoaderTask != null) {
1441 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001442 }
1443 }
Joe Onorato36115782010-06-17 13:28:48 -04001444 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001445
Winson Chung76828c82013-08-19 15:43:29 -07001446 /** Loads the workspace screens db into a map of Rank -> ScreenId */
1447 private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
1448 final ContentResolver contentResolver = context.getContentResolver();
1449 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1450 final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
1451 TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
1452
1453 try {
1454 final int idIndex = sc.getColumnIndexOrThrow(
1455 LauncherSettings.WorkspaceScreens._ID);
1456 final int rankIndex = sc.getColumnIndexOrThrow(
1457 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1458 while (sc.moveToNext()) {
1459 try {
1460 long screenId = sc.getLong(idIndex);
1461 int rank = sc.getInt(rankIndex);
Winson Chung76828c82013-08-19 15:43:29 -07001462 orderedScreens.put(rank, screenId);
1463 } catch (Exception e) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001464 Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001465 }
1466 }
1467 } finally {
1468 sc.close();
1469 }
Winson Chunga90303b2013-11-15 13:05:06 -08001470
1471 // Log to disk
1472 Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
1473 ArrayList<String> orderedScreensPairs= new ArrayList<String>();
1474 for (Integer i : orderedScreens.keySet()) {
1475 orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
1476 }
1477 Launcher.addDumpLog(TAG, "11683562 - screens: " +
1478 TextUtils.join(", ", orderedScreensPairs), true);
Winson Chung76828c82013-08-19 15:43:29 -07001479 return orderedScreens;
1480 }
1481
Michael Jurkac57b7a82011-08-09 22:02:20 -07001482 public boolean isAllAppsLoaded() {
1483 return mAllAppsLoaded;
1484 }
1485
Winson Chung36a62fe2012-05-06 18:04:42 -07001486 boolean isLoadingWorkspace() {
1487 synchronized (mLock) {
1488 if (mLoaderTask != null) {
1489 return mLoaderTask.isLoadingWorkspace();
1490 }
1491 }
1492 return false;
1493 }
1494
Joe Onorato36115782010-06-17 13:28:48 -04001495 /**
1496 * Runnable for the thread that loads the contents of the launcher:
1497 * - workspace icons
1498 * - widgets
1499 * - all apps icons
1500 */
1501 private class LoaderTask implements Runnable {
1502 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001503 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001504 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001505 private boolean mStopped;
1506 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001507 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001508
Winson Chungc3eecff2011-07-11 17:44:15 -07001509 private HashMap<Object, CharSequence> mLabelCache;
Joe Onorato36115782010-06-17 13:28:48 -04001510
Dan Sandlerd5024042014-01-09 15:01:33 -05001511 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001512 mContext = context;
1513 mIsLaunching = isLaunching;
Winson Chungc3eecff2011-07-11 17:44:15 -07001514 mLabelCache = new HashMap<Object, CharSequence>();
Dan Sandlerd5024042014-01-09 15:01:33 -05001515 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001516 }
1517
Joe Onorato36115782010-06-17 13:28:48 -04001518 boolean isLaunching() {
1519 return mIsLaunching;
1520 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001521
Winson Chung36a62fe2012-05-06 18:04:42 -07001522 boolean isLoadingWorkspace() {
1523 return mIsLoadingAndBindingWorkspace;
1524 }
1525
Winson Chungc763c4e2013-07-19 13:49:06 -07001526 /** Returns whether this is an upgrade path */
1527 private boolean loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001528 mIsLoadingAndBindingWorkspace = true;
1529
Joe Onorato36115782010-06-17 13:28:48 -04001530 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001531 if (DEBUG_LOADERS) {
1532 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001533 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001534
Winson Chungc763c4e2013-07-19 13:49:06 -07001535 boolean isUpgradePath = false;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001536 if (!mWorkspaceLoaded) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001537 isUpgradePath = loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001538 synchronized (LoaderTask.this) {
1539 if (mStopped) {
Winson Chungc763c4e2013-07-19 13:49:06 -07001540 return isUpgradePath;
Reena Lee93f824a2011-09-23 17:20:28 -07001541 }
1542 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001543 }
1544 }
1545
Joe Onorato36115782010-06-17 13:28:48 -04001546 // Bind the workspace
Winson Chungc763c4e2013-07-19 13:49:06 -07001547 bindWorkspace(-1, isUpgradePath);
1548 return isUpgradePath;
Joe Onorato36115782010-06-17 13:28:48 -04001549 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001550
Joe Onorato36115782010-06-17 13:28:48 -04001551 private void waitForIdle() {
1552 // Wait until the either we're stopped or the other threads are done.
1553 // This way we don't start loading all apps until the workspace has settled
1554 // down.
1555 synchronized (LoaderTask.this) {
1556 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001557
Joe Onorato36115782010-06-17 13:28:48 -04001558 mHandler.postIdle(new Runnable() {
1559 public void run() {
1560 synchronized (LoaderTask.this) {
1561 mLoadAndBindStepFinished = true;
1562 if (DEBUG_LOADERS) {
1563 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001564 }
Joe Onorato36115782010-06-17 13:28:48 -04001565 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001566 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001567 }
Joe Onorato36115782010-06-17 13:28:48 -04001568 });
1569
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001570 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001571 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001572 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1573 // wait no longer than 1sec at a time
1574 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001575 } catch (InterruptedException ex) {
1576 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001577 }
1578 }
Joe Onorato36115782010-06-17 13:28:48 -04001579 if (DEBUG_LOADERS) {
1580 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001581 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001582 + "ms for previous step to finish binding");
1583 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001584 }
Joe Onorato36115782010-06-17 13:28:48 -04001585 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001586
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001587 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001588 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 // Ensure that we have a valid page index to load synchronously
1590 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1591 "valid page index");
1592 }
1593 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1594 // Ensure that we don't try and bind a specified page when the pages have not been
1595 // loaded already (we should load everything asynchronously in that case)
1596 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1597 }
1598 synchronized (mLock) {
1599 if (mIsLoaderTaskRunning) {
1600 // Ensure that we are never running the background loading at this point since
1601 // we also touch the background collections
1602 throw new RuntimeException("Error! Background loading is already running");
1603 }
1604 }
1605
1606 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1607 // data structures, we can't allow any other thread to touch that data, but because
1608 // this call is synchronous, we can get away with not locking).
1609
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001610 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001611 // operations from the previous activity. We need to ensure that all queued operations
1612 // are executed before any synchronous binding work is done.
1613 mHandler.flush();
1614
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001615 // Divide the set of loaded items into those that we are binding synchronously, and
1616 // everything else that is to be bound normally (asynchronously).
Winson Chungc763c4e2013-07-19 13:49:06 -07001617 bindWorkspace(synchronousBindPage, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001618 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1619 // arise from that.
1620 onlyBindAllApps();
1621 }
1622
Joe Onorato36115782010-06-17 13:28:48 -04001623 public void run() {
Winson Chungc763c4e2013-07-19 13:49:06 -07001624 boolean isUpgrade = false;
1625
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001626 synchronized (mLock) {
1627 mIsLoaderTaskRunning = true;
1628 }
Joe Onorato36115782010-06-17 13:28:48 -04001629 // Optimize for end-user experience: if the Launcher is up and // running with the
1630 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1631 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001632 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001633 // Elevate priority when Home launches for the first time to avoid
1634 // starving at boot time. Staring at a blank home is not cool.
1635 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001636 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1637 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001638 android.os.Process.setThreadPriority(mIsLaunching
1639 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1640 }
Winson Chung64359a52013-07-08 17:17:08 -07001641 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Winson Chungc763c4e2013-07-19 13:49:06 -07001642 isUpgrade = loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001643
Joe Onorato36115782010-06-17 13:28:48 -04001644 if (mStopped) {
1645 break keep_running;
1646 }
1647
1648 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1649 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001650 synchronized (mLock) {
1651 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001652 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001653 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654 }
1655 }
Joe Onorato36115782010-06-17 13:28:48 -04001656 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001657
1658 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001659 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1660 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001661
1662 // Restore the default thread priority after we are done loading items
1663 synchronized (mLock) {
1664 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1665 }
Joe Onorato36115782010-06-17 13:28:48 -04001666 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001667
Winson Chungaac01e12011-08-17 10:37:13 -07001668 // Update the saved icons if necessary
1669 if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
Winson Chung2abf94d2012-07-18 18:16:38 -07001670 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001671 for (Object key : sBgDbIconCache.keySet()) {
1672 updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
1673 }
1674 sBgDbIconCache.clear();
Winson Chungaac01e12011-08-17 10:37:13 -07001675 }
Winson Chungaac01e12011-08-17 10:37:13 -07001676
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001677 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001678 // Ensure that all the applications that are in the system are
1679 // represented on the home screen.
Winson Chungc58497e2013-09-03 17:48:37 -07001680 if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Winson Chungc58497e2013-09-03 17:48:37 -07001681 verifyApplications();
1682 }
Winson Chungc763c4e2013-07-19 13:49:06 -07001683 }
1684
Joe Onorato36115782010-06-17 13:28:48 -04001685 // Clear out this reference, otherwise we end up holding it until all of the
1686 // callback runnables are done.
1687 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001688
Joe Onorato36115782010-06-17 13:28:48 -04001689 synchronized (mLock) {
1690 // If we are still the last one to be scheduled, remove ourselves.
1691 if (mLoaderTask == this) {
1692 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001693 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001694 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001695 }
Joe Onorato36115782010-06-17 13:28:48 -04001696 }
1697
1698 public void stopLocked() {
1699 synchronized (LoaderTask.this) {
1700 mStopped = true;
1701 this.notify();
1702 }
1703 }
1704
1705 /**
1706 * Gets the callbacks object. If we've been stopped, or if the launcher object
1707 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1708 * object that was around when the deferred message was scheduled, and if there's
1709 * a new Callbacks object around then also return null. This will save us from
1710 * calling onto it with data that will be ignored.
1711 */
1712 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1713 synchronized (mLock) {
1714 if (mStopped) {
1715 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001716 }
Joe Onorato36115782010-06-17 13:28:48 -04001717
1718 if (mCallbacks == null) {
1719 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001720 }
Joe Onorato36115782010-06-17 13:28:48 -04001721
1722 final Callbacks callbacks = mCallbacks.get();
1723 if (callbacks != oldCallbacks) {
1724 return null;
1725 }
1726 if (callbacks == null) {
1727 Log.w(TAG, "no mCallbacks");
1728 return null;
1729 }
1730
1731 return callbacks;
1732 }
1733 }
1734
Winson Chungc763c4e2013-07-19 13:49:06 -07001735 private void verifyApplications() {
1736 final Context context = mApp.getContext();
1737
1738 // Cross reference all the applications in our apps list with items in the workspace
1739 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001740 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001741 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001742 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001743 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001744 if (tmpInfos.isEmpty()) {
1745 // We are missing an application icon, so add this to the workspace
1746 added.add(app);
1747 // This is a rare event, so lets log it
1748 Log.e(TAG, "Missing Application on load: " + app);
1749 }
1750 }
1751 }
1752 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001753 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001754 }
1755 }
1756
Joe Onorato36115782010-06-17 13:28:48 -04001757 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001758 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001759 LauncherAppState app = LauncherAppState.getInstance();
1760 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001761 final int countX = (int) grid.numColumns;
1762 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001763
Adam Cohendcd297f2013-06-18 13:13:40 -07001764 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001765 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001766 // Return early if we detect that an item is under the hotseat button
1767 if (mCallbacks == null ||
1768 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001769 Log.e(TAG, "Error loading shortcut into hotseat " + item
1770 + " into position (" + item.screenId + ":" + item.cellX + ","
1771 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001772 return false;
1773 }
1774
Dan Sandler295ae182013-12-10 16:05:47 -05001775 final ItemInfo[][] hotseatItems =
1776 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1777
Adam Cohenae4409d2013-11-26 10:34:59 -08001778 if (item.screenId >= grid.numHotseatIcons) {
1779 Log.e(TAG, "Error loading shortcut " + item
1780 + " into hotseat position " + item.screenId
1781 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1782 + ")");
1783 return false;
1784 }
1785
Dan Sandler295ae182013-12-10 16:05:47 -05001786 if (hotseatItems != null) {
1787 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001788 Log.e(TAG, "Error loading shortcut into hotseat " + item
1789 + " into position (" + item.screenId + ":" + item.cellX + ","
1790 + item.cellY + ") occupied by "
1791 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1792 [(int) item.screenId][0]);
1793 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001794 } else {
1795 hotseatItems[(int) item.screenId][0] = item;
1796 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001797 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001798 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001799 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001800 items[(int) item.screenId][0] = item;
1801 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001802 return true;
1803 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001804 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1805 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001806 return true;
1807 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001808
Adam Cohendcd297f2013-06-18 13:13:40 -07001809 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001810 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001811 occupied.put(item.screenId, items);
1812 }
1813
Dan Sandler295ae182013-12-10 16:05:47 -05001814 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001815 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1816 item.cellX < 0 || item.cellY < 0 ||
1817 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1818 Log.e(TAG, "Error loading shortcut " + item
1819 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1820 + item.cellX + "," + item.cellY
1821 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1822 return false;
1823 }
1824
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001825 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001826 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1827 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001828 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001829 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001830 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001831 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001832 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001834 return false;
1835 }
1836 }
1837 }
1838 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1839 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001840 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001841 }
1842 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001843
Joe Onorato36115782010-06-17 13:28:48 -04001844 return true;
1845 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001846
Winson Chungba9c37f2013-08-30 14:11:37 -07001847 /** Clears all the sBg data structures */
1848 private void clearSBgDataStructures() {
1849 synchronized (sBgLock) {
1850 sBgWorkspaceItems.clear();
1851 sBgAppWidgets.clear();
1852 sBgFolders.clear();
1853 sBgItemsIdMap.clear();
1854 sBgDbIconCache.clear();
1855 sBgWorkspaceScreens.clear();
1856 }
1857 }
1858
Dan Sandlerd5024042014-01-09 15:01:33 -05001859 /** Returns whether this is an upgrade path */
Winson Chungc763c4e2013-07-19 13:49:06 -07001860 private boolean loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001861 // Log to disk
1862 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1863
Joe Onorato36115782010-06-17 13:28:48 -04001864 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001865
Joe Onorato36115782010-06-17 13:28:48 -04001866 final Context context = mContext;
1867 final ContentResolver contentResolver = context.getContentResolver();
1868 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001869 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001870 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1871 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001872 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001873
Winson Chung892c74d2013-08-22 16:15:50 -07001874 LauncherAppState app = LauncherAppState.getInstance();
1875 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1876 int countX = (int) grid.numColumns;
1877 int countY = (int) grid.numRows;
1878
Dan Sandlerd5024042014-01-09 15:01:33 -05001879 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1880 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1881 LauncherAppState.getLauncherProvider().deleteDatabase();
1882 }
1883
1884 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1885 // append the user's Launcher2 shortcuts
1886 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1887 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1888 } else {
1889 // Make sure the default workspace is loaded
1890 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001891 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001892 }
Adam Cohene25af792013-06-06 23:08:25 -07001893
Adam Cohen71483f42014-05-15 14:04:01 -07001894 // This code path is for our old migration code and should no longer be exercised
1895 boolean loadedOldDb = false;
Dan Sandlerf0b8dac2013-11-19 12:21:25 -05001896
Winson Chung9f9f00b2013-11-15 13:27:00 -08001897 // Log to disk
1898 Launcher.addDumpLog(TAG, "11683562 - loadedOldDb: " + loadedOldDb, true);
Michael Jurkab85f8a42012-04-25 15:48:32 -07001899
Winson Chung2abf94d2012-07-18 18:16:38 -07001900 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001901 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001902 final HashSet<String> installingPkgs = PackageInstallerCompat
1903 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001904
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001906 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001907 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001908 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001909 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001910
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001911 // +1 for the hotseat (it can be larger than the workspace)
1912 // Load workspace in reverse order to ensure that latest items are loaded first (and
1913 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001914 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001915
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001916 try {
1917 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1918 final int intentIndex = c.getColumnIndexOrThrow
1919 (LauncherSettings.Favorites.INTENT);
1920 final int titleIndex = c.getColumnIndexOrThrow
1921 (LauncherSettings.Favorites.TITLE);
1922 final int iconTypeIndex = c.getColumnIndexOrThrow(
1923 LauncherSettings.Favorites.ICON_TYPE);
1924 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1925 final int iconPackageIndex = c.getColumnIndexOrThrow(
1926 LauncherSettings.Favorites.ICON_PACKAGE);
1927 final int iconResourceIndex = c.getColumnIndexOrThrow(
1928 LauncherSettings.Favorites.ICON_RESOURCE);
1929 final int containerIndex = c.getColumnIndexOrThrow(
1930 LauncherSettings.Favorites.CONTAINER);
1931 final int itemTypeIndex = c.getColumnIndexOrThrow(
1932 LauncherSettings.Favorites.ITEM_TYPE);
1933 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1934 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001935 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1936 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001937 final int screenIndex = c.getColumnIndexOrThrow(
1938 LauncherSettings.Favorites.SCREEN);
1939 final int cellXIndex = c.getColumnIndexOrThrow
1940 (LauncherSettings.Favorites.CELLX);
1941 final int cellYIndex = c.getColumnIndexOrThrow
1942 (LauncherSettings.Favorites.CELLY);
1943 final int spanXIndex = c.getColumnIndexOrThrow
1944 (LauncherSettings.Favorites.SPANX);
1945 final int spanYIndex = c.getColumnIndexOrThrow(
1946 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001947 final int rankIndex = c.getColumnIndexOrThrow(
1948 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001949 final int restoredIndex = c.getColumnIndexOrThrow(
1950 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001951 final int profileIdIndex = c.getColumnIndexOrThrow(
1952 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001953 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1954 //final int displayModeIndex = c.getColumnIndexOrThrow(
1955 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001956
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001957 ShortcutInfo info;
1958 String intentDescription;
1959 LauncherAppWidgetInfo appWidgetInfo;
1960 int container;
1961 long id;
1962 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001963 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001964
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001965 while (!mStopped && c.moveToNext()) {
1966 try {
1967 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001968 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001969 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001970
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001971 switch (itemType) {
1972 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1973 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001974 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001975 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001976 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001977 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001978 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001979 int disabledState = 0;
Kenny Guyed131872014-04-30 03:02:21 +01001980 if (user == null) {
1981 // User has been deleted remove the item.
1982 itemsToRemove.add(id);
1983 continue;
1984 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001985 try {
1986 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001987 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001988 if (cn != null && cn.getPackageName() != null) {
1989 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1990 cn.getPackageName(), user);
1991 boolean validComponent = validPkg &&
1992 launcherApps.isActivityEnabledForProfile(cn, user);
1993
1994 if (validComponent) {
1995 if (restored) {
1996 // no special handling necessary for this item
1997 restoredRows.add(id);
1998 restored = false;
1999 }
2000 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07002001 intent = null;
2002 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
2003 // We allow auto install apps to have their intent
2004 // updated after an install.
2005 intent = manager.getLaunchIntentForPackage(
2006 cn.getPackageName());
2007 if (intent != null) {
2008 ContentValues values = new ContentValues();
2009 values.put(LauncherSettings.Favorites.INTENT,
2010 intent.toUri(0));
2011 String where = BaseColumns._ID + "= ?";
2012 String[] args = {Long.toString(id)};
2013 contentResolver.update(contentUri, values, where, args);
2014 }
2015 }
2016
2017 if (intent == null) {
2018 // The app is installed but the component is no
2019 // longer available.
2020 Launcher.addDumpLog(TAG,
2021 "Invalid component removed: " + cn, true);
2022 itemsToRemove.add(id);
2023 continue;
2024 } else {
2025 // no special handling necessary for this item
2026 restoredRows.add(id);
2027 restored = false;
2028 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002029 } else if (restored) {
2030 // Package is not yet available but might be
2031 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05002032 Launcher.addDumpLog(TAG,
2033 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002034
2035 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
2036 // Restore has started once.
2037 } else if (installingPkgs.contains(cn.getPackageName())) {
2038 // App restore has started. Update the flag
2039 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
2040 ContentValues values = new ContentValues();
2041 values.put(LauncherSettings.Favorites.RESTORED,
2042 promiseType);
2043 String where = BaseColumns._ID + "= ?";
2044 String[] args = {Long.toString(id)};
2045 contentResolver.update(contentUri, values, where, args);
2046
2047 } else if (REMOVE_UNRESTORED_ICONS) {
2048 Launcher.addDumpLog(TAG,
2049 "Unrestored package removed: " + cn, true);
2050 itemsToRemove.add(id);
2051 continue;
2052 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002053 } else if (launcherApps.isAppEnabled(
2054 manager, cn.getPackageName(),
2055 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2056 // Package is present but not available.
2057 allowMissingTarget = true;
2058 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2059 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002060 // SdCard is not ready yet. Package might get available,
2061 // once it is ready.
2062 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2063 + " (check again later)", true);
2064 HashSet<String> pkgs = sPendingPackages.get(user);
2065 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002066 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002067 sPendingPackages.put(user, pkgs);
2068 }
2069 pkgs.add(cn.getPackageName());
2070 allowMissingTarget = true;
2071 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002072
2073 } else {
2074 // Do not wait for external media load anymore.
2075 // Log the invalid package, and remove it
2076 Launcher.addDumpLog(TAG,
2077 "Invalid package removed: " + cn, true);
2078 itemsToRemove.add(id);
2079 continue;
Winson Chungee055712013-07-30 14:46:24 -07002080 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002081 } else if (cn == null) {
2082 // For shortcuts with no component, keep them as they are
2083 restoredRows.add(id);
2084 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002085 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002087 Launcher.addDumpLog(TAG,
2088 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002089 continue;
2090 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002091
Chris Wrenf4d08112014-01-16 18:13:56 -05002092 if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002093 if (user.equals(UserHandleCompat.myUserHandle())) {
2094 Launcher.addDumpLog(TAG,
2095 "constructing info for partially restored package",
2096 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002097 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002098 intent = getRestoredItemIntent(c, context, intent);
2099 } else {
2100 // Don't restore items for other profiles.
2101 itemsToRemove.add(id);
2102 continue;
2103 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002104 } else if (itemType ==
2105 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002106 info = getShortcutInfo(manager, intent, user, context, c,
2107 iconIndex, titleIndex, mLabelCache, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002108 } else {
2109 info = getShortcutInfo(c, context, iconTypeIndex,
2110 iconPackageIndex, iconResourceIndex, iconIndex,
2111 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002112
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002113 // App shortcuts that used to be automatically added to Launcher
2114 // didn't always have the correct intent flags set, so do that
2115 // here
2116 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002117 intent.getCategories() != null &&
2118 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002119 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 intent.addFlags(
2121 Intent.FLAG_ACTIVITY_NEW_TASK |
2122 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2123 }
Michael Jurka96879562012-03-22 05:54:33 -07002124 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002125
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002127 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002128 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002129 container = c.getInt(containerIndex);
2130 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002131 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002132 info.cellX = c.getInt(cellXIndex);
2133 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002134 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002135 info.spanX = 1;
2136 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002137 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002138 info.isDisabled = disabledState;
2139 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2140 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2141 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002142
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002144 if (!checkItemPlacement(occupied, info)) {
2145 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 break;
2147 }
2148
2149 switch (container) {
2150 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2151 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2152 sBgWorkspaceItems.add(info);
2153 break;
2154 default:
2155 // Item is in a user folder
2156 FolderInfo folderInfo =
2157 findOrMakeFolder(sBgFolders, container);
2158 folderInfo.add(info);
2159 break;
2160 }
2161 sBgItemsIdMap.put(info.id, info);
2162
2163 // now that we've loaded everthing re-save it with the
2164 // icon in case it disappears somehow.
2165 queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
Winson Chung1323b482013-08-05 12:41:55 -07002166 } else {
2167 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002168 }
2169 break;
2170
2171 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2172 id = c.getLong(idIndex);
2173 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2174
2175 folderInfo.title = c.getString(titleIndex);
2176 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002177 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002178 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002179 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002180 folderInfo.cellX = c.getInt(cellXIndex);
2181 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002182 folderInfo.spanX = 1;
2183 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002184
Daniel Sandler8802e962010-05-26 16:28:16 -04002185 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002186 if (!checkItemPlacement(occupied, folderInfo)) {
2187 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002188 break;
2189 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002190
Joe Onorato9c1289c2009-08-17 11:03:03 -04002191 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002192 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2193 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2194 sBgWorkspaceItems.add(folderInfo);
2195 break;
Joe Onorato36115782010-06-17 13:28:48 -04002196 }
Joe Onorato17a89222011-02-08 17:26:11 -08002197
Chris Wrenf4d08112014-01-16 18:13:56 -05002198 if (restored) {
2199 // no special handling required for restored folders
2200 restoredRows.add(id);
2201 }
2202
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002203 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2204 sBgFolders.put(folderInfo.id, folderInfo);
2205 break;
2206
2207 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002208 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002209 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002210 boolean customWidget = itemType ==
2211 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2212
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002213 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002214 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002215 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002216 final ComponentName component =
2217 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002218
Sunny Goyal651077b2014-06-30 14:15:31 -07002219 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002220 final boolean isIdValid = (restoreStatus &
2221 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002222
Sunny Goyalff572272014-07-23 13:58:07 -07002223 final boolean wasProviderReady = (restoreStatus &
2224 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002225
Adam Cohen59400422014-03-05 18:07:04 -08002226 final LauncherAppWidgetProviderInfo provider =
2227 LauncherModel.getProviderInfo(context,
2228 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002229
2230 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002231 if (!isSafeMode && !customWidget &&
2232 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002233 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002234 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002235
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002236 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002237 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002238 itemsToRemove.add(id);
2239 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002240 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002241 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2242 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002243
2244 if (!customWidget) {
2245 int[] minSpan =
2246 Launcher.getMinSpanForWidget(context, provider);
2247 appWidgetInfo.minSpanX = minSpan[0];
2248 appWidgetInfo.minSpanY = minSpan[1];
2249 }
Sunny Goyalff572272014-07-23 13:58:07 -07002250
2251 int status = restoreStatus;
2252 if (!wasProviderReady) {
2253 // If provider was not previously ready, update the
2254 // status and UI flag.
2255
2256 // Id would be valid only if the widget restore broadcast was received.
2257 if (isIdValid) {
2258 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2259 } else {
2260 status &= ~LauncherAppWidgetInfo
2261 .FLAG_PROVIDER_NOT_READY;
2262 }
2263 }
2264 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002265 } else {
2266 Log.v(TAG, "Widget restore pending id=" + id
2267 + " appWidgetId=" + appWidgetId
2268 + " status =" + restoreStatus);
2269 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002270 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002271 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002272
2273 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2274 // Restore has started once.
2275 } else if (installingPkgs.contains(component.getPackageName())) {
2276 // App restore has started. Update the flag
2277 appWidgetInfo.restoreStatus |=
2278 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002279 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002280 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002281 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002282 itemsToRemove.add(id);
2283 continue;
2284 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002285 }
Sunny Goyalff572272014-07-23 13:58:07 -07002286
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002288 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 appWidgetInfo.cellX = c.getInt(cellXIndex);
2290 appWidgetInfo.cellY = c.getInt(cellYIndex);
2291 appWidgetInfo.spanX = c.getInt(spanXIndex);
2292 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002293
Adam Cohen59400422014-03-05 18:07:04 -08002294 if (!customWidget) {
2295 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2296 appWidgetInfo.minSpanX = minSpan[0];
2297 appWidgetInfo.minSpanY = minSpan[1];
2298 }
2299
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002300 container = c.getInt(containerIndex);
2301 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2302 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2303 Log.e(TAG, "Widget found where container != " +
2304 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2305 continue;
2306 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002307
Adam Cohene25af792013-06-06 23:08:25 -07002308 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002309 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002310 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2311 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 break;
2313 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002314
Adam Cohen59400422014-03-05 18:07:04 -08002315 if (!customWidget) {
2316 String providerName =
2317 appWidgetInfo.providerName.flattenToString();
2318 if (!providerName.equals(savedProvider) ||
2319 (appWidgetInfo.restoreStatus != restoreStatus)) {
2320 ContentValues values = new ContentValues();
2321 values.put(
2322 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2323 providerName);
2324 values.put(LauncherSettings.Favorites.RESTORED,
2325 appWidgetInfo.restoreStatus);
2326 String where = BaseColumns._ID + "= ?";
2327 String[] args = {Long.toString(id)};
2328 contentResolver.update(contentUri, values, where, args);
2329 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002330 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002331 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2332 sBgAppWidgets.add(appWidgetInfo);
2333 }
Joe Onorato36115782010-06-17 13:28:48 -04002334 break;
2335 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002336 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002337 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002338 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002339 }
2340 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002341 if (c != null) {
2342 c.close();
2343 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002344 }
2345
Winson Chungba9c37f2013-08-30 14:11:37 -07002346 // Break early if we've stopped loading
2347 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002348 clearSBgDataStructures();
2349 return false;
2350 }
2351
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002352 if (itemsToRemove.size() > 0) {
2353 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002354 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002355 // Remove dead items
2356 for (long id : itemsToRemove) {
2357 if (DEBUG_LOADERS) {
2358 Log.d(TAG, "Removed id = " + id);
2359 }
2360 // Don't notify content observers
2361 try {
2362 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2363 null, null);
2364 } catch (RemoteException e) {
2365 Log.w(TAG, "Could not remove id = " + id);
2366 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002367 }
2368 }
2369
Chris Wrenf4d08112014-01-16 18:13:56 -05002370 if (restoredRows.size() > 0) {
2371 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002372 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002373 // Update restored items that no longer require special handling
2374 try {
2375 StringBuilder selectionBuilder = new StringBuilder();
2376 selectionBuilder.append(LauncherSettings.Favorites._ID);
2377 selectionBuilder.append(" IN (");
2378 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2379 selectionBuilder.append(")");
2380 ContentValues values = new ContentValues();
2381 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002382 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002383 values, selectionBuilder.toString(), null);
2384 } catch (RemoteException e) {
2385 Log.w(TAG, "Could not update restored rows");
2386 }
2387 }
2388
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002389 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2390 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002391 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002392 null, sWorker);
2393 }
2394
Winson Chungc763c4e2013-07-19 13:49:06 -07002395 if (loadedOldDb) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002396 long maxScreenId = 0;
2397 // If we're importing we use the old screen order.
2398 for (ItemInfo item: sBgItemsIdMap.values()) {
2399 long screenId = item.screenId;
2400 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2401 !sBgWorkspaceScreens.contains(screenId)) {
2402 sBgWorkspaceScreens.add(screenId);
2403 if (screenId > maxScreenId) {
2404 maxScreenId = screenId;
2405 }
2406 }
2407 }
2408 Collections.sort(sBgWorkspaceScreens);
Winson Chung9f9f00b2013-11-15 13:27:00 -08002409 // Log to disk
2410 Launcher.addDumpLog(TAG, "11683562 - maxScreenId: " + maxScreenId, true);
2411 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2412 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002413
Michael Jurka414300a2013-08-27 15:42:35 +02002414 LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002415 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Winson Chungc763c4e2013-07-19 13:49:06 -07002416
2417 // Update the max item id after we load an old db
2418 long maxItemId = 0;
2419 // If we're importing we use the old screen order.
2420 for (ItemInfo item: sBgItemsIdMap.values()) {
2421 maxItemId = Math.max(maxItemId, item.id);
2422 }
Michael Jurka414300a2013-08-27 15:42:35 +02002423 LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
Adam Cohendcd297f2013-06-18 13:13:40 -07002424 } else {
Winson Chung76828c82013-08-19 15:43:29 -07002425 TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
2426 for (Integer i : orderedScreens.keySet()) {
2427 sBgWorkspaceScreens.add(orderedScreens.get(i));
Adam Cohendcd297f2013-06-18 13:13:40 -07002428 }
Winson Chung9f9f00b2013-11-15 13:27:00 -08002429 // Log to disk
2430 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2431 TextUtils.join(", ", sBgWorkspaceScreens), true);
Adam Cohendcd297f2013-06-18 13:13:40 -07002432
2433 // Remove any empty screens
Winson Chung933bae62013-08-29 11:42:30 -07002434 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002435 for (ItemInfo item: sBgItemsIdMap.values()) {
2436 long screenId = item.screenId;
Adam Cohendcd297f2013-06-18 13:13:40 -07002437 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2438 unusedScreens.contains(screenId)) {
2439 unusedScreens.remove(screenId);
2440 }
2441 }
2442
2443 // If there are any empty screens remove them, and update.
2444 if (unusedScreens.size() != 0) {
Winson Chung9f9f00b2013-11-15 13:27:00 -08002445 // Log to disk
2446 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2447 TextUtils.join(", ", unusedScreens), true);
2448
Winson Chung933bae62013-08-29 11:42:30 -07002449 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002450 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
2451 }
2452 }
2453
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002454 if (DEBUG_LOADERS) {
2455 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2456 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002457 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002458 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002460
Daniel Sandler566da102013-06-25 23:43:45 -04002461 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002462 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002463 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002464 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002465 line += " | ";
2466 }
Winson Chung892c74d2013-08-22 16:15:50 -07002467 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002468 ItemInfo[][] screen = occupied.get(screenId);
2469 if (x < screen.length && y < screen[x].length) {
2470 line += (screen[x][y] != null) ? "#" : ".";
2471 } else {
2472 line += "!";
2473 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474 }
Joe Onorato36115782010-06-17 13:28:48 -04002475 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002476 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002477 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002478 }
Joe Onorato36115782010-06-17 13:28:48 -04002479 }
Winson Chungc763c4e2013-07-19 13:49:06 -07002480 return loadedOldDb;
Adam Cohene25af792013-06-06 23:08:25 -07002481 }
2482
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002483 /** Filters the set of items who are directly or indirectly (via another container) on the
2484 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002485 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002486 ArrayList<ItemInfo> allWorkspaceItems,
2487 ArrayList<ItemInfo> currentScreenItems,
2488 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002489 // Purge any null ItemInfos
2490 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2491 while (iter.hasNext()) {
2492 ItemInfo i = iter.next();
2493 if (i == null) {
2494 iter.remove();
2495 }
2496 }
2497
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002498 // Order the set of items by their containers first, this allows use to walk through the
2499 // list sequentially, build up a list of containers that are in the specified screen,
2500 // as well as all items in those containers.
2501 Set<Long> itemsOnScreen = new HashSet<Long>();
2502 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2503 @Override
2504 public int compare(ItemInfo lhs, ItemInfo rhs) {
2505 return (int) (lhs.container - rhs.container);
2506 }
2507 });
2508 for (ItemInfo info : allWorkspaceItems) {
2509 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002510 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511 currentScreenItems.add(info);
2512 itemsOnScreen.add(info.id);
2513 } else {
2514 otherScreenItems.add(info);
2515 }
2516 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2517 currentScreenItems.add(info);
2518 itemsOnScreen.add(info.id);
2519 } else {
2520 if (itemsOnScreen.contains(info.container)) {
2521 currentScreenItems.add(info);
2522 itemsOnScreen.add(info.id);
2523 } else {
2524 otherScreenItems.add(info);
2525 }
2526 }
2527 }
2528 }
2529
2530 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002531 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002532 ArrayList<LauncherAppWidgetInfo> appWidgets,
2533 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2534 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002535
2536 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002537 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002538 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002539 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002540 currentScreenWidgets.add(widget);
2541 } else {
2542 otherScreenWidgets.add(widget);
2543 }
2544 }
2545 }
2546
2547 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002548 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 HashMap<Long, ItemInfo> itemsIdMap,
2550 HashMap<Long, FolderInfo> folders,
2551 HashMap<Long, FolderInfo> currentScreenFolders,
2552 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553
2554 for (long id : folders.keySet()) {
2555 ItemInfo info = itemsIdMap.get(id);
2556 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002557 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002559 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002560 currentScreenFolders.put(id, folder);
2561 } else {
2562 otherScreenFolders.put(id, folder);
2563 }
2564 }
2565 }
2566
2567 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2568 * right) */
2569 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002570 final LauncherAppState app = LauncherAppState.getInstance();
2571 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002572 // XXX: review this
2573 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002574 @Override
2575 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002576 int cellCountX = (int) grid.numColumns;
2577 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002578 int screenOffset = cellCountX * cellCountY;
2579 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002580 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002581 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002582 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002583 rhs.cellY * cellCountX + rhs.cellX);
2584 return (int) (lr - rr);
2585 }
2586 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002587 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002588
Adam Cohendcd297f2013-06-18 13:13:40 -07002589 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2590 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002591 final Runnable r = new Runnable() {
2592 @Override
2593 public void run() {
2594 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2595 if (callbacks != null) {
2596 callbacks.bindScreens(orderedScreens);
2597 }
2598 }
2599 };
2600 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2601 }
2602
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002603 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2604 final ArrayList<ItemInfo> workspaceItems,
2605 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2606 final HashMap<Long, FolderInfo> folders,
2607 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002608
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002609 final boolean postOnMainThread = (deferredBindRunnables != null);
2610
2611 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002612 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002613 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002614 final int start = i;
2615 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 final Runnable r = new Runnable() {
2617 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002618 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002619 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002620 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002621 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2622 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002623 }
2624 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002625 };
2626 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002627 synchronized (deferredBindRunnables) {
2628 deferredBindRunnables.add(r);
2629 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002630 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002631 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002632 }
Joe Onorato36115782010-06-17 13:28:48 -04002633 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002634
2635 // Bind the folders
2636 if (!folders.isEmpty()) {
2637 final Runnable r = new Runnable() {
2638 public void run() {
2639 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2640 if (callbacks != null) {
2641 callbacks.bindFolders(folders);
2642 }
2643 }
2644 };
2645 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002646 synchronized (deferredBindRunnables) {
2647 deferredBindRunnables.add(r);
2648 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002649 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002650 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002651 }
2652 }
2653
2654 // Bind the widgets, one at a time
2655 N = appWidgets.size();
2656 for (int i = 0; i < N; i++) {
2657 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2658 final Runnable r = new Runnable() {
2659 public void run() {
2660 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2661 if (callbacks != null) {
2662 callbacks.bindAppWidget(widget);
2663 }
2664 }
2665 };
2666 if (postOnMainThread) {
2667 deferredBindRunnables.add(r);
2668 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002669 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002670 }
2671 }
2672 }
2673
2674 /**
2675 * Binds all loaded data to actual views on the main thread.
2676 */
Winson Chungc763c4e2013-07-19 13:49:06 -07002677 private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002678 final long t = SystemClock.uptimeMillis();
2679 Runnable r;
2680
2681 // Don't use these two variables in any of the callback runnables.
2682 // Otherwise we hold a reference to them.
2683 final Callbacks oldCallbacks = mCallbacks.get();
2684 if (oldCallbacks == null) {
2685 // This launcher has exited and nobody bothered to tell us. Just bail.
2686 Log.w(TAG, "LoaderTask running with no launcher");
2687 return;
2688 }
2689
Winson Chung9b9fb962013-11-15 15:39:34 -08002690 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002691 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2692 ArrayList<LauncherAppWidgetInfo> appWidgets =
2693 new ArrayList<LauncherAppWidgetInfo>();
2694 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2695 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002696 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002697 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002698 workspaceItems.addAll(sBgWorkspaceItems);
2699 appWidgets.addAll(sBgAppWidgets);
2700 folders.putAll(sBgFolders);
2701 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002702 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002703 }
2704
Derek Prothro7aff3992013-12-10 14:00:37 -05002705 final boolean isLoadingSynchronously =
2706 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002707 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002708 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002709 if (currScreen >= orderedScreenIds.size()) {
2710 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002711 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002712 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002713 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002714 final long currentScreenId = currentScreen < 0
2715 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002716
2717 // Load all the items that are on the current page first (and in the process, unbind
2718 // all the existing workspace items before we call startBinding() below.
2719 unbindWorkspaceItemsOnMainThread();
2720
2721 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002722 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2723 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2724 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2725 new ArrayList<LauncherAppWidgetInfo>();
2726 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2727 new ArrayList<LauncherAppWidgetInfo>();
2728 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2729 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2730
Winson Chung9b9fb962013-11-15 15:39:34 -08002731 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002732 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002733 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002734 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002735 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002736 otherFolders);
2737 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2738 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2739
2740 // Tell the workspace that we're about to start binding items
2741 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002742 public void run() {
2743 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2744 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002745 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002746 }
2747 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002748 };
Winson Chung81b52252012-08-27 15:34:29 -07002749 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002750
Adam Cohendcd297f2013-06-18 13:13:40 -07002751 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2752
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002753 // Load items on the current page
2754 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2755 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002756 if (isLoadingSynchronously) {
2757 r = new Runnable() {
2758 public void run() {
2759 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002760 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002761 callbacks.onPageBoundSynchronously(currentScreen);
2762 }
2763 }
2764 };
Winson Chung81b52252012-08-27 15:34:29 -07002765 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002766 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002767
Winson Chung4a2afa32012-07-19 14:53:05 -07002768 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2769 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002770 synchronized (mDeferredBindRunnables) {
2771 mDeferredBindRunnables.clear();
2772 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002773 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002774 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002775
2776 // Tell the workspace that we're done binding items
2777 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002778 public void run() {
2779 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2780 if (callbacks != null) {
Winson Chungc763c4e2013-07-19 13:49:06 -07002781 callbacks.finishBindingItems(isUpgradePath);
Joe Onorato36115782010-06-17 13:28:48 -04002782 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002783
Winson Chung98e030b2012-05-07 16:01:11 -07002784 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002785 if (DEBUG_LOADERS) {
2786 Log.d(TAG, "bound workspace in "
2787 + (SystemClock.uptimeMillis()-t) + "ms");
2788 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002789
2790 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002791 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002792 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002793 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002794 synchronized (mDeferredBindRunnables) {
2795 mDeferredBindRunnables.add(r);
2796 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002797 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002798 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002799 }
Joe Onorato36115782010-06-17 13:28:48 -04002800 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002801
Joe Onorato36115782010-06-17 13:28:48 -04002802 private void loadAndBindAllApps() {
2803 if (DEBUG_LOADERS) {
2804 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2805 }
2806 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002807 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002808 synchronized (LoaderTask.this) {
2809 if (mStopped) {
2810 return;
2811 }
2812 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002813 }
Joe Onorato36115782010-06-17 13:28:48 -04002814 } else {
2815 onlyBindAllApps();
2816 }
2817 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002818
Joe Onorato36115782010-06-17 13:28:48 -04002819 private void onlyBindAllApps() {
2820 final Callbacks oldCallbacks = mCallbacks.get();
2821 if (oldCallbacks == null) {
2822 // This launcher has exited and nobody bothered to tell us. Just bail.
2823 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2824 return;
2825 }
2826
2827 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002828 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002829 final ArrayList<AppInfo> list
2830 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002831 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002832 public void run() {
2833 final long t = SystemClock.uptimeMillis();
2834 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2835 if (callbacks != null) {
2836 callbacks.bindAllApplications(list);
2837 }
2838 if (DEBUG_LOADERS) {
2839 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2840 + (SystemClock.uptimeMillis()-t) + "ms");
2841 }
2842 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002843 };
2844 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002845 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002846 r.run();
2847 } else {
2848 mHandler.post(r);
2849 }
Joe Onorato36115782010-06-17 13:28:48 -04002850 }
2851
Winson Chung64359a52013-07-08 17:17:08 -07002852 private void loadAllApps() {
2853 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002854
Joe Onorato36115782010-06-17 13:28:48 -04002855 final Callbacks oldCallbacks = mCallbacks.get();
2856 if (oldCallbacks == null) {
2857 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002858 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002859 return;
2860 }
2861
2862 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2863 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2864
Kenny Guyed131872014-04-30 03:02:21 +01002865 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2866
Winson Chung64359a52013-07-08 17:17:08 -07002867 // Clear the list of apps
2868 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002869 SharedPreferences prefs = mContext.getSharedPreferences(
2870 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002871 for (UserHandleCompat user : profiles) {
2872 // Query for the set of apps
2873 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2874 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2875 if (DEBUG_LOADERS) {
2876 Log.d(TAG, "getActivityList took "
2877 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2878 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2879 }
2880 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002881 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002882 if (apps == null || apps.isEmpty()) {
2883 return;
2884 }
2885 // Sort the applications by name
2886 final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2887 Collections.sort(apps,
2888 new LauncherModel.ShortcutNameComparator(mLabelCache));
2889 if (DEBUG_LOADERS) {
2890 Log.d(TAG, "sort took "
2891 + (SystemClock.uptimeMillis()-sortTime) + "ms");
2892 }
Joe Onorato36115782010-06-17 13:28:48 -04002893
Kenny Guyed131872014-04-30 03:02:21 +01002894 // Create the ApplicationInfos
2895 for (int i = 0; i < apps.size(); i++) {
2896 LauncherActivityInfoCompat app = apps.get(i);
2897 // This builds the icon bitmaps.
2898 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache, mLabelCache));
2899 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002900
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002901 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002902 // Add shortcuts for packages which were installed while launcher was dead.
2903 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2904 + mUserManager.getSerialNumberForUser(user);
2905 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2906 HashSet<String> newPackageSet = new HashSet<String>();
2907
2908 for (LauncherActivityInfoCompat info : apps) {
2909 String packageName = info.getComponentName().getPackageName();
2910 if (!packagesAdded.contains(packageName)
2911 && !newPackageSet.contains(packageName)) {
2912 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2913 }
2914 newPackageSet.add(packageName);
2915 }
2916
2917 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2918 }
Winson Chung64359a52013-07-08 17:17:08 -07002919 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002920 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002921 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2922 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002923
2924 // Post callback on main thread
2925 mHandler.post(new Runnable() {
2926 public void run() {
2927 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002928 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002929 if (callbacks != null) {
2930 callbacks.bindAllApplications(added);
2931 if (DEBUG_LOADERS) {
2932 Log.d(TAG, "bound " + added.size() + " apps in "
2933 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2934 }
2935 } else {
2936 Log.i(TAG, "not binding apps: no Launcher activity");
2937 }
2938 }
2939 });
2940
Joe Onorato36115782010-06-17 13:28:48 -04002941 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002942 Log.d(TAG, "Icons processed in "
2943 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002944 }
2945 }
2946
2947 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002948 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002949 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2950 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2951 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2952 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2953 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2954 }
Joe Onorato36115782010-06-17 13:28:48 -04002955 }
2956 }
2957
2958 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002959 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002960 }
2961
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002962 private class AppsAvailabilityCheck extends BroadcastReceiver {
2963
2964 @Override
2965 public void onReceive(Context context, Intent intent) {
2966 synchronized (sBgLock) {
2967 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2968 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002969 final PackageManager manager = context.getPackageManager();
2970 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2971 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002972 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2973 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002974 packagesRemoved.clear();
2975 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002976 for (String pkg : entry.getValue()) {
2977 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002978 boolean packageOnSdcard = launcherApps.isAppEnabled(
2979 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2980 if (packageOnSdcard) {
2981 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2982 packagesUnavailable.add(pkg);
2983 } else {
2984 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2985 packagesRemoved.add(pkg);
2986 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002987 }
2988 }
2989 if (!packagesRemoved.isEmpty()) {
2990 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2991 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2992 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002993 if (!packagesUnavailable.isEmpty()) {
2994 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2995 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2996 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002997 }
Sunny Goyal34942622014-08-29 17:20:55 -07002998 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002999 }
3000 }
3001 }
3002
Joe Onorato36115782010-06-17 13:28:48 -04003003 private class PackageUpdatedTask implements Runnable {
3004 int mOp;
3005 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01003006 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04003007
3008 public static final int OP_NONE = 0;
3009 public static final int OP_ADD = 1;
3010 public static final int OP_UPDATE = 2;
3011 public static final int OP_REMOVE = 3; // uninstlled
3012 public static final int OP_UNAVAILABLE = 4; // external media unmounted
3013
3014
Kenny Guyed131872014-04-30 03:02:21 +01003015 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04003016 mOp = op;
3017 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01003018 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04003019 }
3020
3021 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04003022 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04003023
3024 final String[] packages = mPackages;
3025 final int N = packages.length;
3026 switch (mOp) {
3027 case OP_ADD:
3028 for (int i=0; i<N; i++) {
3029 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003030 mIconCache.remove(packages[i], mUser);
3031 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003032 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003033
3034 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003035 if (ADD_MANAGED_PROFILE_SHORTCUTS
3036 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003037 SharedPreferences prefs = context.getSharedPreferences(
3038 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3039 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3040 + mUserManager.getSerialNumberForUser(mUser);
3041 Set<String> shortcutSet = new HashSet<String>(
3042 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3043
3044 for (int i=0; i<N; i++) {
3045 if (!shortcutSet.contains(packages[i])) {
3046 shortcutSet.add(packages[i]);
3047 List<LauncherActivityInfoCompat> activities =
3048 mLauncherApps.getActivityList(packages[i], mUser);
3049 if (activities != null && !activities.isEmpty()) {
3050 InstallShortcutReceiver.queueInstallShortcut(
3051 activities.get(0), context);
3052 }
3053 }
3054 }
3055
3056 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3057 }
Joe Onorato36115782010-06-17 13:28:48 -04003058 break;
3059 case OP_UPDATE:
3060 for (int i=0; i<N; i++) {
3061 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Kenny Guyed131872014-04-30 03:02:21 +01003062 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003063 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003064 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003065 }
3066 break;
3067 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003068 // Remove the packageName for the set of auto-installed shortcuts. This
3069 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003070 if (ADD_MANAGED_PROFILE_SHORTCUTS
3071 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003072 SharedPreferences prefs = context.getSharedPreferences(
3073 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3074 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3075 + mUserManager.getSerialNumberForUser(mUser);
3076 HashSet<String> shortcutSet = new HashSet<String>(
3077 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3078 shortcutSet.removeAll(Arrays.asList(mPackages));
3079 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3080 }
3081 // Fall through
Joe Onorato36115782010-06-17 13:28:48 -04003082 case OP_UNAVAILABLE:
Sunny Goyal1a745e82014-10-02 15:58:31 -07003083 boolean clearCache = mOp == OP_REMOVE;
Joe Onorato36115782010-06-17 13:28:48 -04003084 for (int i=0; i<N; i++) {
3085 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal1a745e82014-10-02 15:58:31 -07003086 mBgAllAppsList.removePackage(packages[i], mUser, clearCache);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003087 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003088 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003089 }
3090 break;
3091 }
3092
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003093 ArrayList<AppInfo> added = null;
3094 ArrayList<AppInfo> modified = null;
3095 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003096
Adam Cohen487f7dd2012-06-28 18:12:10 -07003097 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003098 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003099 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003100 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003101 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003102 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003103 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003104 }
Winson Chung5d55f332012-07-16 20:45:03 -07003105 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003106 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003107 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003108 }
3109
Sunny Goyale0f58d72014-11-10 18:05:31 -08003110 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003111 if (callbacks == null) {
3112 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3113 return;
3114 }
3115
Sunny Goyal4390ace2014-10-13 11:33:11 -07003116 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3117 new HashMap<ComponentName, AppInfo>();
3118
Joe Onorato36115782010-06-17 13:28:48 -04003119 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003120 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003121 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003122 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003123 addAndBindAddedWorkspaceApps(context, addedInfos);
3124 } else {
3125 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003126 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003127 for (AppInfo ai : added) {
3128 addedOrUpdatedApps.put(ai.componentName, ai);
3129 }
Joe Onorato36115782010-06-17 13:28:48 -04003130 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003131
Joe Onorato36115782010-06-17 13:28:48 -04003132 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003133 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003134 for (AppInfo ai : modified) {
3135 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003136 }
3137
Joe Onorato36115782010-06-17 13:28:48 -04003138 mHandler.post(new Runnable() {
3139 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003140 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003141 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003142 callbacks.bindAppsUpdated(modifiedFinal);
3143 }
3144 }
3145 });
3146 }
Winson Chung83892cc2013-05-01 16:53:33 -07003147
Sunny Goyal4390ace2014-10-13 11:33:11 -07003148 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003149 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003150 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3151 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3152 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3153
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003154 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003155 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003156 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003157 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3158 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003159 boolean infoUpdated = false;
3160 boolean shortcutUpdated = false;
3161
3162 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003163 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003164 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003165 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3166 si.iconResource.resourceName, mIconCache, context);
3167 if (icon != null) {
3168 si.setIcon(icon);
3169 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003170 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003171 }
3172 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003173
3174 ComponentName cn = si.getTargetComponent();
3175 if (cn != null && packageSet.contains(cn.getPackageName())) {
3176 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3177
3178 if (si.isPromise()) {
3179 mIconCache.deletePreloadedIcon(cn, mUser);
3180 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3181 // Auto install icon
3182 PackageManager pm = context.getPackageManager();
3183 ResolveInfo matched = pm.resolveActivity(
3184 new Intent(Intent.ACTION_MAIN)
3185 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3186 PackageManager.MATCH_DEFAULT_ONLY);
3187 if (matched == null) {
3188 // Try to find the best match activity.
3189 Intent intent = pm.getLaunchIntentForPackage(
3190 cn.getPackageName());
3191 if (intent != null) {
3192 cn = intent.getComponent();
3193 appInfo = addedOrUpdatedApps.get(cn);
3194 }
3195
3196 if ((intent == null) || (appInfo == null)) {
3197 removedShortcuts.add(si);
3198 continue;
3199 }
3200 si.promisedIntent = intent;
3201 }
3202 }
3203
3204 // Restore the shortcut.
3205 si.intent = si.promisedIntent;
3206 si.promisedIntent = null;
3207 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3208 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3209 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3210
3211 infoUpdated = true;
3212 si.updateIcon(mIconCache);
3213 }
3214
3215 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3216 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3217 si.updateIcon(mIconCache);
3218 si.title = appInfo.title.toString();
3219 si.contentDescription = appInfo.contentDescription;
3220 infoUpdated = true;
3221 }
3222
3223 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3224 // Since package was just updated, the target must be available now.
3225 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3226 shortcutUpdated = true;
3227 }
3228 }
3229
3230 if (infoUpdated || shortcutUpdated) {
3231 updatedShortcuts.add(si);
3232 }
3233 if (infoUpdated) {
3234 updateItemInDatabase(context, si);
3235 }
3236 } else if (info instanceof LauncherAppWidgetInfo) {
3237 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3238 if (mUser.equals(widgetInfo.user)
3239 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3240 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3241 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3242 widgets.add(widgetInfo);
3243 updateItemInDatabase(context, widgetInfo);
3244 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003245 }
3246 }
3247 }
3248
Sunny Goyal4390ace2014-10-13 11:33:11 -07003249 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3250 mHandler.post(new Runnable() {
3251
3252 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003253 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003254 if (callbacks == cb && cb != null) {
3255 callbacks.bindShortcutsChanged(
3256 updatedShortcuts, removedShortcuts, mUser);
3257 }
3258 }
3259 });
3260 if (!removedShortcuts.isEmpty()) {
3261 deleteItemsFromDatabase(context, removedShortcuts);
3262 }
3263 }
3264 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003265 mHandler.post(new Runnable() {
3266 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003267 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003268 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003269 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003270 }
3271 }
3272 });
3273 }
3274 }
3275
Winson Chungdf95eb12013-10-16 14:57:07 -07003276 final ArrayList<String> removedPackageNames =
3277 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003278 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003279 // Mark all packages in the broadcast to be removed
3280 removedPackageNames.addAll(Arrays.asList(packages));
3281 } else if (mOp == OP_UPDATE) {
3282 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003283 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003284 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003285 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003286 }
3287 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003288 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003289
Winson Chungdf95eb12013-10-16 14:57:07 -07003290 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003291 final int removeReason;
3292 if (mOp == OP_UNAVAILABLE) {
3293 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3294 } else {
3295 // Remove all the components associated with this package
3296 for (String pn : removedPackageNames) {
3297 deletePackageFromDatabase(context, pn, mUser);
3298 }
3299 // Remove all the specific components
3300 for (AppInfo a : removedApps) {
3301 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3302 deleteItemsFromDatabase(context, infos);
3303 }
3304 removeReason = 0;
3305 }
3306
Winson Chungdf95eb12013-10-16 14:57:07 -07003307 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003308 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003309 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003310 mHandler.post(new Runnable() {
3311 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003312 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003313 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003314 callbacks.bindComponentsRemoved(
3315 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003316 }
3317 }
3318 });
Joe Onoratobe386092009-11-17 17:32:16 -08003319 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003320
Michael Jurkac402cd92013-05-20 15:49:32 +02003321 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003322 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003323 mHandler.post(new Runnable() {
3324 @Override
3325 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003326 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003327 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003328 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003329 }
3330 }
3331 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003332
3333 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003334 mHandler.post(new Runnable() {
3335 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003336 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003337 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003338 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003339 }
3340 }
3341 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003342 }
3343 }
3344
Adam Cohen59400422014-03-05 18:07:04 -08003345 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3346 synchronized (sBgLock) {
3347 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3348 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3349 }
3350 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3351 List<AppWidgetProviderInfo> widgets =
3352 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3353 LauncherAppWidgetProviderInfo info;
3354 for (AppWidgetProviderInfo pInfo : widgets) {
3355 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3356 sBgWidgetProviders.put(info.provider, info);
3357 }
3358
3359 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3360 for (CustomAppWidget widget : customWidgets) {
3361 info = new LauncherAppWidgetProviderInfo(context, widget);
3362 sBgWidgetProviders.put(info.provider, info);
3363 }
3364 sWidgetProvidersDirty = false;
3365 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3366 }
3367 }
3368
3369 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3370 synchronized (sBgLock) {
3371 if (sBgWidgetProviders == null) {
3372 getWidgetProviders(ctx);
3373 }
3374 return sBgWidgetProviders.get(name);
3375 }
3376 }
3377
Michael Jurkac402cd92013-05-20 15:49:32 +02003378 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3379 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3380 PackageManager packageManager = context.getPackageManager();
3381 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003382 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003383 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3384 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003385 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003386 return widgetsAndShortcuts;
3387 }
3388
Kenny Guyed131872014-04-30 03:02:21 +01003389 private static boolean isPackageDisabled(Context context, String packageName,
3390 UserHandleCompat user) {
3391 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3392 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003393 }
Adam Cohen556f6132014-01-15 15:18:08 -08003394
Kenny Guyed131872014-04-30 03:02:21 +01003395 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3396 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003397 if (cn == null) {
3398 return false;
3399 }
Kenny Guyed131872014-04-30 03:02:21 +01003400 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3401 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003402 return false;
3403 }
Kenny Guyed131872014-04-30 03:02:21 +01003404 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003405 }
3406
Adam Cohena28b78e2014-05-20 17:03:04 -07003407 public static boolean isValidPackage(Context context, String packageName,
3408 UserHandleCompat user) {
3409 if (packageName == null) {
3410 return false;
3411 }
3412 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3413 return launcherApps.isPackageEnabledForProfile(packageName, user);
3414 }
3415
Joe Onorato9c1289c2009-08-17 11:03:03 -04003416 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003417 * Make an ShortcutInfo object for a restored application or shortcut item that points
3418 * to a package that is not yet installed on the system.
3419 */
Sunny Goyal34942622014-08-29 17:20:55 -07003420 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3421 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003422 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003423 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34942622014-08-29 17:20:55 -07003424 mIconCache.getTitleAndIcon(info, intent, info.user, true);
3425
3426 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3427 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3428 if (!TextUtils.isEmpty(title)) {
3429 info.title = title;
3430 }
3431 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3432 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3433 if (TextUtils.isEmpty(info.title)) {
3434 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3435 }
3436 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3437 } else {
3438 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3439 }
3440
Kenny Guyc2bd8102014-06-30 12:30:31 +01003441 info.contentDescription = mUserManager.getBadgedLabelForUser(
3442 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003443 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003444 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003445 return info;
3446 }
3447
3448 /**
3449 * Make an Intent object for a restored application or shortcut item that points
3450 * to the market page for the item.
3451 */
3452 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3453 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003454 return getMarketIntent(componentName.getPackageName());
3455 }
3456
3457 static Intent getMarketIntent(String packageName) {
3458 return new Intent(Intent.ACTION_VIEW)
3459 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003460 .scheme("market")
3461 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003462 .appendQueryParameter("id", packageName)
3463 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003464 }
3465
3466 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003467 * This is called from the code that adds shortcuts from the intent receiver. This
3468 * doesn't have a Cursor, but
Joe Onorato9c1289c2009-08-17 11:03:03 -04003469 */
Kenny Guyed131872014-04-30 03:02:21 +01003470 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3471 UserHandleCompat user, Context context) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003472 return getShortcutInfo(manager, intent, user, context, null, -1, -1, null, false);
Joe Onorato56d82912010-03-07 14:32:10 -05003473 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003474
Joe Onorato56d82912010-03-07 14:32:10 -05003475 /**
3476 * Make an ShortcutInfo object for a shortcut that is an application.
3477 *
3478 * If c is not null, then it will be used to fill in missing data like the title and icon.
3479 */
Kenny Guyed131872014-04-30 03:02:21 +01003480 public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent,
3481 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003482 HashMap<Object, CharSequence> labelCache, boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003483 if (user == null) {
3484 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003485 return null;
3486 }
3487
Kenny Guyed131872014-04-30 03:02:21 +01003488 ComponentName componentName = intent.getComponent();
3489 if (componentName == null) {
3490 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3491 return null;
3492 }
3493
3494 Intent newIntent = new Intent(intent.getAction(), null);
3495 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3496 newIntent.setComponent(componentName);
3497 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003498 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003499 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3500 return null;
3501 }
3502
3503 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003504
Joe Onorato56d82912010-03-07 14:32:10 -05003505 // the resource -- This may implicitly give us back the fallback icon,
3506 // but don't worry about that. All we're doing with usingFallbackIcon is
3507 // to avoid saving lots of copies of that in the database, and most apps
3508 // have icons anyway.
Kenny Guyed131872014-04-30 03:02:21 +01003509 Bitmap icon = mIconCache.getIcon(componentName, lai, labelCache);
Winson Chungc208ff92012-03-29 17:37:41 -07003510
Joe Onorato56d82912010-03-07 14:32:10 -05003511 // the db
3512 if (icon == null) {
3513 if (c != null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003514 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003515 }
3516 }
3517 // the fallback icon
3518 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003519 icon = mIconCache.getDefaultIcon(user);
Joe Onorato56d82912010-03-07 14:32:10 -05003520 info.usingFallbackIcon = true;
3521 }
3522 info.setIcon(icon);
3523
Kenny Guyed131872014-04-30 03:02:21 +01003524 // From the cache.
3525 if (labelCache != null) {
3526 info.title = labelCache.get(componentName);
3527 }
3528
Joe Onorato56d82912010-03-07 14:32:10 -05003529 // from the resource
Kenny Guyed131872014-04-30 03:02:21 +01003530 if (info.title == null && lai != null) {
3531 info.title = lai.getLabel();
3532 if (labelCache != null) {
3533 labelCache.put(componentName, info.title);
Winson Chungc3eecff2011-07-11 17:44:15 -07003534 }
Joe Onorato56d82912010-03-07 14:32:10 -05003535 }
3536 // from the db
Joe Onorato9c1289c2009-08-17 11:03:03 -04003537 if (info.title == null) {
Joe Onorato56d82912010-03-07 14:32:10 -05003538 if (c != null) {
3539 info.title = c.getString(titleIndex);
3540 }
3541 }
3542 // fall back to the class name of the activity
3543 if (info.title == null) {
3544 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003545 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003546 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003547 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003548 info.contentDescription = mUserManager.getBadgedLabelForUser(
3549 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003550 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003551 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003552
Winson Chung64359a52013-07-08 17:17:08 -07003553 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3554 ItemInfoFilter f) {
3555 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3556 for (ItemInfo i : infos) {
3557 if (i instanceof ShortcutInfo) {
3558 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003559 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003560 if (cn != null && f.filterItem(null, info, cn)) {
3561 filtered.add(info);
3562 }
3563 } else if (i instanceof FolderInfo) {
3564 FolderInfo info = (FolderInfo) i;
3565 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003566 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003567 if (cn != null && f.filterItem(info, s, cn)) {
3568 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003569 }
3570 }
Winson Chung64359a52013-07-08 17:17:08 -07003571 } else if (i instanceof LauncherAppWidgetInfo) {
3572 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3573 ComponentName cn = info.providerName;
3574 if (cn != null && f.filterItem(null, info, cn)) {
3575 filtered.add(info);
3576 }
Winson Chung8a435102012-08-30 17:16:53 -07003577 }
3578 }
Winson Chung64359a52013-07-08 17:17:08 -07003579 return new ArrayList<ItemInfo>(filtered);
3580 }
3581
Kenny Guyed131872014-04-30 03:02:21 +01003582 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3583 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003584 ItemInfoFilter filter = new ItemInfoFilter() {
3585 @Override
3586 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003587 if (info.user == null) {
3588 return cn.equals(cname);
3589 } else {
3590 return cn.equals(cname) && info.user.equals(user);
3591 }
Winson Chung64359a52013-07-08 17:17:08 -07003592 }
3593 };
3594 return filterItemInfos(sBgItemsIdMap.values(), filter);
3595 }
3596
Sunny Goyal1a745e82014-10-02 15:58:31 -07003597 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003598 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003599 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003600 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003601 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3602 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003603
Joe Onorato56d82912010-03-07 14:32:10 -05003604 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003605 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003606 // Non-app shortcuts are only supported for current user.
3607 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003608 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003609
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003610 // TODO: If there's an explicit component and we can't install that, delete it.
3611
Joe Onorato56d82912010-03-07 14:32:10 -05003612 info.title = c.getString(titleIndex);
3613
Joe Onorato9c1289c2009-08-17 11:03:03 -04003614 int iconType = c.getInt(iconTypeIndex);
3615 switch (iconType) {
3616 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3617 String packageName = c.getString(iconPackageIndex);
3618 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003619 info.customIcon = false;
3620 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003621 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003622 // the db
3623 if (icon == null) {
Michael Jurka931dc972011-08-05 15:08:15 -07003624 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003625 }
3626 // the fallback icon
3627 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003628 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003629 info.usingFallbackIcon = true;
3630 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003631 break;
3632 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Michael Jurka931dc972011-08-05 15:08:15 -07003633 icon = getIconFromCursor(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003634 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003635 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003636 info.customIcon = false;
3637 info.usingFallbackIcon = true;
3638 } else {
3639 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003640 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003641 break;
3642 default:
Kenny Guyed131872014-04-30 03:02:21 +01003643 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003644 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003645 info.customIcon = false;
3646 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003647 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003648 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003649 return info;
3650 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003651
Michael Jurka931dc972011-08-05 15:08:15 -07003652 Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
Michael Jurka3a9fced2012-04-13 14:44:29 -07003653 @SuppressWarnings("all") // suppress dead code warning
3654 final boolean debug = false;
3655 if (debug) {
Joe Onorato56d82912010-03-07 14:32:10 -05003656 Log.d(TAG, "getIconFromCursor app="
3657 + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
3658 }
3659 byte[] data = c.getBlob(iconIndex);
3660 try {
Michael Jurka931dc972011-08-05 15:08:15 -07003661 return Utilities.createIconBitmap(
3662 BitmapFactory.decodeByteArray(data, 0, data.length), context);
Joe Onorato56d82912010-03-07 14:32:10 -05003663 } catch (Exception e) {
3664 return null;
3665 }
3666 }
3667
Sunny Goyal2350bc92014-10-14 16:42:54 -07003668 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003669 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3670 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3671 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3672
Adam Cohend9198822011-11-22 16:42:47 -08003673 if (intent == null) {
3674 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3675 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3676 return null;
3677 }
3678
Joe Onorato0589f0f2010-02-08 13:44:00 -08003679 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003680 boolean customIcon = false;
3681 ShortcutIconResource iconResource = null;
3682
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003683 if (bitmap instanceof Bitmap) {
3684 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003685 customIcon = true;
3686 } else {
3687 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003688 if (extra instanceof ShortcutIconResource) {
3689 iconResource = (ShortcutIconResource) extra;
3690 icon = Utilities.createIconBitmap(iconResource.packageName,
3691 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003692 }
3693 }
3694
Michael Jurkac9d95c52011-08-29 14:03:34 -07003695 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003696
Kenny Guyed131872014-04-30 03:02:21 +01003697 // Only support intents for current user for now. Intents sent from other
3698 // users wouldn't get here without intent forwarding anyway.
3699 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003700 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003701 icon = mIconCache.getDefaultIcon(info.user);
3702 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003703 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003704 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003705
Joe Onorato0589f0f2010-02-08 13:44:00 -08003706 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003707 info.contentDescription = mUserManager.getBadgedLabelForUser(
3708 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003709 info.intent = intent;
3710 info.customIcon = customIcon;
3711 info.iconResource = iconResource;
3712
3713 return info;
3714 }
3715
Winson Chungaac01e12011-08-17 10:37:13 -07003716 boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
3717 int iconIndex) {
Joe Onorato17a89222011-02-08 17:26:11 -08003718 // If apps can't be on SD, don't even bother.
Winson Chungee055712013-07-30 14:46:24 -07003719 if (!mAppsCanBeOnRemoveableStorage) {
Winson Chungaac01e12011-08-17 10:37:13 -07003720 return false;
Joe Onorato17a89222011-02-08 17:26:11 -08003721 }
Joe Onorato56d82912010-03-07 14:32:10 -05003722 // If this icon doesn't have a custom icon, check to see
3723 // what's stored in the DB, and if it doesn't match what
3724 // we're going to show, store what we are going to show back
3725 // into the DB. We do this so when we're loading, if the
3726 // package manager can't find an icon (for example because
3727 // the app is on SD) then we can use that instead.
Joe Onoratoddc9c1f2010-08-30 18:30:15 -07003728 if (!info.customIcon && !info.usingFallbackIcon) {
Winson Chungaac01e12011-08-17 10:37:13 -07003729 cache.put(info, c.getBlob(iconIndex));
3730 return true;
3731 }
3732 return false;
3733 }
3734 void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
3735 boolean needSave = false;
3736 try {
3737 if (data != null) {
3738 Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
3739 Bitmap loaded = info.getIcon(mIconCache);
3740 needSave = !saved.sameAs(loaded);
3741 } else {
Joe Onorato56d82912010-03-07 14:32:10 -05003742 needSave = true;
3743 }
Winson Chungaac01e12011-08-17 10:37:13 -07003744 } catch (Exception e) {
3745 needSave = true;
3746 }
3747 if (needSave) {
3748 Log.d(TAG, "going to save icon bitmap for info=" + info);
3749 // This is slower than is ideal, but this only happens once
3750 // or when the app is updated with a new icon.
3751 updateItemInDatabase(context, info);
Joe Onorato56d82912010-03-07 14:32:10 -05003752 }
3753 }
3754
Joe Onorato9c1289c2009-08-17 11:03:03 -04003755 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003756 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003757 * or make a new one.
3758 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003759 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003760 // See if a placeholder was created for us already
3761 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003762 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003763 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003764 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003765 folders.put(id, folderInfo);
3766 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003767 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003768 }
3769
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003770 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003771 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003772 return new Comparator<AppInfo>() {
3773 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003774 if (a.user.equals(b.user)) {
3775 int result = collator.compare(a.title.toString().trim(),
3776 b.title.toString().trim());
3777 if (result == 0) {
3778 result = a.componentName.compareTo(b.componentName);
3779 }
3780 return result;
3781 } else {
3782 // TODO Need to figure out rules for sorting
3783 // profiles, this puts work second.
3784 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003785 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003786 }
Winson Chung11904872012-09-17 16:58:46 -07003787 };
3788 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003789 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3790 = new Comparator<AppInfo>() {
3791 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003792 if (a.firstInstallTime < b.firstInstallTime) return 1;
3793 if (a.firstInstallTime > b.firstInstallTime) return -1;
3794 return 0;
3795 }
3796 };
Winson Chung5308f242011-08-18 12:12:41 -07003797 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3798 if (info.activityInfo != null) {
3799 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3800 } else {
3801 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3802 }
3803 }
Kenny Guyed131872014-04-30 03:02:21 +01003804 public static class ShortcutNameComparator implements Comparator<LauncherActivityInfoCompat> {
Winson Chung11904872012-09-17 16:58:46 -07003805 private Collator mCollator;
Winson Chungc3eecff2011-07-11 17:44:15 -07003806 private HashMap<Object, CharSequence> mLabelCache;
Winson Chung785d2eb2011-04-14 16:08:02 -07003807 ShortcutNameComparator(PackageManager pm) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003808 mLabelCache = new HashMap<Object, CharSequence>();
Winson Chung11904872012-09-17 16:58:46 -07003809 mCollator = Collator.getInstance();
Winson Chungc3eecff2011-07-11 17:44:15 -07003810 }
Kenny Guyed131872014-04-30 03:02:21 +01003811 ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
Winson Chungc3eecff2011-07-11 17:44:15 -07003812 mLabelCache = labelCache;
Winson Chung11904872012-09-17 16:58:46 -07003813 mCollator = Collator.getInstance();
Winson Chung785d2eb2011-04-14 16:08:02 -07003814 }
Kenny Guyed131872014-04-30 03:02:21 +01003815 public final int compare(LauncherActivityInfoCompat a, LauncherActivityInfoCompat b) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003816 String labelA, labelB;
Kenny Guyed131872014-04-30 03:02:21 +01003817 ComponentName keyA = a.getComponentName();
3818 ComponentName keyB = b.getComponentName();
Winson Chung5308f242011-08-18 12:12:41 -07003819 if (mLabelCache.containsKey(keyA)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003820 labelA = mLabelCache.get(keyA).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003821 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003822 labelA = a.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003823
Winson Chung5308f242011-08-18 12:12:41 -07003824 mLabelCache.put(keyA, labelA);
Winson Chungc3eecff2011-07-11 17:44:15 -07003825 }
Winson Chung5308f242011-08-18 12:12:41 -07003826 if (mLabelCache.containsKey(keyB)) {
Sunny Goyal0c4a6442014-07-22 12:27:04 -07003827 labelB = mLabelCache.get(keyB).toString();
Winson Chungc3eecff2011-07-11 17:44:15 -07003828 } else {
Kenny Guyed131872014-04-30 03:02:21 +01003829 labelB = b.getLabel().toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003830
Winson Chung5308f242011-08-18 12:12:41 -07003831 mLabelCache.put(keyB, labelB);
Winson Chungc3eecff2011-07-11 17:44:15 -07003832 }
Winson Chung11904872012-09-17 16:58:46 -07003833 return mCollator.compare(labelA, labelB);
Winson Chung785d2eb2011-04-14 16:08:02 -07003834 }
3835 };
Winson Chung1ed747a2011-05-03 16:18:34 -07003836 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003837 private final AppWidgetManagerCompat mManager;
3838 private final PackageManager mPackageManager;
3839 private final HashMap<Object, String> mLabelCache;
3840 private final Collator mCollator;
3841
3842 WidgetAndShortcutNameComparator(Context context) {
3843 mManager = AppWidgetManagerCompat.getInstance(context);
3844 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003845 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003846 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003847 }
3848 public final int compare(Object a, Object b) {
3849 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003850 if (mLabelCache.containsKey(a)) {
3851 labelA = mLabelCache.get(a);
3852 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003853 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3854 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003855 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003856 mLabelCache.put(a, labelA);
3857 }
3858 if (mLabelCache.containsKey(b)) {
3859 labelB = mLabelCache.get(b);
3860 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003861 labelB = (b instanceof LauncherAppWidgetProviderInfo)
3862 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003863 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003864 mLabelCache.put(b, labelB);
3865 }
Winson Chung11904872012-09-17 16:58:46 -07003866 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003867 }
3868 };
Joe Onoratobe386092009-11-17 17:32:16 -08003869
Sunny Goyal651077b2014-06-30 14:15:31 -07003870 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3871 return (provider != null) && (provider.provider != null)
3872 && (provider.provider.getPackageName() != null);
3873 }
3874
Joe Onoratobe386092009-11-17 17:32:16 -08003875 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003876 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003877 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3878 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3879 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3880 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003881 if (mLoaderTask != null) {
3882 mLoaderTask.dumpState();
3883 } else {
3884 Log.d(TAG, "mLoaderTask=null");
3885 }
Joe Onoratobe386092009-11-17 17:32:16 -08003886 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003887
3888 public Callbacks getCallback() {
3889 return mCallbacks != null ? mCallbacks.get() : null;
3890 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003891}