blob: 2fd9db2c39f9d836f07f94688f5fe4fd50a3519d [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;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040086 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070087 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080088 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040089
Joe Onorato9c1289c2009-08-17 11:03:03 -040090 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070091
Dan Sandlerd5024042014-01-09 15:01:33 -050092 public static final int LOADER_FLAG_NONE = 0;
93 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
94 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
95
Joe Onorato36115782010-06-17 13:28:48 -040096 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050097 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080098
Winson Chungee055712013-07-30 14:46:24 -070099 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800100 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400101
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400102 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400103 private final Object mLock = new Object();
104 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400105 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700106 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
Sunny Goyale0f58d72014-11-10 18:05:31 -0800108 /**
109 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
110 */
111 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
112
Winson Chung81b52252012-08-27 15:34:29 -0700113 // Specific runnable types that are run on the main thread deferred handler, this allows us to
114 // clear all queued binding runnables when the Launcher activity is destroyed.
115 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
116 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
117
Jason Monkbbe1e242014-05-16 17:37:34 -0400118 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700119
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700120 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
121 static {
122 sWorkerThread.start();
123 }
124 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
125
Joe Onoratocc67f472010-06-08 10:54:30 -0700126 // We start off with everything not loaded. After that, we assume that
127 // our monitoring of the package manager provides all updates and we never
128 // need to do a requery. These are only ever touched from the loader thread.
129 private boolean mWorkspaceLoaded;
130 private boolean mAllAppsLoaded;
131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // When we are loading pages synchronously, we can't just post the binding of items on the side
133 // pages as this delays the rotation process. Instead, we wait for a callback from the first
134 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
135 // a normal load, we also clear this set of Runnables.
136 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
137
Joe Onorato9c1289c2009-08-17 11:03:03 -0400138 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700141 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800142
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700143 // The lock that must be acquired before referencing any static bg data structures. Unlike
144 // other locks, this one can generally be held long-term because we never expect any of these
145 // static data structures to be referenced outside of the worker thread except on the first
146 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700147 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
154 // created by LauncherModel that are directly on the home screen (however, no widgets or
155 // shortcuts within folders).
156 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
159 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 new ArrayList<LauncherAppWidgetInfo>();
161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
163 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700164
Adam Cohendcd297f2013-06-18 13:13:40 -0700165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Adam Cohen59400422014-03-05 18:07:04 -0800168 // sBgWidgetProviders is the set of widget providers including custom internal widgets
169 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800170
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700172 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
173 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700174
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 // </ only access in worker thread >
176
177 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
Reena Lee99a73f32011-10-24 17:27:37 -0700179 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700180
Kenny Guyed131872014-04-30 03:02:21 +0100181 private final LauncherAppsCompat mLauncherApps;
182 private final UserManagerCompat mUserManager;
183
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700185 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public int getCurrentWorkspaceScreen();
187 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
189 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700190 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700191 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500192 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800193 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200195 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700196 public void bindAppsAdded(ArrayList<Long> newScreens,
197 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700198 ArrayList<ItemInfo> addAnimated,
199 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200200 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700201 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
202 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
203 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700204 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700205 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700206 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700207 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200208 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100209 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700210 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700211 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700212 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800213 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
214 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400215 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
Winson Chung64359a52013-07-08 17:17:08 -0700217 public interface ItemInfoFilter {
218 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
219 }
220
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800221 public interface ScreenPosProvider {
222 int getScreenIndex(ArrayList<Long> screenIDs);
223 }
224
Bjorn Bringert1307f632013-10-03 22:31:03 +0100225 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800226 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400227
Winson Chungee055712013-07-30 14:46:24 -0700228 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700229 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400230 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
231 // resource string.
232 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
233 ProviderInfo providerInfo =
234 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
235 ProviderInfo redirectProvider =
236 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700237
238 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400239 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700240
241 if (mOldContentProviderExists) {
242 Log.d(TAG, "Old launcher provider exists.");
243 } else {
244 Log.d(TAG, "Old launcher provider does not exist.");
245 }
246
Daniel Sandlere4f98912013-06-25 15:13:26 -0400247 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100248 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800249 mIconCache = iconCache;
250
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400251 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700252 Configuration config = res.getConfiguration();
253 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100254 mLauncherApps = LauncherAppsCompat.getInstance(context);
255 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800256 }
257
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700258 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
259 * posted on the main thread handler. */
260 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700261 runOnMainThread(r, 0);
262 }
263 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700264 if (sWorkerThread.getThreadId() == Process.myTid()) {
265 // If we are on the worker thread, post onto the main handler
266 mHandler.post(r);
267 } else {
268 r.run();
269 }
270 }
271
272 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
273 * posted on the worker thread handler. */
274 private static void runOnWorkerThread(Runnable r) {
275 if (sWorkerThread.getThreadId() == Process.myTid()) {
276 r.run();
277 } else {
278 // If we are not on the worker thread, then post to the worker handler
279 sWorker.post(r);
280 }
281 }
282
Winson Chunge43a1e72014-01-15 10:33:02 -0800283 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
284 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800285 }
286
Sunny Goyale755d462014-07-22 13:48:29 -0700287 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500288 // Process the updated package state
289 Runnable r = new Runnable() {
290 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800291 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500292 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700293 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500294 }
295 }
296 };
297 mHandler.post(r);
298 }
299
Sunny Goyala22666f2014-09-18 13:25:15 -0700300 public void updatePackageBadge(final String packageName) {
301 // Process the updated package badge
302 Runnable r = new Runnable() {
303 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800304 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700305 if (callbacks != null) {
306 callbacks.updatePackageBadge(packageName);
307 }
308 }
309 };
310 mHandler.post(r);
311 }
312
Adam Cohen76a47a12014-02-05 11:47:43 -0800313 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800314 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800315
316 if (allAppsApps == null) {
317 throw new RuntimeException("allAppsApps must not be null");
318 }
319 if (allAppsApps.isEmpty()) {
320 return;
321 }
322
323 // Process the newly added applications and add them to the database first
324 Runnable r = new Runnable() {
325 public void run() {
326 runOnMainThread(new Runnable() {
327 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800328 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800329 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500330 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800331 }
332 }
333 });
334 }
335 };
336 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700337 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800338
339 public void addAndBindAddedWorkspaceApps(final Context context,
340 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800341 addAndBindAddedWorkspaceApps(context, workspaceApps,
342 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800343
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800344 @Override
345 public int getScreenIndex(ArrayList<Long> screenIDs) {
346 return screenIDs.isEmpty() ? 0 : 1;
347 }
348 }, 1, false);
349 }
350
351 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
352 int[] xy, int spanX, int spanY) {
353 LauncherAppState app = LauncherAppState.getInstance();
354 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
355 final int xCount = (int) grid.numColumns;
356 final int yCount = (int) grid.numRows;
357 boolean[][] occupied = new boolean[xCount][yCount];
358 if (occupiedPos != null) {
359 for (Rect r : occupiedPos) {
360 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
361 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
362 occupied[x][y] = true;
363 }
364 }
365 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800366 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800367 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
368 }
369
370 /**
371 * Find a position on the screen for the given size or adds a new screen.
372 * @return screenId and the coordinates for the item.
373 */
374 private static Pair<Long, int[]> findSpaceForItem(
375 Context context,
376 ScreenPosProvider preferredScreen,
377 int fallbackStartScreen,
378 ArrayList<Long> workspaceScreens,
379 ArrayList<Long> addedWorkspaceScreensFinal,
380 int spanX, int spanY) {
381 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
382 // loadWorkspace() may not have been called.
383 final ContentResolver cr = context.getContentResolver();
384 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
385 new String[] {
386 LauncherSettings.Favorites.SCREEN,
387 LauncherSettings.Favorites.CELLX,
388 LauncherSettings.Favorites.CELLY,
389 LauncherSettings.Favorites.SPANX,
390 LauncherSettings.Favorites.SPANY,
391 LauncherSettings.Favorites.CONTAINER
392 },
393 "container=?",
394 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
395 null);
396
397 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
398 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
399 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
400 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
401 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
402 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
403 try {
404 while (c.moveToNext()) {
405 Rect rect = new Rect();
406 rect.left = c.getInt(cellXIndex);
407 rect.top = c.getInt(cellYIndex);
408 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
409 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
410
411 long screenId = c.getInt(screenIndex);
412 ArrayList<Rect> items = screenItems.get(screenId);
413 if (items == null) {
414 items = new ArrayList<Rect>();
415 screenItems.put(screenId, items);
416 }
417 items.add(rect);
418 }
419 } catch (Exception e) {
420 screenItems.clear();
421 } finally {
422 c.close();
423 }
424
425 // Find appropriate space for the item.
426 long screenId = 0;
427 int[] cordinates = new int[2];
428 boolean found = false;
429
430 int screenCount = workspaceScreens.size();
431 // First check the preferred screen.
432 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
433 if (preferredScreenIndex < screenCount) {
434 screenId = workspaceScreens.get(preferredScreenIndex);
435 found = findNextAvailableIconSpaceInScreen(
436 screenItems.get(screenId), cordinates, spanX, spanY);
437 }
438
439 if (!found) {
440 // Search on any of the screens.
441 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
442 screenId = workspaceScreens.get(screen);
443 if (findNextAvailableIconSpaceInScreen(
444 screenItems.get(screenId), cordinates, spanX, spanY)) {
445 // We found a space for it
446 found = true;
447 break;
448 }
449 }
450 }
451
452 if (!found) {
453 // Still no position found. Add a new screen to the end.
454 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
455
456 // Save the screen id for binding in the workspace
457 workspaceScreens.add(screenId);
458 addedWorkspaceScreensFinal.add(screenId);
459
460 // If we still can't find an empty space, then God help us all!!!
461 if (!findNextAvailableIconSpaceInScreen(
462 screenItems.get(screenId), cordinates, spanX, spanY)) {
463 throw new RuntimeException("Can't find space to add the item");
464 }
465 }
466 return Pair.create(screenId, cordinates);
467 }
468
469 /**
470 * Adds the provided items to the workspace.
471 * @param preferredScreen the screen where we should try to add the app first
472 * @param fallbackStartScreen the screen to start search for empty space if
473 * preferredScreen is not available.
474 */
475 public void addAndBindPendingItem(
476 final Context context,
477 final PendingAddItemInfo addInfo,
478 final ScreenPosProvider preferredScreen,
479 final int fallbackStartScreen) {
480 final Callbacks callbacks = getCallback();
481 // Process the newly added applications and add them to the database first
482 Runnable r = new Runnable() {
483 public void run() {
484 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800485 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800486
487 // Find appropriate space for the item.
488 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
489 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
490 addInfo.spanX,
491 addInfo.spanY);
492 final long screenId = coords.first;
493 final int[] cordinates = coords.second;
494
495 // Update the workspace screens
496 updateWorkspaceScreenOrder(context, workspaceScreens);
497 runOnMainThread(new Runnable() {
498 public void run() {
499 Callbacks cb = getCallback();
500 if (callbacks == cb && cb != null) {
501 cb.bindAddScreens(addedWorkspaceScreensFinal);
502 cb.bindAddPendingItem(addInfo,
503 LauncherSettings.Favorites.CONTAINER_DESKTOP,
504 screenId, cordinates, addInfo.spanX, addInfo.spanY);
505 }
506 }
507 });
508 }
509 };
510 runOnWorkerThread(r);
511 }
512
513 /**
514 * Adds the provided items to the workspace.
515 * @param preferredScreen the screen where we should try to add the app first
516 * @param fallbackStartScreen the screen to start search for empty space if
517 * preferredScreen is not available.
518 */
519 public void addAndBindAddedWorkspaceApps(final Context context,
520 final ArrayList<ItemInfo> workspaceApps,
521 final ScreenPosProvider preferredScreen,
522 final int fallbackStartScreen,
523 final boolean allowDuplicate) {
524 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800525 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700526 return;
Winson Chung997a9232013-07-24 15:33:46 -0700527 }
Winson Chung64359a52013-07-08 17:17:08 -0700528 // Process the newly added applications and add them to the database first
529 Runnable r = new Runnable() {
530 public void run() {
531 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
532 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
533
Winson Chung76828c82013-08-19 15:43:29 -0700534 // Get the list of workspace screens. We need to append to this list and
535 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
536 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800537 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700538 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800539 for (ItemInfo item : workspaceApps) {
540 if (!allowDuplicate) {
541 // Short-circuit this logic if the icon exists somewhere on the workspace
542 if (shortcutExists(context, item.title.toString(),
543 item.getIntent(), item.user)) {
544 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700545 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800546 }
Winson Chung76828c82013-08-19 15:43:29 -0700547
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800548 // Find appropriate space for the item.
549 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
550 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
551 1, 1);
552 long screenId = coords.first;
553 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700554
Winson Chung997a9232013-07-24 15:33:46 -0700555 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800556 if (item instanceof ShortcutInfo) {
557 shortcutInfo = (ShortcutInfo) item;
558 } else if (item instanceof AppInfo) {
559 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700560 } else {
561 throw new RuntimeException("Unexpected info type");
562 }
Winson Chung94d67682013-09-25 16:29:40 -0700563
Winson Chung64359a52013-07-08 17:17:08 -0700564 // Add the shortcut to the db
565 addItemToDatabase(context, shortcutInfo,
566 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800567 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700568 // Save the ShortcutInfo for binding in the workspace
569 addedShortcutsFinal.add(shortcutInfo);
570 }
571 }
572
Winson Chung76828c82013-08-19 15:43:29 -0700573 // Update the workspace screens
574 updateWorkspaceScreenOrder(context, workspaceScreens);
575
Adam Cohen76a47a12014-02-05 11:47:43 -0800576 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700577 runOnMainThread(new Runnable() {
578 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800579 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700580 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700581 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
582 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700583 if (!addedShortcutsFinal.isEmpty()) {
584 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
585 long lastScreenId = info.screenId;
586 for (ItemInfo i : addedShortcutsFinal) {
587 if (i.screenId == lastScreenId) {
588 addAnimated.add(i);
589 } else {
590 addNotAnimated.add(i);
591 }
Winson Chung997a9232013-07-24 15:33:46 -0700592 }
593 }
Winson Chungd64d1762013-08-20 14:37:16 -0700594 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800595 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700596 }
Winson Chung64359a52013-07-08 17:17:08 -0700597 }
Winson Chung997a9232013-07-24 15:33:46 -0700598 });
599 }
Winson Chung64359a52013-07-08 17:17:08 -0700600 }
601 };
602 runOnWorkerThread(r);
603 }
604
Winson Chung81b52252012-08-27 15:34:29 -0700605 public void unbindItemInfosAndClearQueuedBindRunnables() {
606 if (sWorkerThread.getThreadId() == Process.myTid()) {
607 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
608 "main thread");
609 }
610
611 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400612 synchronized (mDeferredBindRunnables) {
613 mDeferredBindRunnables.clear();
614 }
Winson Chung81b52252012-08-27 15:34:29 -0700615 // Remove any queued bind runnables
616 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
617 // Unbind all the workspace items
618 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700619 }
620
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700621 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700622 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700623 // Ensure that we don't use the same workspace items data structure on the main thread
624 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700625 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
626 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700627 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700628 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
629 tmpAppWidgets.addAll(sBgAppWidgets);
630 }
631 Runnable r = new Runnable() {
632 @Override
633 public void run() {
634 for (ItemInfo item : tmpWorkspaceItems) {
635 item.unbind();
636 }
637 for (ItemInfo item : tmpAppWidgets) {
638 item.unbind();
639 }
640 }
641 };
642 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700643 }
644
Joe Onorato9c1289c2009-08-17 11:03:03 -0400645 /**
646 * Adds an item to the DB if it was not created previously, or move it to a new
647 * <container, screen, cellX, cellY>
648 */
649 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700650 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400651 if (item.container == ItemInfo.NO_ID) {
652 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400654 } else {
655 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700656 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800657 }
658 }
659
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700660 static void checkItemInfoLocked(
661 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
662 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
663 if (modelItem != null && item != modelItem) {
664 // check all the data is consistent
665 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
666 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
667 ShortcutInfo shortcut = (ShortcutInfo) item;
668 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
669 modelShortcut.intent.filterEquals(shortcut.intent) &&
670 modelShortcut.id == shortcut.id &&
671 modelShortcut.itemType == shortcut.itemType &&
672 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700674 modelShortcut.cellX == shortcut.cellX &&
675 modelShortcut.cellY == shortcut.cellY &&
676 modelShortcut.spanX == shortcut.spanX &&
677 modelShortcut.spanY == shortcut.spanY &&
678 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
679 (modelShortcut.dropPos != null &&
680 shortcut.dropPos != null &&
681 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
682 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
683 // For all intents and purposes, this is the same object
684 return;
685 }
686 }
687
688 // the modelItem needs to match up perfectly with item if our model is
689 // to be consistent with the database-- for now, just require
690 // modelItem == item or the equality check above
691 String msg = "item: " + ((item != null) ? item.toString() : "null") +
692 "modelItem: " +
693 ((modelItem != null) ? modelItem.toString() : "null") +
694 "Error: ItemInfo passed to checkItemInfo doesn't match original";
695 RuntimeException e = new RuntimeException(msg);
696 if (stackTrace != null) {
697 e.setStackTrace(stackTrace);
698 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800699 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700700 }
701 }
702
Michael Jurka816474f2012-06-25 14:49:02 -0700703 static void checkItemInfo(final ItemInfo item) {
704 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
705 final long itemId = item.id;
706 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700707 public void run() {
708 synchronized (sBgLock) {
709 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700710 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700711 }
712 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700713 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700714 }
715
Michael Jurkac9d95c52011-08-29 14:03:34 -0700716 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
717 final ItemInfo item, final String callingFunction) {
718 final long itemId = item.id;
719 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
720 final ContentResolver cr = context.getContentResolver();
721
Adam Cohen487f7dd2012-06-28 18:12:10 -0700722 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700723 Runnable r = new Runnable() {
724 public void run() {
725 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700726 updateItemArrays(item, itemId, stackTrace);
727 }
728 };
729 runOnWorkerThread(r);
730 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700731
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700732 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
733 final ArrayList<ItemInfo> items, final String callingFunction) {
734 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700735
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700736 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
737 Runnable r = new Runnable() {
738 public void run() {
739 ArrayList<ContentProviderOperation> ops =
740 new ArrayList<ContentProviderOperation>();
741 int count = items.size();
742 for (int i = 0; i < count; i++) {
743 ItemInfo item = items.get(i);
744 final long itemId = item.id;
745 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
746 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700747
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700748 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
749 updateItemArrays(item, itemId, stackTrace);
750
751 }
752 try {
753 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
754 } catch (Exception e) {
755 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700756 }
757 }
758 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700759 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700760 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700761
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700762 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
763 // Lock on mBgLock *after* the db operation
764 synchronized (sBgLock) {
765 checkItemInfoLocked(itemId, item, stackTrace);
766
767 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
768 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
769 // Item is in a folder, make sure this folder exists
770 if (!sBgFolders.containsKey(item.container)) {
771 // An items container is being set to a that of an item which is not in
772 // the list of Folders.
773 String msg = "item: " + item + " container being set to: " +
774 item.container + ", not in the list of folders";
775 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700776 }
777 }
778
779 // Items are added/removed from the corresponding FolderInfo elsewhere, such
780 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
781 // that are on the desktop, as appropriate
782 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800783 if (modelItem != null &&
784 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
785 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700786 switch (modelItem.itemType) {
787 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
788 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
789 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
790 if (!sBgWorkspaceItems.contains(modelItem)) {
791 sBgWorkspaceItems.add(modelItem);
792 }
793 break;
794 default:
795 break;
796 }
797 } else {
798 sBgWorkspaceItems.remove(modelItem);
799 }
800 }
801 }
802
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800803 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400804 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700805 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700806 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400808 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 item.cellX = cellX;
810 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700811
Winson Chung3d503fb2011-07-13 17:25:49 -0700812 // We store hotseat items in canonical form which is this orientation invariant position
813 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700815 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700817 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700818 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700819 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400820
821 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400822 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700823 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
824 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800825 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400827
Michael Jurkac9d95c52011-08-29 14:03:34 -0700828 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700829 }
830
831 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700832 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
833 * cellX, cellY have already been updated on the ItemInfos.
834 */
835 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
836 final long container, final int screen) {
837
838 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
839 int count = items.size();
840
841 for (int i = 0; i < count; i++) {
842 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700843 item.container = container;
844
845 // We store hotseat items in canonical form which is this orientation invariant position
846 // in the hotseat
847 if (context instanceof Launcher && screen < 0 &&
848 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700849 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700850 item.cellY);
851 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700852 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700853 }
854
855 final ContentValues values = new ContentValues();
856 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
857 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
858 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800859 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700860 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700861
862 contentValues.add(values);
863 }
864 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
865 }
866
867 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700868 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800869 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700870 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700871 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700872 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800873 item.cellX = cellX;
874 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700875 item.spanX = spanX;
876 item.spanY = spanY;
877
878 // We store hotseat items in canonical form which is this orientation invariant position
879 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700880 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700881 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700882 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700884 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700885 }
Adam Cohend4844c32011-02-18 19:25:06 -0800886
Adam Cohend4844c32011-02-18 19:25:06 -0800887 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800888 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700889 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
890 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800891 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700892 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
893 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700894 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800895
Michael Jurka816474f2012-06-25 14:49:02 -0700896 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700897 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700898
899 /**
900 * Update an item to the database in a specified container.
901 */
902 static void updateItemInDatabase(Context context, final ItemInfo item) {
903 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100904 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700905 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800906 }
907
908 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400909 * Returns true if the shortcuts already exists in the database.
910 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800911 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800912 static boolean shortcutExists(Context context, String title, Intent intent,
913 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400914 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700915 final Intent intentWithPkg, intentWithoutPkg;
916
917 if (intent.getComponent() != null) {
918 // If component is not null, an intent with null package will produce
919 // the same result and should also be a match.
920 if (intent.getPackage() != null) {
921 intentWithPkg = intent;
922 intentWithoutPkg = new Intent(intent).setPackage(null);
923 } else {
924 intentWithPkg = new Intent(intent).setPackage(
925 intent.getComponent().getPackageName());
926 intentWithoutPkg = intent;
927 }
928 } else {
929 intentWithPkg = intent;
930 intentWithoutPkg = intent;
931 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800932 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
933 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400934 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800935 new String[] { "title", "intent", "profileId" },
936 "title=? and (intent=? or intent=?) and profileId=?",
937 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
938 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400939 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800940 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400941 } finally {
942 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700944 }
945
Joe Onorato9c1289c2009-08-17 11:03:03 -0400946 /**
947 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
948 */
949 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
950 final ContentResolver cr = context.getContentResolver();
951 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
952 "_id=? and (itemType=? or itemType=?)",
953 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700954 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700955
Joe Onorato9c1289c2009-08-17 11:03:03 -0400956 try {
957 if (c.moveToFirst()) {
958 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
959 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
960 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
961 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
962 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
963 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800964
Joe Onorato9c1289c2009-08-17 11:03:03 -0400965 FolderInfo folderInfo = null;
966 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700967 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
968 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400969 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700970 }
971
Joe Onorato9c1289c2009-08-17 11:03:03 -0400972 folderInfo.title = c.getString(titleIndex);
973 folderInfo.id = id;
974 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700975 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700976 folderInfo.cellX = c.getInt(cellXIndex);
977 folderInfo.cellY = c.getInt(cellYIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978
979 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700980 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981 } finally {
982 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700983 }
984
985 return null;
986 }
987
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 /**
989 * Add an item to the database in a specified container. Sets the container, screen, cellX and
990 * cellY fields of the item. Also assigns an ID to the item.
991 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700992 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700993 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995 item.cellX = cellX;
996 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700997 // We store hotseat items in canonical form which is this orientation invariant position
998 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700999 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001000 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001005
1006 final ContentValues values = new ContentValues();
1007 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001008 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
Michael Jurka414300a2013-08-27 15:42:35 +02001010 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001011 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001012
Jason Monk8e19cf22014-03-20 15:06:57 -04001013 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001014 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 public void run() {
1016 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1017 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001018
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001019 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001020 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001021 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001022 sBgItemsIdMap.put(item.id, item);
1023 switch (item.itemType) {
1024 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1025 sBgFolders.put(item.id, (FolderInfo) item);
1026 // Fall through
1027 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1028 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1029 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1030 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1031 sBgWorkspaceItems.add(item);
1032 } else {
1033 if (!sBgFolders.containsKey(item.container)) {
1034 // Adding an item to a folder that doesn't exist.
1035 String msg = "adding item: " + item + " to a folder that " +
1036 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001037 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001039 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 break;
1041 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1042 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1043 break;
1044 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001045 }
1046 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001047 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001048 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001049 }
1050
Joe Onorato9c1289c2009-08-17 11:03:03 -04001051 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001052 * Creates a new unique child id, for a given cell span across all layouts.
1053 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001054 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001055 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001056 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001057 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001058 }
1059
Sunny Goyal34942622014-08-29 17:20:55 -07001060 private static ArrayList<ItemInfo> getItemsByPackageName(
1061 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001062 ItemInfoFilter filter = new ItemInfoFilter() {
1063 @Override
1064 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1065 return cn.getPackageName().equals(pn) && info.user.equals(user);
1066 }
1067 };
Sunny Goyal34942622014-08-29 17:20:55 -07001068 return filterItemInfos(sBgItemsIdMap.values(), filter);
1069 }
1070
1071 /**
1072 * Removes all the items from the database corresponding to the specified package.
1073 */
1074 static void deletePackageFromDatabase(Context context, final String pn,
1075 final UserHandleCompat user) {
1076 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001077 }
1078
1079 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001080 * Removes the specified item from the database
1081 * @param context
1082 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001083 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001084 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001085 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1086 items.add(item);
1087 deleteItemsFromDatabase(context, items);
1088 }
1089
1090 /**
1091 * Removes the specified items from the database
1092 * @param context
1093 * @param item
1094 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001095 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001096 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001097
Michael Jurka83df1882011-08-31 20:59:26 -07001098 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001099 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001100 for (ItemInfo item : items) {
1101 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1102 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001103
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001104 // Lock on mBgLock *after* the db operation
1105 synchronized (sBgLock) {
1106 switch (item.itemType) {
1107 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1108 sBgFolders.remove(item.id);
1109 for (ItemInfo info: sBgItemsIdMap.values()) {
1110 if (info.container == item.id) {
1111 // We are deleting a folder which still contains items that
1112 // think they are contained by that folder.
1113 String msg = "deleting a folder (" + item + ") which still " +
1114 "contains items (" + info + ")";
1115 Log.e(TAG, msg);
1116 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001117 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001118 sBgWorkspaceItems.remove(item);
1119 break;
1120 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1121 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1122 sBgWorkspaceItems.remove(item);
1123 break;
1124 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1125 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1126 break;
1127 }
1128 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001129 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001130 }
1131 }
Michael Jurka83df1882011-08-31 20:59:26 -07001132 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001133 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001134 }
1135
1136 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001137 * Update the order of the workspace screens in the database. The array list contains
1138 * a list of screen ids in the order that they should appear.
1139 */
Winson Chungc9168342013-06-26 14:54:55 -07001140 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001141 // Log to disk
1142 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1143 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1144
Winson Chung64359a52013-07-08 17:17:08 -07001145 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001146 final ContentResolver cr = context.getContentResolver();
1147 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1148
1149 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001150 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001151 while (iter.hasNext()) {
1152 long id = iter.next();
1153 if (id < 0) {
1154 iter.remove();
1155 }
1156 }
1157
1158 Runnable r = new Runnable() {
1159 @Override
1160 public void run() {
Yura085c8532014-02-11 15:15:29 +00001161 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001162 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001163 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001164 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001165 for (int i = 0; i < count; i++) {
1166 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001167 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1169 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001170 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 }
Yura085c8532014-02-11 15:15:29 +00001172
1173 try {
1174 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1175 } catch (Exception ex) {
1176 throw new RuntimeException(ex);
1177 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001178
Winson Chungba9c37f2013-08-30 14:11:37 -07001179 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001180 sBgWorkspaceScreens.clear();
1181 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001182 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001183 }
1184 };
1185 runOnWorkerThread(r);
1186 }
1187
1188 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001189 * Remove the contents of the specified folder from the database
1190 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001191 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001192 final ContentResolver cr = context.getContentResolver();
1193
Michael Jurkac9d95c52011-08-29 14:03:34 -07001194 Runnable r = new Runnable() {
1195 public void run() {
1196 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001198 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001199 sBgItemsIdMap.remove(info.id);
1200 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 sBgWorkspaceItems.remove(info);
1202 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001203
Michael Jurkac9d95c52011-08-29 14:03:34 -07001204 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1205 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001206 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001207 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 for (ItemInfo childInfo : info.contents) {
1209 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001211 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001212 }
1213 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001215 }
1216
1217 /**
1218 * Set this as the current Launcher activity object for the loader.
1219 */
1220 public void initialize(Callbacks callbacks) {
1221 synchronized (mLock) {
1222 mCallbacks = new WeakReference<Callbacks>(callbacks);
1223 }
1224 }
1225
Kenny Guyed131872014-04-30 03:02:21 +01001226 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001227 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001228 int op = PackageUpdatedTask.OP_UPDATE;
1229 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1230 user));
1231 }
1232
1233 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001234 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001235 int op = PackageUpdatedTask.OP_REMOVE;
1236 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1237 user));
1238 }
1239
1240 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001241 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001242 int op = PackageUpdatedTask.OP_ADD;
1243 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1244 user));
1245 }
1246
1247 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001248 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001249 boolean replacing) {
1250 if (!replacing) {
1251 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1252 user));
1253 if (mAppsCanBeOnRemoveableStorage) {
1254 // Only rebind if we support removable storage. It catches the
1255 // case where
1256 // apps on the external sd card need to be reloaded
1257 startLoaderFromBackground();
1258 }
1259 } else {
1260 // If we are replacing then just update the packages in the list
1261 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1262 packageNames, user));
1263 }
1264 }
1265
1266 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001267 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001268 boolean replacing) {
1269 if (!replacing) {
1270 enqueuePackageUpdated(new PackageUpdatedTask(
1271 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1272 user));
1273 }
Kenny Guyed131872014-04-30 03:02:21 +01001274 }
1275
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001276 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001277 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1278 * ACTION_PACKAGE_CHANGED.
1279 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001280 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001281 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001282 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001283
Joe Onorato36115782010-06-17 13:28:48 -04001284 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001285 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001286 // If we have changed locale we need to clear out the labels in all apps/workspace.
1287 forceReload();
1288 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1289 // Check if configuration change was an mcc/mnc change which would affect app resources
1290 // and we would need to clear out the labels in all apps/workspace. Same handling as
1291 // above for ACTION_LOCALE_CHANGED
1292 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001293 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001294 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001295 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001296 forceReload();
1297 }
1298 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001299 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001300 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1301 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001302 Callbacks callbacks = getCallback();
1303 if (callbacks != null) {
1304 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001305 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001306 }
1307 }
1308
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001309 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001310 resetLoadedState(true, true);
1311
Reena Lee93f824a2011-09-23 17:20:28 -07001312 // Do this here because if the launcher activity is running it will be restarted.
1313 // If it's not running startLoaderFromBackground will merely tell it that it needs
1314 // to reload.
1315 startLoaderFromBackground();
1316 }
1317
Winson Chungf0c6ae02012-03-21 16:10:31 -07001318 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1319 synchronized (mLock) {
1320 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1321 // mWorkspaceLoaded to true later
1322 stopLoaderLocked();
1323 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1324 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1325 }
1326 }
1327
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001328 /**
1329 * When the launcher is in the background, it's possible for it to miss paired
1330 * configuration changes. So whenever we trigger the loader from the background
1331 * tell the launcher that it needs to re-run the loader when it comes back instead
1332 * of doing it now.
1333 */
1334 public void startLoaderFromBackground() {
1335 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001336 Callbacks callbacks = getCallback();
1337 if (callbacks != null) {
1338 // Only actually run the loader if they're not paused.
1339 if (!callbacks.setLoadOnResume()) {
1340 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001341 }
1342 }
1343 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001344 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001345 }
Joe Onorato36115782010-06-17 13:28:48 -04001346 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001347
Reena Lee93f824a2011-09-23 17:20:28 -07001348 // If there is already a loader task running, tell it to stop.
1349 // returns true if isLaunching() was true on the old task
1350 private boolean stopLoaderLocked() {
1351 boolean isLaunching = false;
1352 LoaderTask oldTask = mLoaderTask;
1353 if (oldTask != null) {
1354 if (oldTask.isLaunching()) {
1355 isLaunching = true;
1356 }
1357 oldTask.stopLocked();
1358 }
1359 return isLaunching;
1360 }
1361
Adam Cohen1a85c582014-09-30 09:48:49 -07001362 public boolean isCurrentCallbacks(Callbacks callbacks) {
1363 return (mCallbacks != null && mCallbacks.get() == callbacks);
1364 }
1365
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001366 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001367 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1368 }
1369
1370 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001371 synchronized (mLock) {
1372 if (DEBUG_LOADERS) {
1373 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1374 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001375
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001376 // Clear any deferred bind-runnables from the synchronized load process
1377 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001378 synchronized (mDeferredBindRunnables) {
1379 mDeferredBindRunnables.clear();
1380 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381
Joe Onorato36115782010-06-17 13:28:48 -04001382 // Don't bother to start the thread if we know it's not going to do anything
1383 if (mCallbacks != null && mCallbacks.get() != null) {
1384 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001385 // also, don't downgrade isLaunching if we're already running
1386 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001387 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001388 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1389 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001390 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1391 } else {
1392 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1393 sWorker.post(mLoaderTask);
1394 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001395 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001396 }
1397 }
1398
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001399 void bindRemainingSynchronousPages() {
1400 // Post the remaining side pages to be loaded
1401 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001402 Runnable[] deferredBindRunnables = null;
1403 synchronized (mDeferredBindRunnables) {
1404 deferredBindRunnables = mDeferredBindRunnables.toArray(
1405 new Runnable[mDeferredBindRunnables.size()]);
1406 mDeferredBindRunnables.clear();
1407 }
1408 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001409 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001410 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 }
1412 }
1413
Joe Onorato36115782010-06-17 13:28:48 -04001414 public void stopLoader() {
1415 synchronized (mLock) {
1416 if (mLoaderTask != null) {
1417 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001418 }
1419 }
Joe Onorato36115782010-06-17 13:28:48 -04001420 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001421
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001422 /**
1423 * Loads the workspace screen ids in an ordered list.
1424 */
1425 private static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001426 final ContentResolver contentResolver = context.getContentResolver();
1427 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001428
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001429 // Get screens ordered by rank.
1430 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1431 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1432 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001433 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001434 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001435 while (sc.moveToNext()) {
1436 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001437 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001438 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001439 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1440 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001441 }
1442 }
1443 } finally {
1444 sc.close();
1445 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001446 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001447 }
1448
Michael Jurkac57b7a82011-08-09 22:02:20 -07001449 public boolean isAllAppsLoaded() {
1450 return mAllAppsLoaded;
1451 }
1452
Winson Chung36a62fe2012-05-06 18:04:42 -07001453 boolean isLoadingWorkspace() {
1454 synchronized (mLock) {
1455 if (mLoaderTask != null) {
1456 return mLoaderTask.isLoadingWorkspace();
1457 }
1458 }
1459 return false;
1460 }
1461
Joe Onorato36115782010-06-17 13:28:48 -04001462 /**
1463 * Runnable for the thread that loads the contents of the launcher:
1464 * - workspace icons
1465 * - widgets
1466 * - all apps icons
1467 */
1468 private class LoaderTask implements Runnable {
1469 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001470 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001471 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001472 private boolean mStopped;
1473 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001474 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001475
Dan Sandlerd5024042014-01-09 15:01:33 -05001476 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001477 mContext = context;
1478 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001479 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001480 }
1481
Joe Onorato36115782010-06-17 13:28:48 -04001482 boolean isLaunching() {
1483 return mIsLaunching;
1484 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001485
Winson Chung36a62fe2012-05-06 18:04:42 -07001486 boolean isLoadingWorkspace() {
1487 return mIsLoadingAndBindingWorkspace;
1488 }
1489
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001490 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001491 mIsLoadingAndBindingWorkspace = true;
1492
Joe Onorato36115782010-06-17 13:28:48 -04001493 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001494 if (DEBUG_LOADERS) {
1495 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001496 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001497
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001498 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001499 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001500 synchronized (LoaderTask.this) {
1501 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001502 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001503 }
1504 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001505 }
1506 }
1507
Joe Onorato36115782010-06-17 13:28:48 -04001508 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001509 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001510 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001511
Joe Onorato36115782010-06-17 13:28:48 -04001512 private void waitForIdle() {
1513 // Wait until the either we're stopped or the other threads are done.
1514 // This way we don't start loading all apps until the workspace has settled
1515 // down.
1516 synchronized (LoaderTask.this) {
1517 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001518
Joe Onorato36115782010-06-17 13:28:48 -04001519 mHandler.postIdle(new Runnable() {
1520 public void run() {
1521 synchronized (LoaderTask.this) {
1522 mLoadAndBindStepFinished = true;
1523 if (DEBUG_LOADERS) {
1524 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001525 }
Joe Onorato36115782010-06-17 13:28:48 -04001526 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001527 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001528 }
Joe Onorato36115782010-06-17 13:28:48 -04001529 });
1530
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001531 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001532 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001533 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1534 // wait no longer than 1sec at a time
1535 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001536 } catch (InterruptedException ex) {
1537 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001538 }
1539 }
Joe Onorato36115782010-06-17 13:28:48 -04001540 if (DEBUG_LOADERS) {
1541 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001542 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001543 + "ms for previous step to finish binding");
1544 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001545 }
Joe Onorato36115782010-06-17 13:28:48 -04001546 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001547
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001548 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001549 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001550 // Ensure that we have a valid page index to load synchronously
1551 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1552 "valid page index");
1553 }
1554 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1555 // Ensure that we don't try and bind a specified page when the pages have not been
1556 // loaded already (we should load everything asynchronously in that case)
1557 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1558 }
1559 synchronized (mLock) {
1560 if (mIsLoaderTaskRunning) {
1561 // Ensure that we are never running the background loading at this point since
1562 // we also touch the background collections
1563 throw new RuntimeException("Error! Background loading is already running");
1564 }
1565 }
1566
1567 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1568 // data structures, we can't allow any other thread to touch that data, but because
1569 // this call is synchronous, we can get away with not locking).
1570
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001571 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001572 // operations from the previous activity. We need to ensure that all queued operations
1573 // are executed before any synchronous binding work is done.
1574 mHandler.flush();
1575
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001576 // Divide the set of loaded items into those that we are binding synchronously, and
1577 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001578 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001579 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1580 // arise from that.
1581 onlyBindAllApps();
1582 }
1583
Joe Onorato36115782010-06-17 13:28:48 -04001584 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001585 synchronized (mLock) {
1586 mIsLoaderTaskRunning = true;
1587 }
Joe Onorato36115782010-06-17 13:28:48 -04001588 // Optimize for end-user experience: if the Launcher is up and // running with the
1589 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1590 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001591 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001592 // Elevate priority when Home launches for the first time to avoid
1593 // starving at boot time. Staring at a blank home is not cool.
1594 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001595 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1596 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001597 android.os.Process.setThreadPriority(mIsLaunching
1598 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1599 }
Winson Chung64359a52013-07-08 17:17:08 -07001600 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001601 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001602
Joe Onorato36115782010-06-17 13:28:48 -04001603 if (mStopped) {
1604 break keep_running;
1605 }
1606
1607 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1608 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001609 synchronized (mLock) {
1610 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001611 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001612 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613 }
1614 }
Joe Onorato36115782010-06-17 13:28:48 -04001615 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001616
1617 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001618 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1619 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001620
1621 // Restore the default thread priority after we are done loading items
1622 synchronized (mLock) {
1623 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1624 }
Joe Onorato36115782010-06-17 13:28:48 -04001625 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001626
Joe Onorato36115782010-06-17 13:28:48 -04001627 // Clear out this reference, otherwise we end up holding it until all of the
1628 // callback runnables are done.
1629 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001630
Joe Onorato36115782010-06-17 13:28:48 -04001631 synchronized (mLock) {
1632 // If we are still the last one to be scheduled, remove ourselves.
1633 if (mLoaderTask == this) {
1634 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001635 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001636 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001637 }
Joe Onorato36115782010-06-17 13:28:48 -04001638 }
1639
1640 public void stopLocked() {
1641 synchronized (LoaderTask.this) {
1642 mStopped = true;
1643 this.notify();
1644 }
1645 }
1646
1647 /**
1648 * Gets the callbacks object. If we've been stopped, or if the launcher object
1649 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1650 * object that was around when the deferred message was scheduled, and if there's
1651 * a new Callbacks object around then also return null. This will save us from
1652 * calling onto it with data that will be ignored.
1653 */
1654 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1655 synchronized (mLock) {
1656 if (mStopped) {
1657 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001658 }
Joe Onorato36115782010-06-17 13:28:48 -04001659
1660 if (mCallbacks == null) {
1661 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663
1664 final Callbacks callbacks = mCallbacks.get();
1665 if (callbacks != oldCallbacks) {
1666 return null;
1667 }
1668 if (callbacks == null) {
1669 Log.w(TAG, "no mCallbacks");
1670 return null;
1671 }
1672
1673 return callbacks;
1674 }
1675 }
1676
1677 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001678 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001679 LauncherAppState app = LauncherAppState.getInstance();
1680 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001681 final int countX = (int) grid.numColumns;
1682 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001683
Adam Cohendcd297f2013-06-18 13:13:40 -07001684 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001685 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001686 // Return early if we detect that an item is under the hotseat button
1687 if (mCallbacks == null ||
1688 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001689 Log.e(TAG, "Error loading shortcut into hotseat " + item
1690 + " into position (" + item.screenId + ":" + item.cellX + ","
1691 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001692 return false;
1693 }
1694
Dan Sandler295ae182013-12-10 16:05:47 -05001695 final ItemInfo[][] hotseatItems =
1696 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1697
Adam Cohenae4409d2013-11-26 10:34:59 -08001698 if (item.screenId >= grid.numHotseatIcons) {
1699 Log.e(TAG, "Error loading shortcut " + item
1700 + " into hotseat position " + item.screenId
1701 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1702 + ")");
1703 return false;
1704 }
1705
Dan Sandler295ae182013-12-10 16:05:47 -05001706 if (hotseatItems != null) {
1707 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001708 Log.e(TAG, "Error loading shortcut into hotseat " + item
1709 + " into position (" + item.screenId + ":" + item.cellX + ","
1710 + item.cellY + ") occupied by "
1711 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1712 [(int) item.screenId][0]);
1713 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001714 } else {
1715 hotseatItems[(int) item.screenId][0] = item;
1716 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001717 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001718 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001719 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001720 items[(int) item.screenId][0] = item;
1721 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001722 return true;
1723 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001724 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1725 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001726 return true;
1727 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001728
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001730 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001731 occupied.put(item.screenId, items);
1732 }
1733
Dan Sandler295ae182013-12-10 16:05:47 -05001734 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001735 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1736 item.cellX < 0 || item.cellY < 0 ||
1737 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1738 Log.e(TAG, "Error loading shortcut " + item
1739 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1740 + item.cellX + "," + item.cellY
1741 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1742 return false;
1743 }
1744
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001745 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001746 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1747 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001748 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001749 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001750 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001751 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001752 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001753 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001754 return false;
1755 }
1756 }
1757 }
1758 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1759 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001760 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001761 }
1762 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001763
Joe Onorato36115782010-06-17 13:28:48 -04001764 return true;
1765 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001766
Winson Chungba9c37f2013-08-30 14:11:37 -07001767 /** Clears all the sBg data structures */
1768 private void clearSBgDataStructures() {
1769 synchronized (sBgLock) {
1770 sBgWorkspaceItems.clear();
1771 sBgAppWidgets.clear();
1772 sBgFolders.clear();
1773 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001774 sBgWorkspaceScreens.clear();
1775 }
1776 }
1777
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001778 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001779 // Log to disk
1780 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1781
Joe Onorato36115782010-06-17 13:28:48 -04001782 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001783
Joe Onorato36115782010-06-17 13:28:48 -04001784 final Context context = mContext;
1785 final ContentResolver contentResolver = context.getContentResolver();
1786 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001787 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001788 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1789 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001790 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001791
Winson Chung892c74d2013-08-22 16:15:50 -07001792 LauncherAppState app = LauncherAppState.getInstance();
1793 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1794 int countX = (int) grid.numColumns;
1795 int countY = (int) grid.numRows;
1796
Dan Sandlerd5024042014-01-09 15:01:33 -05001797 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1798 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1799 LauncherAppState.getLauncherProvider().deleteDatabase();
1800 }
1801
1802 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1803 // append the user's Launcher2 shortcuts
1804 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1805 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1806 } else {
1807 // Make sure the default workspace is loaded
1808 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001809 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001810 }
Adam Cohene25af792013-06-06 23:08:25 -07001811
Winson Chung2abf94d2012-07-18 18:16:38 -07001812 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001813 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001814 final HashSet<String> installingPkgs = PackageInstallerCompat
1815 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001816
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001817 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001818 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001819 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001820 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001821 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001822
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001823 // +1 for the hotseat (it can be larger than the workspace)
1824 // Load workspace in reverse order to ensure that latest items are loaded first (and
1825 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001826 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001827
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 try {
1829 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1830 final int intentIndex = c.getColumnIndexOrThrow
1831 (LauncherSettings.Favorites.INTENT);
1832 final int titleIndex = c.getColumnIndexOrThrow
1833 (LauncherSettings.Favorites.TITLE);
1834 final int iconTypeIndex = c.getColumnIndexOrThrow(
1835 LauncherSettings.Favorites.ICON_TYPE);
1836 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1837 final int iconPackageIndex = c.getColumnIndexOrThrow(
1838 LauncherSettings.Favorites.ICON_PACKAGE);
1839 final int iconResourceIndex = c.getColumnIndexOrThrow(
1840 LauncherSettings.Favorites.ICON_RESOURCE);
1841 final int containerIndex = c.getColumnIndexOrThrow(
1842 LauncherSettings.Favorites.CONTAINER);
1843 final int itemTypeIndex = c.getColumnIndexOrThrow(
1844 LauncherSettings.Favorites.ITEM_TYPE);
1845 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1846 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001847 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1848 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001849 final int screenIndex = c.getColumnIndexOrThrow(
1850 LauncherSettings.Favorites.SCREEN);
1851 final int cellXIndex = c.getColumnIndexOrThrow
1852 (LauncherSettings.Favorites.CELLX);
1853 final int cellYIndex = c.getColumnIndexOrThrow
1854 (LauncherSettings.Favorites.CELLY);
1855 final int spanXIndex = c.getColumnIndexOrThrow
1856 (LauncherSettings.Favorites.SPANX);
1857 final int spanYIndex = c.getColumnIndexOrThrow(
1858 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001859 final int rankIndex = c.getColumnIndexOrThrow(
1860 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001861 final int restoredIndex = c.getColumnIndexOrThrow(
1862 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001863 final int profileIdIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001865 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1866 //final int displayModeIndex = c.getColumnIndexOrThrow(
1867 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001868
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001869 ShortcutInfo info;
1870 String intentDescription;
1871 LauncherAppWidgetInfo appWidgetInfo;
1872 int container;
1873 long id;
1874 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001875 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001876
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001877 while (!mStopped && c.moveToNext()) {
1878 try {
1879 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001880 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001881 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001882
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 switch (itemType) {
1884 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1885 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001886 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001888 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001889 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001890 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001891 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001892 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001893 if (user == null) {
1894 // User has been deleted remove the item.
1895 itemsToRemove.add(id);
1896 continue;
1897 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001898 try {
1899 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001900 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001901 if (cn != null && cn.getPackageName() != null) {
1902 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1903 cn.getPackageName(), user);
1904 boolean validComponent = validPkg &&
1905 launcherApps.isActivityEnabledForProfile(cn, user);
1906
1907 if (validComponent) {
1908 if (restored) {
1909 // no special handling necessary for this item
1910 restoredRows.add(id);
1911 restored = false;
1912 }
1913 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001914 intent = null;
1915 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1916 // We allow auto install apps to have their intent
1917 // updated after an install.
1918 intent = manager.getLaunchIntentForPackage(
1919 cn.getPackageName());
1920 if (intent != null) {
1921 ContentValues values = new ContentValues();
1922 values.put(LauncherSettings.Favorites.INTENT,
1923 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001924 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001925 }
1926 }
1927
1928 if (intent == null) {
1929 // The app is installed but the component is no
1930 // longer available.
1931 Launcher.addDumpLog(TAG,
1932 "Invalid component removed: " + cn, true);
1933 itemsToRemove.add(id);
1934 continue;
1935 } else {
1936 // no special handling necessary for this item
1937 restoredRows.add(id);
1938 restored = false;
1939 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001940 } else if (restored) {
1941 // Package is not yet available but might be
1942 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001943 Launcher.addDumpLog(TAG,
1944 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001945
1946 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1947 // Restore has started once.
1948 } else if (installingPkgs.contains(cn.getPackageName())) {
1949 // App restore has started. Update the flag
1950 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1951 ContentValues values = new ContentValues();
1952 values.put(LauncherSettings.Favorites.RESTORED,
1953 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001954 updateItem(id, values);
1955 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1956 // This is a common app. Try to replace this.
1957 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1958 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1959 if (parser.findDefaultApp()) {
1960 // Default app found. Replace it.
1961 intent = parser.parsedIntent;
1962 cn = intent.getComponent();
1963 ContentValues values = parser.parsedValues;
1964 values.put(LauncherSettings.Favorites.RESTORED, 0);
1965 updateItem(id, values);
1966 restored = false;
1967 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001968
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001969 } else if (REMOVE_UNRESTORED_ICONS) {
1970 Launcher.addDumpLog(TAG,
1971 "Unrestored package removed: " + cn, true);
1972 itemsToRemove.add(id);
1973 continue;
1974 }
Sunny Goyal94485362014-09-18 16:13:58 -07001975 } else if (REMOVE_UNRESTORED_ICONS) {
1976 Launcher.addDumpLog(TAG,
1977 "Unrestored package removed: " + cn, true);
1978 itemsToRemove.add(id);
1979 continue;
1980 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001981 } else if (launcherApps.isAppEnabled(
1982 manager, cn.getPackageName(),
1983 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1984 // Package is present but not available.
1985 allowMissingTarget = true;
1986 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1987 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001988 // SdCard is not ready yet. Package might get available,
1989 // once it is ready.
1990 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1991 + " (check again later)", true);
1992 HashSet<String> pkgs = sPendingPackages.get(user);
1993 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001994 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001995 sPendingPackages.put(user, pkgs);
1996 }
1997 pkgs.add(cn.getPackageName());
1998 allowMissingTarget = true;
1999 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002000
2001 } else {
2002 // Do not wait for external media load anymore.
2003 // Log the invalid package, and remove it
2004 Launcher.addDumpLog(TAG,
2005 "Invalid package removed: " + cn, true);
2006 itemsToRemove.add(id);
2007 continue;
Winson Chungee055712013-07-30 14:46:24 -07002008 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002009 } else if (cn == null) {
2010 // For shortcuts with no component, keep them as they are
2011 restoredRows.add(id);
2012 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002013 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002014 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002015 Launcher.addDumpLog(TAG,
2016 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002017 continue;
2018 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002019
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002020 if (itemReplaced) {
2021 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002022 info = getAppShortcutInfo(manager, intent, user, context, null,
2023 iconIndex, titleIndex, false);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002024 } else {
2025 // Don't replace items for other profiles.
2026 itemsToRemove.add(id);
2027 continue;
2028 }
2029 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002030 if (user.equals(UserHandleCompat.myUserHandle())) {
2031 Launcher.addDumpLog(TAG,
2032 "constructing info for partially restored package",
2033 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002034 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002035 intent = getRestoredItemIntent(c, context, intent);
2036 } else {
2037 // Don't restore items for other profiles.
2038 itemsToRemove.add(id);
2039 continue;
2040 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002041 } else if (itemType ==
2042 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002043 info = getAppShortcutInfo(manager, intent, user, context, c,
2044 iconIndex, titleIndex, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002045 } else {
2046 info = getShortcutInfo(c, context, iconTypeIndex,
2047 iconPackageIndex, iconResourceIndex, iconIndex,
2048 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002049
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002050 // App shortcuts that used to be automatically added to Launcher
2051 // didn't always have the correct intent flags set, so do that
2052 // here
2053 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002054 intent.getCategories() != null &&
2055 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002056 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 intent.addFlags(
2058 Intent.FLAG_ACTIVITY_NEW_TASK |
2059 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2060 }
Michael Jurka96879562012-03-22 05:54:33 -07002061 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002062
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002063 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002064 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 container = c.getInt(containerIndex);
2067 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002068 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 info.cellX = c.getInt(cellXIndex);
2070 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002071 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002072 info.spanX = 1;
2073 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002074 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002075 info.isDisabled = disabledState;
2076 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2077 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2078 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002079
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002080 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002081 if (!checkItemPlacement(occupied, info)) {
2082 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002083 break;
2084 }
2085
2086 switch (container) {
2087 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2088 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2089 sBgWorkspaceItems.add(info);
2090 break;
2091 default:
2092 // Item is in a user folder
2093 FolderInfo folderInfo =
2094 findOrMakeFolder(sBgFolders, container);
2095 folderInfo.add(info);
2096 break;
2097 }
2098 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002099 } else {
2100 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002101 }
2102 break;
2103
2104 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2105 id = c.getLong(idIndex);
2106 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2107
2108 folderInfo.title = c.getString(titleIndex);
2109 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002110 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002112 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002113 folderInfo.cellX = c.getInt(cellXIndex);
2114 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002115 folderInfo.spanX = 1;
2116 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002117
Daniel Sandler8802e962010-05-26 16:28:16 -04002118 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002119 if (!checkItemPlacement(occupied, folderInfo)) {
2120 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002121 break;
2122 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002123
Joe Onorato9c1289c2009-08-17 11:03:03 -04002124 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002125 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2126 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2127 sBgWorkspaceItems.add(folderInfo);
2128 break;
Joe Onorato36115782010-06-17 13:28:48 -04002129 }
Joe Onorato17a89222011-02-08 17:26:11 -08002130
Chris Wrenf4d08112014-01-16 18:13:56 -05002131 if (restored) {
2132 // no special handling required for restored folders
2133 restoredRows.add(id);
2134 }
2135
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002136 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2137 sBgFolders.put(folderInfo.id, folderInfo);
2138 break;
2139
2140 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002141 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002143 boolean customWidget = itemType ==
2144 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2145
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002146 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002147 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002148 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002149 final ComponentName component =
2150 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002151
Sunny Goyal651077b2014-06-30 14:15:31 -07002152 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002153 final boolean isIdValid = (restoreStatus &
2154 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002155
Sunny Goyalff572272014-07-23 13:58:07 -07002156 final boolean wasProviderReady = (restoreStatus &
2157 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002158
Adam Cohen59400422014-03-05 18:07:04 -08002159 final LauncherAppWidgetProviderInfo provider =
2160 LauncherModel.getProviderInfo(context,
2161 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002162
2163 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002164 if (!isSafeMode && !customWidget &&
2165 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002166 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002167 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002168
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002169 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002170 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002171 itemsToRemove.add(id);
2172 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002173 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002174 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2175 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002176
2177 if (!customWidget) {
2178 int[] minSpan =
2179 Launcher.getMinSpanForWidget(context, provider);
2180 appWidgetInfo.minSpanX = minSpan[0];
2181 appWidgetInfo.minSpanY = minSpan[1];
2182 }
Sunny Goyalff572272014-07-23 13:58:07 -07002183
2184 int status = restoreStatus;
2185 if (!wasProviderReady) {
2186 // If provider was not previously ready, update the
2187 // status and UI flag.
2188
2189 // Id would be valid only if the widget restore broadcast was received.
2190 if (isIdValid) {
2191 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2192 } else {
2193 status &= ~LauncherAppWidgetInfo
2194 .FLAG_PROVIDER_NOT_READY;
2195 }
2196 }
2197 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002198 } else {
2199 Log.v(TAG, "Widget restore pending id=" + id
2200 + " appWidgetId=" + appWidgetId
2201 + " status =" + restoreStatus);
2202 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002203 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002204 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002205
2206 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2207 // Restore has started once.
2208 } else if (installingPkgs.contains(component.getPackageName())) {
2209 // App restore has started. Update the flag
2210 appWidgetInfo.restoreStatus |=
2211 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002212 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002213 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002214 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002215 itemsToRemove.add(id);
2216 continue;
2217 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002218 }
Sunny Goyalff572272014-07-23 13:58:07 -07002219
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002220 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002221 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002222 appWidgetInfo.cellX = c.getInt(cellXIndex);
2223 appWidgetInfo.cellY = c.getInt(cellYIndex);
2224 appWidgetInfo.spanX = c.getInt(spanXIndex);
2225 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002226
Adam Cohen59400422014-03-05 18:07:04 -08002227 if (!customWidget) {
2228 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2229 appWidgetInfo.minSpanX = minSpan[0];
2230 appWidgetInfo.minSpanY = minSpan[1];
2231 }
2232
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002233 container = c.getInt(containerIndex);
2234 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2235 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2236 Log.e(TAG, "Widget found where container != " +
2237 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2238 continue;
2239 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240
Adam Cohene25af792013-06-06 23:08:25 -07002241 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002242 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002243 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2244 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 break;
2246 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002247
Adam Cohen59400422014-03-05 18:07:04 -08002248 if (!customWidget) {
2249 String providerName =
2250 appWidgetInfo.providerName.flattenToString();
2251 if (!providerName.equals(savedProvider) ||
2252 (appWidgetInfo.restoreStatus != restoreStatus)) {
2253 ContentValues values = new ContentValues();
2254 values.put(
2255 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2256 providerName);
2257 values.put(LauncherSettings.Favorites.RESTORED,
2258 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002259 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002260 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002261 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2263 sBgAppWidgets.add(appWidgetInfo);
2264 }
Joe Onorato36115782010-06-17 13:28:48 -04002265 break;
2266 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002267 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002268 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002269 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002270 }
2271 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002272 if (c != null) {
2273 c.close();
2274 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 }
2276
Winson Chungba9c37f2013-08-30 14:11:37 -07002277 // Break early if we've stopped loading
2278 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002279 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002280 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002281 }
2282
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002283 if (itemsToRemove.size() > 0) {
2284 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002285 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002286 // Remove dead items
2287 for (long id : itemsToRemove) {
2288 if (DEBUG_LOADERS) {
2289 Log.d(TAG, "Removed id = " + id);
2290 }
2291 // Don't notify content observers
2292 try {
2293 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2294 null, null);
2295 } catch (RemoteException e) {
2296 Log.w(TAG, "Could not remove id = " + id);
2297 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002298 }
2299 }
2300
Chris Wrenf4d08112014-01-16 18:13:56 -05002301 if (restoredRows.size() > 0) {
2302 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002303 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002304 // Update restored items that no longer require special handling
2305 try {
2306 StringBuilder selectionBuilder = new StringBuilder();
2307 selectionBuilder.append(LauncherSettings.Favorites._ID);
2308 selectionBuilder.append(" IN (");
2309 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2310 selectionBuilder.append(")");
2311 ContentValues values = new ContentValues();
2312 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002313 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002314 values, selectionBuilder.toString(), null);
2315 } catch (RemoteException e) {
2316 Log.w(TAG, "Could not update restored rows");
2317 }
2318 }
2319
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002320 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2321 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002322 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002323 null, sWorker);
2324 }
2325
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002326 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2327 // Log to disk
2328 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2329 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002330
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002331 // Remove any empty screens
2332 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2333 for (ItemInfo item: sBgItemsIdMap.values()) {
2334 long screenId = item.screenId;
2335 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2336 unusedScreens.contains(screenId)) {
2337 unusedScreens.remove(screenId);
2338 }
2339 }
2340
2341 // If there are any empty screens remove them, and update.
2342 if (unusedScreens.size() != 0) {
2343 // Log to disk
2344 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2345 TextUtils.join(", ", unusedScreens), true);
2346
2347 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002348 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002349 }
2350
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002351 if (DEBUG_LOADERS) {
2352 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2353 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002354 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002355 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002356 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002357
Daniel Sandler566da102013-06-25 23:43:45 -04002358 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002359 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002360 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002361 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 line += " | ";
2363 }
Winson Chung892c74d2013-08-22 16:15:50 -07002364 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002365 ItemInfo[][] screen = occupied.get(screenId);
2366 if (x < screen.length && y < screen[x].length) {
2367 line += (screen[x][y] != null) ? "#" : ".";
2368 } else {
2369 line += "!";
2370 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002371 }
Joe Onorato36115782010-06-17 13:28:48 -04002372 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002373 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002374 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002375 }
Joe Onorato36115782010-06-17 13:28:48 -04002376 }
Adam Cohene25af792013-06-06 23:08:25 -07002377 }
2378
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002379 /**
2380 * Partially updates the item without any notification. Must be called on the worker thread.
2381 */
2382 private void updateItem(long itemId, ContentValues update) {
2383 mContext.getContentResolver().update(
2384 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2385 update,
2386 BaseColumns._ID + "= ?",
2387 new String[]{Long.toString(itemId)});
2388 }
2389
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002390 /** Filters the set of items who are directly or indirectly (via another container) on the
2391 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002392 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002393 ArrayList<ItemInfo> allWorkspaceItems,
2394 ArrayList<ItemInfo> currentScreenItems,
2395 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002396 // Purge any null ItemInfos
2397 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2398 while (iter.hasNext()) {
2399 ItemInfo i = iter.next();
2400 if (i == null) {
2401 iter.remove();
2402 }
2403 }
2404
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002405 // Order the set of items by their containers first, this allows use to walk through the
2406 // list sequentially, build up a list of containers that are in the specified screen,
2407 // as well as all items in those containers.
2408 Set<Long> itemsOnScreen = new HashSet<Long>();
2409 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2410 @Override
2411 public int compare(ItemInfo lhs, ItemInfo rhs) {
2412 return (int) (lhs.container - rhs.container);
2413 }
2414 });
2415 for (ItemInfo info : allWorkspaceItems) {
2416 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002417 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002418 currentScreenItems.add(info);
2419 itemsOnScreen.add(info.id);
2420 } else {
2421 otherScreenItems.add(info);
2422 }
2423 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2424 currentScreenItems.add(info);
2425 itemsOnScreen.add(info.id);
2426 } else {
2427 if (itemsOnScreen.contains(info.container)) {
2428 currentScreenItems.add(info);
2429 itemsOnScreen.add(info.id);
2430 } else {
2431 otherScreenItems.add(info);
2432 }
2433 }
2434 }
2435 }
2436
2437 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002438 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002439 ArrayList<LauncherAppWidgetInfo> appWidgets,
2440 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2441 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002442
2443 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002444 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002445 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002446 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002447 currentScreenWidgets.add(widget);
2448 } else {
2449 otherScreenWidgets.add(widget);
2450 }
2451 }
2452 }
2453
2454 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002455 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 HashMap<Long, ItemInfo> itemsIdMap,
2457 HashMap<Long, FolderInfo> folders,
2458 HashMap<Long, FolderInfo> currentScreenFolders,
2459 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002460
2461 for (long id : folders.keySet()) {
2462 ItemInfo info = itemsIdMap.get(id);
2463 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002464 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002465 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002466 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467 currentScreenFolders.put(id, folder);
2468 } else {
2469 otherScreenFolders.put(id, folder);
2470 }
2471 }
2472 }
2473
2474 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2475 * right) */
2476 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002477 final LauncherAppState app = LauncherAppState.getInstance();
2478 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002479 // XXX: review this
2480 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002481 @Override
2482 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002483 int cellCountX = (int) grid.numColumns;
2484 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002485 int screenOffset = cellCountX * cellCountY;
2486 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002487 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002488 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002489 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002490 rhs.cellY * cellCountX + rhs.cellX);
2491 return (int) (lr - rr);
2492 }
2493 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002494 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002495
Adam Cohendcd297f2013-06-18 13:13:40 -07002496 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2497 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002498 final Runnable r = new Runnable() {
2499 @Override
2500 public void run() {
2501 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2502 if (callbacks != null) {
2503 callbacks.bindScreens(orderedScreens);
2504 }
2505 }
2506 };
2507 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2508 }
2509
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002510 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2511 final ArrayList<ItemInfo> workspaceItems,
2512 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2513 final HashMap<Long, FolderInfo> folders,
2514 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002515
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002516 final boolean postOnMainThread = (deferredBindRunnables != null);
2517
2518 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002519 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002521 final int start = i;
2522 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 final Runnable r = new Runnable() {
2524 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002525 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002526 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002527 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002528 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2529 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002530 }
2531 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002532 };
2533 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002534 synchronized (deferredBindRunnables) {
2535 deferredBindRunnables.add(r);
2536 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002537 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002538 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 }
Joe Onorato36115782010-06-17 13:28:48 -04002540 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002541
2542 // Bind the folders
2543 if (!folders.isEmpty()) {
2544 final Runnable r = new Runnable() {
2545 public void run() {
2546 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2547 if (callbacks != null) {
2548 callbacks.bindFolders(folders);
2549 }
2550 }
2551 };
2552 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002553 synchronized (deferredBindRunnables) {
2554 deferredBindRunnables.add(r);
2555 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002556 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002557 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558 }
2559 }
2560
2561 // Bind the widgets, one at a time
2562 N = appWidgets.size();
2563 for (int i = 0; i < N; i++) {
2564 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2565 final Runnable r = new Runnable() {
2566 public void run() {
2567 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2568 if (callbacks != null) {
2569 callbacks.bindAppWidget(widget);
2570 }
2571 }
2572 };
2573 if (postOnMainThread) {
2574 deferredBindRunnables.add(r);
2575 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002576 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002577 }
2578 }
2579 }
2580
2581 /**
2582 * Binds all loaded data to actual views on the main thread.
2583 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002584 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002585 final long t = SystemClock.uptimeMillis();
2586 Runnable r;
2587
2588 // Don't use these two variables in any of the callback runnables.
2589 // Otherwise we hold a reference to them.
2590 final Callbacks oldCallbacks = mCallbacks.get();
2591 if (oldCallbacks == null) {
2592 // This launcher has exited and nobody bothered to tell us. Just bail.
2593 Log.w(TAG, "LoaderTask running with no launcher");
2594 return;
2595 }
2596
Winson Chung9b9fb962013-11-15 15:39:34 -08002597 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2599 ArrayList<LauncherAppWidgetInfo> appWidgets =
2600 new ArrayList<LauncherAppWidgetInfo>();
2601 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2602 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002603 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002604 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002605 workspaceItems.addAll(sBgWorkspaceItems);
2606 appWidgets.addAll(sBgAppWidgets);
2607 folders.putAll(sBgFolders);
2608 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002609 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002610 }
2611
Derek Prothro7aff3992013-12-10 14:00:37 -05002612 final boolean isLoadingSynchronously =
2613 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002614 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002615 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002616 if (currScreen >= orderedScreenIds.size()) {
2617 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002618 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002619 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002620 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002621 final long currentScreenId = currentScreen < 0
2622 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002623
2624 // Load all the items that are on the current page first (and in the process, unbind
2625 // all the existing workspace items before we call startBinding() below.
2626 unbindWorkspaceItemsOnMainThread();
2627
2628 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002629 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2630 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2631 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2632 new ArrayList<LauncherAppWidgetInfo>();
2633 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2634 new ArrayList<LauncherAppWidgetInfo>();
2635 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2636 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2637
Winson Chung9b9fb962013-11-15 15:39:34 -08002638 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002639 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002640 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002641 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002642 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002643 otherFolders);
2644 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2645 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2646
2647 // Tell the workspace that we're about to start binding items
2648 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002649 public void run() {
2650 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2651 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002653 }
2654 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655 };
Winson Chung81b52252012-08-27 15:34:29 -07002656 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002657
Adam Cohendcd297f2013-06-18 13:13:40 -07002658 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2659
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002660 // Load items on the current page
2661 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2662 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002663 if (isLoadingSynchronously) {
2664 r = new Runnable() {
2665 public void run() {
2666 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002667 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002668 callbacks.onPageBoundSynchronously(currentScreen);
2669 }
2670 }
2671 };
Winson Chung81b52252012-08-27 15:34:29 -07002672 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002673 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002674
Winson Chung4a2afa32012-07-19 14:53:05 -07002675 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2676 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002677 synchronized (mDeferredBindRunnables) {
2678 mDeferredBindRunnables.clear();
2679 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002680 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002681 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002682
2683 // Tell the workspace that we're done binding items
2684 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002685 public void run() {
2686 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2687 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002688 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002690
Winson Chung98e030b2012-05-07 16:01:11 -07002691 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002692 if (DEBUG_LOADERS) {
2693 Log.d(TAG, "bound workspace in "
2694 + (SystemClock.uptimeMillis()-t) + "ms");
2695 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002696
2697 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002698 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002699 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002700 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002701 synchronized (mDeferredBindRunnables) {
2702 mDeferredBindRunnables.add(r);
2703 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002704 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002705 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002706 }
Joe Onorato36115782010-06-17 13:28:48 -04002707 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002708
Joe Onorato36115782010-06-17 13:28:48 -04002709 private void loadAndBindAllApps() {
2710 if (DEBUG_LOADERS) {
2711 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2712 }
2713 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002714 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002715 synchronized (LoaderTask.this) {
2716 if (mStopped) {
2717 return;
2718 }
2719 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002720 }
Joe Onorato36115782010-06-17 13:28:48 -04002721 } else {
2722 onlyBindAllApps();
2723 }
2724 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002725
Joe Onorato36115782010-06-17 13:28:48 -04002726 private void onlyBindAllApps() {
2727 final Callbacks oldCallbacks = mCallbacks.get();
2728 if (oldCallbacks == null) {
2729 // This launcher has exited and nobody bothered to tell us. Just bail.
2730 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2731 return;
2732 }
2733
2734 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002735 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002736 final ArrayList<AppInfo> list
2737 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002738 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002739 public void run() {
2740 final long t = SystemClock.uptimeMillis();
2741 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2742 if (callbacks != null) {
2743 callbacks.bindAllApplications(list);
2744 }
2745 if (DEBUG_LOADERS) {
2746 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2747 + (SystemClock.uptimeMillis()-t) + "ms");
2748 }
2749 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002750 };
2751 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002752 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002753 r.run();
2754 } else {
2755 mHandler.post(r);
2756 }
Joe Onorato36115782010-06-17 13:28:48 -04002757 }
2758
Winson Chung64359a52013-07-08 17:17:08 -07002759 private void loadAllApps() {
2760 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002761
Joe Onorato36115782010-06-17 13:28:48 -04002762 final Callbacks oldCallbacks = mCallbacks.get();
2763 if (oldCallbacks == null) {
2764 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002765 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002766 return;
2767 }
2768
2769 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2770 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2771
Kenny Guyed131872014-04-30 03:02:21 +01002772 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2773
Winson Chung64359a52013-07-08 17:17:08 -07002774 // Clear the list of apps
2775 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002776 SharedPreferences prefs = mContext.getSharedPreferences(
2777 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002778 for (UserHandleCompat user : profiles) {
2779 // Query for the set of apps
2780 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2781 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2782 if (DEBUG_LOADERS) {
2783 Log.d(TAG, "getActivityList took "
2784 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2785 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2786 }
2787 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002788 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002789 if (apps == null || apps.isEmpty()) {
2790 return;
2791 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002792
2793 // Update icon cache
2794 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2795
2796 // If any package icon has changed (app was updated while launcher was dead),
2797 // update the corresponding shortcuts.
2798 if (!updatedPackages.isEmpty()) {
2799 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2800 synchronized (sBgLock) {
2801 for (ItemInfo info : sBgItemsIdMap.values()) {
2802 if (info instanceof ShortcutInfo && user.equals(info.user)
2803 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2804 ShortcutInfo si = (ShortcutInfo) info;
2805 ComponentName cn = si.getTargetComponent();
2806 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2807 si.updateIcon(mIconCache);
2808 updates.add(si);
2809 }
2810 }
2811 }
2812 }
2813
2814 if (!updates.isEmpty()) {
2815 final UserHandleCompat userFinal = user;
2816 mHandler.post(new Runnable() {
2817
2818 public void run() {
2819 Callbacks cb = getCallback();
2820 if (cb != null) {
2821 cb.bindShortcutsChanged(
2822 updates, new ArrayList<ShortcutInfo>(), userFinal);
2823 }
2824 }
2825 });
2826 }
Kenny Guyed131872014-04-30 03:02:21 +01002827 }
Joe Onorato36115782010-06-17 13:28:48 -04002828
Kenny Guyed131872014-04-30 03:02:21 +01002829 // Create the ApplicationInfos
2830 for (int i = 0; i < apps.size(); i++) {
2831 LauncherActivityInfoCompat app = apps.get(i);
2832 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002833 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002834 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002835
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002836 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002837 // Add shortcuts for packages which were installed while launcher was dead.
2838 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2839 + mUserManager.getSerialNumberForUser(user);
2840 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2841 HashSet<String> newPackageSet = new HashSet<String>();
2842
2843 for (LauncherActivityInfoCompat info : apps) {
2844 String packageName = info.getComponentName().getPackageName();
2845 if (!packagesAdded.contains(packageName)
2846 && !newPackageSet.contains(packageName)) {
2847 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2848 }
2849 newPackageSet.add(packageName);
2850 }
2851
2852 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2853 }
Winson Chung64359a52013-07-08 17:17:08 -07002854 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002855 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002856 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2857 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002858
2859 // Post callback on main thread
2860 mHandler.post(new Runnable() {
2861 public void run() {
2862 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002863 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002864 if (callbacks != null) {
2865 callbacks.bindAllApplications(added);
2866 if (DEBUG_LOADERS) {
2867 Log.d(TAG, "bound " + added.size() + " apps in "
2868 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2869 }
2870 } else {
2871 Log.i(TAG, "not binding apps: no Launcher activity");
2872 }
2873 }
2874 });
2875
Joe Onorato36115782010-06-17 13:28:48 -04002876 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002877 Log.d(TAG, "Icons processed in "
2878 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002879 }
2880 }
2881
2882 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002883 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002884 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2885 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2886 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2887 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2888 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2889 }
Joe Onorato36115782010-06-17 13:28:48 -04002890 }
2891 }
2892
2893 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002894 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002895 }
2896
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002897 private class AppsAvailabilityCheck extends BroadcastReceiver {
2898
2899 @Override
2900 public void onReceive(Context context, Intent intent) {
2901 synchronized (sBgLock) {
2902 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2903 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002904 final PackageManager manager = context.getPackageManager();
2905 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2906 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002907 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2908 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002909 packagesRemoved.clear();
2910 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002911 for (String pkg : entry.getValue()) {
2912 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002913 boolean packageOnSdcard = launcherApps.isAppEnabled(
2914 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2915 if (packageOnSdcard) {
2916 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2917 packagesUnavailable.add(pkg);
2918 } else {
2919 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2920 packagesRemoved.add(pkg);
2921 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002922 }
2923 }
2924 if (!packagesRemoved.isEmpty()) {
2925 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2926 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2927 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002928 if (!packagesUnavailable.isEmpty()) {
2929 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2930 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2931 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002932 }
Sunny Goyal34942622014-08-29 17:20:55 -07002933 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002934 }
2935 }
2936 }
2937
Joe Onorato36115782010-06-17 13:28:48 -04002938 private class PackageUpdatedTask implements Runnable {
2939 int mOp;
2940 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002941 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002942
2943 public static final int OP_NONE = 0;
2944 public static final int OP_ADD = 1;
2945 public static final int OP_UPDATE = 2;
2946 public static final int OP_REMOVE = 3; // uninstlled
2947 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2948
2949
Kenny Guyed131872014-04-30 03:02:21 +01002950 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002951 mOp = op;
2952 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002953 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002954 }
2955
2956 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002957 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002958
2959 final String[] packages = mPackages;
2960 final int N = packages.length;
2961 switch (mOp) {
2962 case OP_ADD:
2963 for (int i=0; i<N; i++) {
2964 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002965 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002966 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002967 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002968
2969 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002970 if (ADD_MANAGED_PROFILE_SHORTCUTS
2971 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002972 SharedPreferences prefs = context.getSharedPreferences(
2973 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2974 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2975 + mUserManager.getSerialNumberForUser(mUser);
2976 Set<String> shortcutSet = new HashSet<String>(
2977 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2978
2979 for (int i=0; i<N; i++) {
2980 if (!shortcutSet.contains(packages[i])) {
2981 shortcutSet.add(packages[i]);
2982 List<LauncherActivityInfoCompat> activities =
2983 mLauncherApps.getActivityList(packages[i], mUser);
2984 if (activities != null && !activities.isEmpty()) {
2985 InstallShortcutReceiver.queueInstallShortcut(
2986 activities.get(0), context);
2987 }
2988 }
2989 }
2990
2991 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
2992 }
Joe Onorato36115782010-06-17 13:28:48 -04002993 break;
2994 case OP_UPDATE:
2995 for (int i=0; i<N; i++) {
2996 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002997 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002998 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07002999 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003000 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003001 }
3002 break;
3003 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003004 // Remove the packageName for the set of auto-installed shortcuts. This
3005 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003006 if (ADD_MANAGED_PROFILE_SHORTCUTS
3007 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003008 SharedPreferences prefs = context.getSharedPreferences(
3009 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3010 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3011 + mUserManager.getSerialNumberForUser(mUser);
3012 HashSet<String> shortcutSet = new HashSet<String>(
3013 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3014 shortcutSet.removeAll(Arrays.asList(mPackages));
3015 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3016 }
Joe Onorato36115782010-06-17 13:28:48 -04003017 for (int i=0; i<N; i++) {
3018 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003019 mIconCache.removeIconsForPkg(packages[i], mUser);
3020 }
3021 // Fall through
3022 case OP_UNAVAILABLE:
3023 for (int i=0; i<N; i++) {
3024 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3025 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003026 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003027 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003028 }
3029 break;
3030 }
3031
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003032 ArrayList<AppInfo> added = null;
3033 ArrayList<AppInfo> modified = null;
3034 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003035
Adam Cohen487f7dd2012-06-28 18:12:10 -07003036 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003037 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003038 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003039 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003040 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003041 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003042 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003043 }
Winson Chung5d55f332012-07-16 20:45:03 -07003044 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003045 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003046 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003047 }
3048
Sunny Goyale0f58d72014-11-10 18:05:31 -08003049 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003050 if (callbacks == null) {
3051 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3052 return;
3053 }
3054
Sunny Goyal4390ace2014-10-13 11:33:11 -07003055 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3056 new HashMap<ComponentName, AppInfo>();
3057
Joe Onorato36115782010-06-17 13:28:48 -04003058 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003059 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003060 for (AppInfo ai : added) {
3061 addedOrUpdatedApps.put(ai.componentName, ai);
3062 }
Joe Onorato36115782010-06-17 13:28:48 -04003063 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003064
Joe Onorato36115782010-06-17 13:28:48 -04003065 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003066 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003067 for (AppInfo ai : modified) {
3068 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003069 }
3070
Joe Onorato36115782010-06-17 13:28:48 -04003071 mHandler.post(new Runnable() {
3072 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003073 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003074 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003075 callbacks.bindAppsUpdated(modifiedFinal);
3076 }
3077 }
3078 });
3079 }
Winson Chung83892cc2013-05-01 16:53:33 -07003080
Sunny Goyal4390ace2014-10-13 11:33:11 -07003081 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003082 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003083 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3084 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3085 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3086
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003087 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003088 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003089 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003090 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3091 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003092 boolean infoUpdated = false;
3093 boolean shortcutUpdated = false;
3094
3095 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003096 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003097 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003098 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3099 si.iconResource.resourceName, mIconCache, context);
3100 if (icon != null) {
3101 si.setIcon(icon);
3102 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003103 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003104 }
3105 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003106
3107 ComponentName cn = si.getTargetComponent();
3108 if (cn != null && packageSet.contains(cn.getPackageName())) {
3109 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3110
3111 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003112 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3113 // Auto install icon
3114 PackageManager pm = context.getPackageManager();
3115 ResolveInfo matched = pm.resolveActivity(
3116 new Intent(Intent.ACTION_MAIN)
3117 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3118 PackageManager.MATCH_DEFAULT_ONLY);
3119 if (matched == null) {
3120 // Try to find the best match activity.
3121 Intent intent = pm.getLaunchIntentForPackage(
3122 cn.getPackageName());
3123 if (intent != null) {
3124 cn = intent.getComponent();
3125 appInfo = addedOrUpdatedApps.get(cn);
3126 }
3127
3128 if ((intent == null) || (appInfo == null)) {
3129 removedShortcuts.add(si);
3130 continue;
3131 }
3132 si.promisedIntent = intent;
3133 }
3134 }
3135
3136 // Restore the shortcut.
3137 si.intent = si.promisedIntent;
3138 si.promisedIntent = null;
3139 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3140 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3141 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3142
3143 infoUpdated = true;
3144 si.updateIcon(mIconCache);
3145 }
3146
3147 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3148 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3149 si.updateIcon(mIconCache);
3150 si.title = appInfo.title.toString();
3151 si.contentDescription = appInfo.contentDescription;
3152 infoUpdated = true;
3153 }
3154
3155 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3156 // Since package was just updated, the target must be available now.
3157 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3158 shortcutUpdated = true;
3159 }
3160 }
3161
3162 if (infoUpdated || shortcutUpdated) {
3163 updatedShortcuts.add(si);
3164 }
3165 if (infoUpdated) {
3166 updateItemInDatabase(context, si);
3167 }
3168 } else if (info instanceof LauncherAppWidgetInfo) {
3169 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3170 if (mUser.equals(widgetInfo.user)
3171 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3172 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3173 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3174 widgets.add(widgetInfo);
3175 updateItemInDatabase(context, widgetInfo);
3176 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003177 }
3178 }
3179 }
3180
Sunny Goyal4390ace2014-10-13 11:33:11 -07003181 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3182 mHandler.post(new Runnable() {
3183
3184 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003185 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003186 if (callbacks == cb && cb != null) {
3187 callbacks.bindShortcutsChanged(
3188 updatedShortcuts, removedShortcuts, mUser);
3189 }
3190 }
3191 });
3192 if (!removedShortcuts.isEmpty()) {
3193 deleteItemsFromDatabase(context, removedShortcuts);
3194 }
3195 }
3196 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003197 mHandler.post(new Runnable() {
3198 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003199 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003200 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003201 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003202 }
3203 }
3204 });
3205 }
3206 }
3207
Winson Chungdf95eb12013-10-16 14:57:07 -07003208 final ArrayList<String> removedPackageNames =
3209 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003210 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003211 // Mark all packages in the broadcast to be removed
3212 removedPackageNames.addAll(Arrays.asList(packages));
3213 } else if (mOp == OP_UPDATE) {
3214 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003215 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003216 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003217 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003218 }
3219 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003220 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003221
Winson Chungdf95eb12013-10-16 14:57:07 -07003222 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003223 final int removeReason;
3224 if (mOp == OP_UNAVAILABLE) {
3225 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3226 } else {
3227 // Remove all the components associated with this package
3228 for (String pn : removedPackageNames) {
3229 deletePackageFromDatabase(context, pn, mUser);
3230 }
3231 // Remove all the specific components
3232 for (AppInfo a : removedApps) {
3233 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3234 deleteItemsFromDatabase(context, infos);
3235 }
3236 removeReason = 0;
3237 }
3238
Winson Chungdf95eb12013-10-16 14:57:07 -07003239 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003240 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003241 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003242 mHandler.post(new Runnable() {
3243 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003244 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003245 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003246 callbacks.bindComponentsRemoved(
3247 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003248 }
3249 }
3250 });
Joe Onoratobe386092009-11-17 17:32:16 -08003251 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003252
Michael Jurkac402cd92013-05-20 15:49:32 +02003253 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003254 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003255 mHandler.post(new Runnable() {
3256 @Override
3257 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003258 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003259 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003260 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003261 }
3262 }
3263 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003264
3265 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003266 mHandler.post(new Runnable() {
3267 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003268 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003269 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003270 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003271 }
3272 }
3273 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003274 }
3275 }
3276
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003277 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3278 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003279 synchronized (sBgLock) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003280 if (sBgWidgetProviders != null && !refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003281 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3282 }
3283 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3284 List<AppWidgetProviderInfo> widgets =
3285 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3286 LauncherAppWidgetProviderInfo info;
3287 for (AppWidgetProviderInfo pInfo : widgets) {
3288 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3289 sBgWidgetProviders.put(info.provider, info);
3290 }
3291
3292 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3293 for (CustomAppWidget widget : customWidgets) {
3294 info = new LauncherAppWidgetProviderInfo(context, widget);
3295 sBgWidgetProviders.put(info.provider, info);
3296 }
Adam Cohen59400422014-03-05 18:07:04 -08003297 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3298 }
3299 }
3300
3301 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3302 synchronized (sBgLock) {
3303 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003304 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003305 }
3306 return sBgWidgetProviders.get(name);
3307 }
3308 }
3309
Winson Chungb745afb2015-03-02 11:51:23 -08003310 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003311 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003312 PackageManager packageManager = context.getPackageManager();
3313 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003314 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003315 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3316 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003317 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003318 return widgetsAndShortcuts;
3319 }
3320
Kenny Guyed131872014-04-30 03:02:21 +01003321 private static boolean isPackageDisabled(Context context, String packageName,
3322 UserHandleCompat user) {
3323 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3324 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003325 }
Adam Cohen556f6132014-01-15 15:18:08 -08003326
Kenny Guyed131872014-04-30 03:02:21 +01003327 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3328 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003329 if (cn == null) {
3330 return false;
3331 }
Kenny Guyed131872014-04-30 03:02:21 +01003332 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3333 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003334 return false;
3335 }
Kenny Guyed131872014-04-30 03:02:21 +01003336 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003337 }
3338
Adam Cohena28b78e2014-05-20 17:03:04 -07003339 public static boolean isValidPackage(Context context, String packageName,
3340 UserHandleCompat user) {
3341 if (packageName == null) {
3342 return false;
3343 }
3344 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3345 return launcherApps.isPackageEnabledForProfile(packageName, user);
3346 }
3347
Joe Onorato9c1289c2009-08-17 11:03:03 -04003348 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003349 * Make an ShortcutInfo object for a restored application or shortcut item that points
3350 * to a package that is not yet installed on the system.
3351 */
Sunny Goyal34942622014-08-29 17:20:55 -07003352 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3353 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003354 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003355 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003356 mIconCache.getTitleAndIcon(info, intent, info.user);
Sunny Goyal34942622014-08-29 17:20:55 -07003357
3358 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3359 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3360 if (!TextUtils.isEmpty(title)) {
3361 info.title = title;
3362 }
3363 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3364 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3365 if (TextUtils.isEmpty(info.title)) {
3366 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3367 }
3368 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3369 } else {
3370 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3371 }
3372
Kenny Guyc2bd8102014-06-30 12:30:31 +01003373 info.contentDescription = mUserManager.getBadgedLabelForUser(
3374 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003375 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003376 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003377 return info;
3378 }
3379
3380 /**
3381 * Make an Intent object for a restored application or shortcut item that points
3382 * to the market page for the item.
3383 */
3384 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3385 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003386 return getMarketIntent(componentName.getPackageName());
3387 }
3388
3389 static Intent getMarketIntent(String packageName) {
3390 return new Intent(Intent.ACTION_VIEW)
3391 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003392 .scheme("market")
3393 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003394 .appendQueryParameter("id", packageName)
3395 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003396 }
3397
3398 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003399 * Make an ShortcutInfo object for a shortcut that is an application.
3400 *
3401 * If c is not null, then it will be used to fill in missing data like the title and icon.
3402 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003403 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003404 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003405 boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003406 if (user == null) {
3407 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003408 return null;
3409 }
3410
Kenny Guyed131872014-04-30 03:02:21 +01003411 ComponentName componentName = intent.getComponent();
3412 if (componentName == null) {
3413 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3414 return null;
3415 }
3416
3417 Intent newIntent = new Intent(intent.getAction(), null);
3418 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3419 newIntent.setComponent(componentName);
3420 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003421 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003422 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3423 return null;
3424 }
3425
3426 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003427 mIconCache.getTitleAndIcon(info, componentName, lai, user, false);
3428 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3429 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3430 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003431 }
3432
Joe Onorato56d82912010-03-07 14:32:10 -05003433 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003434 if (TextUtils.isEmpty(info.title) && c != null) {
3435 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003436 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003437
Joe Onorato56d82912010-03-07 14:32:10 -05003438 // fall back to the class name of the activity
3439 if (info.title == null) {
3440 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003441 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003442
Joe Onorato9c1289c2009-08-17 11:03:03 -04003443 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003444 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003445 info.contentDescription = mUserManager.getBadgedLabelForUser(
3446 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003447 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003448 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003449
Winson Chung64359a52013-07-08 17:17:08 -07003450 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3451 ItemInfoFilter f) {
3452 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3453 for (ItemInfo i : infos) {
3454 if (i instanceof ShortcutInfo) {
3455 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003456 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003457 if (cn != null && f.filterItem(null, info, cn)) {
3458 filtered.add(info);
3459 }
3460 } else if (i instanceof FolderInfo) {
3461 FolderInfo info = (FolderInfo) i;
3462 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003463 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003464 if (cn != null && f.filterItem(info, s, cn)) {
3465 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003466 }
3467 }
Winson Chung64359a52013-07-08 17:17:08 -07003468 } else if (i instanceof LauncherAppWidgetInfo) {
3469 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3470 ComponentName cn = info.providerName;
3471 if (cn != null && f.filterItem(null, info, cn)) {
3472 filtered.add(info);
3473 }
Winson Chung8a435102012-08-30 17:16:53 -07003474 }
3475 }
Winson Chung64359a52013-07-08 17:17:08 -07003476 return new ArrayList<ItemInfo>(filtered);
3477 }
3478
Kenny Guyed131872014-04-30 03:02:21 +01003479 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3480 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003481 ItemInfoFilter filter = new ItemInfoFilter() {
3482 @Override
3483 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003484 if (info.user == null) {
3485 return cn.equals(cname);
3486 } else {
3487 return cn.equals(cname) && info.user.equals(user);
3488 }
Winson Chung64359a52013-07-08 17:17:08 -07003489 }
3490 };
3491 return filterItemInfos(sBgItemsIdMap.values(), filter);
3492 }
3493
Sunny Goyal1a745e82014-10-02 15:58:31 -07003494 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003495 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003496 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003497 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003498 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3499 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003500
Joe Onorato56d82912010-03-07 14:32:10 -05003501 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003502 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003503 // Non-app shortcuts are only supported for current user.
3504 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003505 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003506
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003507 // TODO: If there's an explicit component and we can't install that, delete it.
3508
Joe Onorato56d82912010-03-07 14:32:10 -05003509 info.title = c.getString(titleIndex);
3510
Joe Onorato9c1289c2009-08-17 11:03:03 -04003511 int iconType = c.getInt(iconTypeIndex);
3512 switch (iconType) {
3513 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3514 String packageName = c.getString(iconPackageIndex);
3515 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003516 info.customIcon = false;
3517 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003518 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003519 // the db
3520 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003521 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003522 }
3523 // the fallback icon
3524 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003525 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003526 info.usingFallbackIcon = true;
3527 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003528 break;
3529 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003530 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003531 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003532 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003533 info.customIcon = false;
3534 info.usingFallbackIcon = true;
3535 } else {
3536 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003537 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003538 break;
3539 default:
Kenny Guyed131872014-04-30 03:02:21 +01003540 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003541 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003542 info.customIcon = false;
3543 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003544 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003545 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003546 return info;
3547 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003548
Sunny Goyal2350bc92014-10-14 16:42:54 -07003549 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003550 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3551 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3552 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3553
Adam Cohend9198822011-11-22 16:42:47 -08003554 if (intent == null) {
3555 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3556 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3557 return null;
3558 }
3559
Joe Onorato0589f0f2010-02-08 13:44:00 -08003560 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003561 boolean customIcon = false;
3562 ShortcutIconResource iconResource = null;
3563
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003564 if (bitmap instanceof Bitmap) {
3565 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003566 customIcon = true;
3567 } else {
3568 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003569 if (extra instanceof ShortcutIconResource) {
3570 iconResource = (ShortcutIconResource) extra;
3571 icon = Utilities.createIconBitmap(iconResource.packageName,
3572 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003573 }
3574 }
3575
Michael Jurkac9d95c52011-08-29 14:03:34 -07003576 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003577
Kenny Guyed131872014-04-30 03:02:21 +01003578 // Only support intents for current user for now. Intents sent from other
3579 // users wouldn't get here without intent forwarding anyway.
3580 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003581 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003582 icon = mIconCache.getDefaultIcon(info.user);
3583 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003584 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003585 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003586
Joe Onorato0589f0f2010-02-08 13:44:00 -08003587 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003588 info.contentDescription = mUserManager.getBadgedLabelForUser(
3589 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003590 info.intent = intent;
3591 info.customIcon = customIcon;
3592 info.iconResource = iconResource;
3593
3594 return info;
3595 }
3596
Joe Onorato9c1289c2009-08-17 11:03:03 -04003597 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003598 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003599 * or make a new one.
3600 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003601 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003602 // See if a placeholder was created for us already
3603 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003604 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003605 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003606 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003607 folders.put(id, folderInfo);
3608 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003609 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003610 }
3611
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003612 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003613 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003614 return new Comparator<AppInfo>() {
3615 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003616 if (a.user.equals(b.user)) {
3617 int result = collator.compare(a.title.toString().trim(),
3618 b.title.toString().trim());
3619 if (result == 0) {
3620 result = a.componentName.compareTo(b.componentName);
3621 }
3622 return result;
3623 } else {
3624 // TODO Need to figure out rules for sorting
3625 // profiles, this puts work second.
3626 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003627 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003628 }
Winson Chung11904872012-09-17 16:58:46 -07003629 };
3630 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003631 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3632 = new Comparator<AppInfo>() {
3633 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003634 if (a.firstInstallTime < b.firstInstallTime) return 1;
3635 if (a.firstInstallTime > b.firstInstallTime) return -1;
3636 return 0;
3637 }
3638 };
Winson Chung5308f242011-08-18 12:12:41 -07003639 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3640 if (info.activityInfo != null) {
3641 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3642 } else {
3643 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3644 }
3645 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003646
Winson Chung1ed747a2011-05-03 16:18:34 -07003647 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003648 private final AppWidgetManagerCompat mManager;
3649 private final PackageManager mPackageManager;
3650 private final HashMap<Object, String> mLabelCache;
3651 private final Collator mCollator;
3652
3653 WidgetAndShortcutNameComparator(Context context) {
3654 mManager = AppWidgetManagerCompat.getInstance(context);
3655 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003656 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003657 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003658 }
3659 public final int compare(Object a, Object b) {
3660 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003661 if (mLabelCache.containsKey(a)) {
3662 labelA = mLabelCache.get(a);
3663 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003664 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3665 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003666 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003667 mLabelCache.put(a, labelA);
3668 }
3669 if (mLabelCache.containsKey(b)) {
3670 labelB = mLabelCache.get(b);
3671 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003672 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003673 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003674 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003675 mLabelCache.put(b, labelB);
3676 }
Winson Chung11904872012-09-17 16:58:46 -07003677 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003678 }
3679 };
Joe Onoratobe386092009-11-17 17:32:16 -08003680
Sunny Goyal651077b2014-06-30 14:15:31 -07003681 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3682 return (provider != null) && (provider.provider != null)
3683 && (provider.provider.getPackageName() != null);
3684 }
3685
Joe Onoratobe386092009-11-17 17:32:16 -08003686 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003687 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003688 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3689 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3690 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3691 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003692 if (mLoaderTask != null) {
3693 mLoaderTask.dumpState();
3694 } else {
3695 Log.d(TAG, "mLoaderTask=null");
3696 }
Joe Onoratobe386092009-11-17 17:32:16 -08003697 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003698
3699 public Callbacks getCallback() {
3700 return mCallbacks != null ? mCallbacks.get() : null;
3701 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003702}