blob: 97a28300690ab803dd62acf0c3f4fb86808579c3 [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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080031import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040032import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070034import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.res.Resources;
36import android.database.Cursor;
37import android.graphics.Bitmap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.net.Uri;
Hyunyoung Songd4af1482015-04-20 20:40:03 -070039import android.os.Build;
Joe Onorato17a89222011-02-08 17:26:11 -080040import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040041import android.os.Handler;
42import android.os.HandlerThread;
Sunny Goyal756adbc2015-04-16 15:20:51 -070043import android.os.Looper;
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;
Robin Lee26ace122015-03-16 19:41:43 +000061import com.android.launcher3.util.ComponentKey;
Sunny Goyale2df0622015-04-24 11:27:00 -070062import com.android.launcher3.util.LongArrayMap;
Sunny Goyal18bf8e22015-04-08 18:13:46 -070063import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Romain Guyedcce092010-03-04 13:03:17 -080065
Michael Jurkac2f801e2011-07-12 14:19:46 -070066import java.lang.ref.WeakReference;
67import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070068import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.text.Collator;
70import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070071import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070072import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070073import java.util.Collections;
74import java.util.Comparator;
75import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070077import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070079import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070080import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070081
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082/**
83 * Maintains in-memory state of the Launcher. It is expected that there should be only one
84 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070085 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 */
Kenny Guyed131872014-04-30 03:02:21 +010087public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010088 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080089 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040090 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070091 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Chris Wrenb358f812014-04-16 13:37:00 -040092
Joe Onorato9c1289c2009-08-17 11:03:03 -040093 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070094
Dan Sandlerd5024042014-01-09 15:01:33 -050095 public static final int LOADER_FLAG_NONE = 0;
96 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
97 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
98
Joe Onorato36115782010-06-17 13:28:48 -040099 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500100 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800101
Adam Cohen091440a2015-03-18 14:16:05 -0700102 @Thunk final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800103 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400104
Adam Cohen091440a2015-03-18 14:16:05 -0700105 @Thunk final LauncherAppState mApp;
106 @Thunk final Object mLock = new Object();
107 @Thunk DeferredHandler mHandler = new DeferredHandler();
108 @Thunk LoaderTask mLoaderTask;
109 @Thunk boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
Jason Monkbbe1e242014-05-16 17:37:34 -0400111 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700112
Adam Cohen091440a2015-03-18 14:16:05 -0700113 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700114 static {
115 sWorkerThread.start();
116 }
Adam Cohen091440a2015-03-18 14:16:05 -0700117 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700118
Joe Onoratocc67f472010-06-08 10:54:30 -0700119 // We start off with everything not loaded. After that, we assume that
120 // our monitoring of the package manager provides all updates and we never
121 // need to do a requery. These are only ever touched from the loader thread.
Adam Cohen091440a2015-03-18 14:16:05 -0700122 @Thunk boolean mWorkspaceLoaded;
123 @Thunk boolean mAllAppsLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700124
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700125 // When we are loading pages synchronously, we can't just post the binding of items on the side
126 // pages as this delays the rotation process. Instead, we wait for a callback from the first
127 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
128 // a normal load, we also clear this set of Runnables.
129 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
130
Adam Cohen091440a2015-03-18 14:16:05 -0700131 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700133 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700134 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800135
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700136 // The lock that must be acquired before referencing any static bg data structures. Unlike
137 // other locks, this one can generally be held long-term because we never expect any of these
138 // static data structures to be referenced outside of the worker thread except on the first
139 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700140 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700141
Adam Cohen487f7dd2012-06-28 18:12:10 -0700142 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700143 // LauncherModel to their ids
Sunny Goyale2df0622015-04-24 11:27:00 -0700144 static final LongArrayMap<ItemInfo> sBgItemsIdMap = new LongArrayMap<>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
147 // created by LauncherModel that are directly on the home screen (however, no widgets or
148 // shortcuts within folders).
149 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
152 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153 new ArrayList<LauncherAppWidgetInfo>();
154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
Sunny Goyale2df0622015-04-24 11:27:00 -0700156 static final LongArrayMap<FolderInfo> sBgFolders = new LongArrayMap<>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700157
Adam Cohendcd297f2013-06-18 13:13:40 -0700158 // sBgWorkspaceScreens is the ordered set of workspace screens.
159 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
160
Adam Cohen59400422014-03-05 18:07:04 -0800161 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000162 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800163
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700164 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700165 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
166 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700167
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700168 // </ only access in worker thread >
169
Adam Cohen091440a2015-03-18 14:16:05 -0700170 @Thunk IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171
Reena Lee99a73f32011-10-24 17:27:37 -0700172 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700173
Adam Cohen091440a2015-03-18 14:16:05 -0700174 @Thunk final LauncherAppsCompat mLauncherApps;
175 @Thunk final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100176
Joe Onorato9c1289c2009-08-17 11:03:03 -0400177 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700178 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400179 public int getCurrentWorkspaceScreen();
180 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700181 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
182 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700183 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700184 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Sunny Goyale2df0622015-04-24 11:27:00 -0700185 public void bindFolders(LongArrayMap<FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800186 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400187 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200188 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700189 public void bindAppsAdded(ArrayList<Long> newScreens,
190 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700191 ArrayList<ItemInfo> addAnimated,
192 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200193 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700194 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
195 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
196 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyal756adbc2015-04-16 15:20:51 -0700197 public void bindRestoreItemsChange(HashSet<ItemInfo> updates);
Winson Chung83892cc2013-05-01 16:53:33 -0700198 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700199 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200200 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100201 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700202 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700203 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700204 public void dumpLogsToLocalData();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400205 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206
Winson Chung64359a52013-07-08 17:17:08 -0700207 public interface ItemInfoFilter {
208 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
209 }
210
Bjorn Bringert1307f632013-10-03 22:31:03 +0100211 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800212 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400213
Winson Chungee055712013-07-30 14:46:24 -0700214 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700215 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400216 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
217 // resource string.
218 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
219 ProviderInfo providerInfo =
220 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
221 ProviderInfo redirectProvider =
222 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700223
224 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400225 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700226
227 if (mOldContentProviderExists) {
228 Log.d(TAG, "Old launcher provider exists.");
229 } else {
230 Log.d(TAG, "Old launcher provider does not exist.");
231 }
232
Daniel Sandlere4f98912013-06-25 15:13:26 -0400233 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100234 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800235 mIconCache = iconCache;
236
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400237 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700238 Configuration config = res.getConfiguration();
239 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100240 mLauncherApps = LauncherAppsCompat.getInstance(context);
241 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800242 }
243
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700244 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
245 * posted on the main thread handler. */
Adam Cohen091440a2015-03-18 14:16:05 -0700246 @Thunk void runOnMainThread(Runnable r) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700247 if (sWorkerThread.getThreadId() == Process.myTid()) {
248 // If we are on the worker thread, post onto the main handler
249 mHandler.post(r);
250 } else {
251 r.run();
252 }
253 }
254
255 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
256 * posted on the worker thread handler. */
257 private static void runOnWorkerThread(Runnable r) {
258 if (sWorkerThread.getThreadId() == Process.myTid()) {
259 r.run();
260 } else {
261 // If we are not on the worker thread, then post to the worker handler
262 sWorker.post(r);
263 }
264 }
265
Winson Chunge43a1e72014-01-15 10:33:02 -0800266 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
267 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800268 }
269
Sunny Goyal756adbc2015-04-16 15:20:51 -0700270 public void setPackageState(final PackageInstallInfo installInfo) {
271 Runnable updateRunnable = new Runnable() {
272
273 @Override
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500274 public void run() {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700275 synchronized (sBgLock) {
276 final HashSet<ItemInfo> updates = new HashSet<>();
277
278 if (installInfo.state == PackageInstallerCompat.STATUS_INSTALLED) {
279 // Ignore install success events as they are handled by Package add events.
280 return;
281 }
282
Sunny Goyale2df0622015-04-24 11:27:00 -0700283 for (ItemInfo info : sBgItemsIdMap) {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700284 if (info instanceof ShortcutInfo) {
285 ShortcutInfo si = (ShortcutInfo) info;
286 ComponentName cn = si.getTargetComponent();
287 if (si.isPromise() && (cn != null)
288 && installInfo.packageName.equals(cn.getPackageName())) {
289 si.setInstallProgress(installInfo.progress);
290
291 if (installInfo.state == PackageInstallerCompat.STATUS_FAILED) {
292 // Mark this info as broken.
293 si.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
294 }
295 updates.add(si);
296 }
297 }
298 }
299
300 for (LauncherAppWidgetInfo widget : sBgAppWidgets) {
301 if (widget.providerName.getPackageName().equals(installInfo.packageName)) {
302 widget.installProgress = installInfo.progress;
303 updates.add(widget);
304 }
305 }
306
307 if (!updates.isEmpty()) {
308 // Push changes to the callback.
309 Runnable r = new Runnable() {
310 public void run() {
311 Callbacks callbacks = getCallback();
312 if (callbacks != null) {
313 callbacks.bindRestoreItemsChange(updates);
314 }
315 }
316 };
317 mHandler.post(r);
318 }
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500319 }
320 }
321 };
Sunny Goyal756adbc2015-04-16 15:20:51 -0700322 runOnWorkerThread(updateRunnable);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500323 }
324
Sunny Goyal756adbc2015-04-16 15:20:51 -0700325 /**
326 * Updates the icons and label of all pending icons for the provided package name.
327 */
328 public void updateSessionDisplayInfo(final String packageName) {
329 Runnable updateRunnable = new Runnable() {
330
331 @Override
Sunny Goyala22666f2014-09-18 13:25:15 -0700332 public void run() {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700333 synchronized (sBgLock) {
334 final ArrayList<ShortcutInfo> updates = new ArrayList<>();
335 final UserHandleCompat user = UserHandleCompat.myUserHandle();
336
Sunny Goyale2df0622015-04-24 11:27:00 -0700337 for (ItemInfo info : sBgItemsIdMap) {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700338 if (info instanceof ShortcutInfo) {
339 ShortcutInfo si = (ShortcutInfo) info;
340 ComponentName cn = si.getTargetComponent();
341 if (si.isPromise() && (cn != null)
342 && packageName.equals(cn.getPackageName())) {
343 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
344 // For auto install apps update the icon as well as label.
345 mIconCache.getTitleAndIcon(si,
346 si.promisedIntent, user,
347 si.shouldUseLowResIcon());
348 } else {
349 // Only update the icon for restored apps.
350 si.updateIcon(mIconCache);
351 }
352 updates.add(si);
353 }
354 }
355 }
356
357 if (!updates.isEmpty()) {
358 // Push changes to the callback.
359 Runnable r = new Runnable() {
360 public void run() {
361 Callbacks callbacks = getCallback();
362 if (callbacks != null) {
363 callbacks.bindShortcutsChanged(updates,
364 new ArrayList<ShortcutInfo>(), user);
365 }
366 }
367 };
368 mHandler.post(r);
369 }
Sunny Goyala22666f2014-09-18 13:25:15 -0700370 }
371 }
372 };
Sunny Goyal756adbc2015-04-16 15:20:51 -0700373 runOnWorkerThread(updateRunnable);
Sunny Goyala22666f2014-09-18 13:25:15 -0700374 }
375
Adam Cohen76a47a12014-02-05 11:47:43 -0800376 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800377 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800378
379 if (allAppsApps == null) {
380 throw new RuntimeException("allAppsApps must not be null");
381 }
382 if (allAppsApps.isEmpty()) {
383 return;
384 }
385
386 // Process the newly added applications and add them to the database first
387 Runnable r = new Runnable() {
388 public void run() {
389 runOnMainThread(new Runnable() {
390 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800391 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800392 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500393 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800394 }
395 }
396 });
397 }
398 };
399 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700400 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800401
Sunny Goyala9116722015-04-29 13:55:58 -0700402 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> occupiedPos,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800403 int[] xy, int spanX, int spanY) {
404 LauncherAppState app = LauncherAppState.getInstance();
405 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
406 final int xCount = (int) grid.numColumns;
407 final int yCount = (int) grid.numRows;
408 boolean[][] occupied = new boolean[xCount][yCount];
409 if (occupiedPos != null) {
Sunny Goyala9116722015-04-29 13:55:58 -0700410 for (ItemInfo r : occupiedPos) {
411 int right = r.cellX + r.spanX;
412 int bottom = r.cellY + r.spanY;
413 for (int x = r.cellX; 0 <= x && x < right && x < xCount; x++) {
414 for (int y = r.cellY; 0 <= y && y < bottom && y < yCount; y++) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800415 occupied[x][y] = true;
416 }
417 }
418 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800419 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700420 return Utilities.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800421 }
422
423 /**
424 * Find a position on the screen for the given size or adds a new screen.
425 * @return screenId and the coordinates for the item.
426 */
Adam Cohen091440a2015-03-18 14:16:05 -0700427 @Thunk static Pair<Long, int[]> findSpaceForItem(
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800428 Context context,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800429 ArrayList<Long> workspaceScreens,
430 ArrayList<Long> addedWorkspaceScreensFinal,
431 int spanX, int spanY) {
Sunny Goyala9116722015-04-29 13:55:58 -0700432 LongSparseArray<ArrayList<ItemInfo>> screenItems = new LongSparseArray<>();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800433
Sunny Goyala9116722015-04-29 13:55:58 -0700434 // Use sBgItemsIdMap as all the items are already loaded.
435 // TODO: Throw exception is above condition is not met.
436 synchronized (sBgLock) {
437 for (ItemInfo info : sBgItemsIdMap) {
438 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
439 ArrayList<ItemInfo> items = screenItems.get(info.screenId);
440 if (items == null) {
441 items = new ArrayList<>();
442 screenItems.put(info.screenId, items);
443 }
444 items.add(info);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800445 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800446 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800447 }
448
449 // Find appropriate space for the item.
450 long screenId = 0;
451 int[] cordinates = new int[2];
452 boolean found = false;
453
454 int screenCount = workspaceScreens.size();
455 // First check the preferred screen.
Sunny Goyala9116722015-04-29 13:55:58 -0700456 int preferredScreenIndex = workspaceScreens.isEmpty() ? 0 : 1;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800457 if (preferredScreenIndex < screenCount) {
458 screenId = workspaceScreens.get(preferredScreenIndex);
459 found = findNextAvailableIconSpaceInScreen(
460 screenItems.get(screenId), cordinates, spanX, spanY);
461 }
462
463 if (!found) {
Sunny Goyala9116722015-04-29 13:55:58 -0700464 // Search on any of the screens starting from the first screen.
465 for (int screen = 1; screen < screenCount; screen++) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800466 screenId = workspaceScreens.get(screen);
467 if (findNextAvailableIconSpaceInScreen(
468 screenItems.get(screenId), cordinates, spanX, spanY)) {
469 // We found a space for it
470 found = true;
471 break;
472 }
473 }
474 }
475
476 if (!found) {
477 // Still no position found. Add a new screen to the end.
478 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
479
480 // Save the screen id for binding in the workspace
481 workspaceScreens.add(screenId);
482 addedWorkspaceScreensFinal.add(screenId);
483
484 // If we still can't find an empty space, then God help us all!!!
485 if (!findNextAvailableIconSpaceInScreen(
486 screenItems.get(screenId), cordinates, spanX, spanY)) {
487 throw new RuntimeException("Can't find space to add the item");
488 }
489 }
490 return Pair.create(screenId, cordinates);
491 }
492
493 /**
494 * Adds the provided items to the workspace.
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800495 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700496 public void addAndBindAddedWorkspaceItems(final Context context,
Sunny Goyala9116722015-04-29 13:55:58 -0700497 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800498 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800499 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700500 return;
Winson Chung997a9232013-07-24 15:33:46 -0700501 }
Winson Chung64359a52013-07-08 17:17:08 -0700502 // Process the newly added applications and add them to the database first
503 Runnable r = new Runnable() {
504 public void run() {
505 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
506 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
507
Winson Chung76828c82013-08-19 15:43:29 -0700508 // Get the list of workspace screens. We need to append to this list and
509 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
510 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800511 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700512 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800513 for (ItemInfo item : workspaceApps) {
Sunny Goyala9116722015-04-29 13:55:58 -0700514 if (item instanceof ShortcutInfo) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800515 // Short-circuit this logic if the icon exists somewhere on the workspace
Sunny Goyal756adbc2015-04-16 15:20:51 -0700516 if (shortcutExists(context, item.getIntent(), item.user)) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800517 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700518 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800519 }
Winson Chung76828c82013-08-19 15:43:29 -0700520
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800521 // Find appropriate space for the item.
Sunny Goyala9116722015-04-29 13:55:58 -0700522 Pair<Long, int[]> coords = findSpaceForItem(context,
523 workspaceScreens, addedWorkspaceScreensFinal,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800524 1, 1);
525 long screenId = coords.first;
526 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700527
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700528 ItemInfo itemInfo;
529 if (item instanceof ShortcutInfo || item instanceof FolderInfo) {
530 itemInfo = item;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800531 } else if (item instanceof AppInfo) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700532 itemInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700533 } else {
534 throw new RuntimeException("Unexpected info type");
535 }
Winson Chung94d67682013-09-25 16:29:40 -0700536
Winson Chung64359a52013-07-08 17:17:08 -0700537 // Add the shortcut to the db
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700538 addItemToDatabase(context, itemInfo,
Winson Chung64359a52013-07-08 17:17:08 -0700539 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700540 screenId, cordinates[0], cordinates[1]);
Winson Chung64359a52013-07-08 17:17:08 -0700541 // Save the ShortcutInfo for binding in the workspace
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700542 addedShortcutsFinal.add(itemInfo);
Winson Chung64359a52013-07-08 17:17:08 -0700543 }
544 }
545
Winson Chung76828c82013-08-19 15:43:29 -0700546 // Update the workspace screens
547 updateWorkspaceScreenOrder(context, workspaceScreens);
548
Adam Cohen76a47a12014-02-05 11:47:43 -0800549 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700550 runOnMainThread(new Runnable() {
551 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800552 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700553 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700554 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
555 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700556 if (!addedShortcutsFinal.isEmpty()) {
557 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
558 long lastScreenId = info.screenId;
559 for (ItemInfo i : addedShortcutsFinal) {
560 if (i.screenId == lastScreenId) {
561 addAnimated.add(i);
562 } else {
563 addNotAnimated.add(i);
564 }
Winson Chung997a9232013-07-24 15:33:46 -0700565 }
566 }
Winson Chungd64d1762013-08-20 14:37:16 -0700567 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800568 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700569 }
Winson Chung64359a52013-07-08 17:17:08 -0700570 }
Winson Chung997a9232013-07-24 15:33:46 -0700571 });
572 }
Winson Chung64359a52013-07-08 17:17:08 -0700573 }
574 };
575 runOnWorkerThread(r);
576 }
577
Sunny Goyald33860f2015-04-23 16:02:20 -0700578 private void unbindItemInfosAndClearQueuedBindRunnables() {
Winson Chung81b52252012-08-27 15:34:29 -0700579 if (sWorkerThread.getThreadId() == Process.myTid()) {
580 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
581 "main thread");
582 }
583
584 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400585 synchronized (mDeferredBindRunnables) {
586 mDeferredBindRunnables.clear();
587 }
Sunny Goyald33860f2015-04-23 16:02:20 -0700588
589 // Remove any queued UI runnables
590 mHandler.cancelAll();
Winson Chung81b52252012-08-27 15:34:29 -0700591 // Unbind all the workspace items
592 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700593 }
594
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700595 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700596 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700597 // Ensure that we don't use the same workspace items data structure on the main thread
598 // by making a copy of workspace items first.
Sunny Goyald33860f2015-04-23 16:02:20 -0700599 final ArrayList<ItemInfo> tmpItems = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700600 synchronized (sBgLock) {
Sunny Goyald33860f2015-04-23 16:02:20 -0700601 tmpItems.addAll(sBgWorkspaceItems);
602 tmpItems.addAll(sBgAppWidgets);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700603 }
604 Runnable r = new Runnable() {
605 @Override
606 public void run() {
Sunny Goyald33860f2015-04-23 16:02:20 -0700607 for (ItemInfo item : tmpItems) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700608 item.unbind();
609 }
610 }
611 };
612 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700613 }
614
Joe Onorato9c1289c2009-08-17 11:03:03 -0400615 /**
616 * Adds an item to the DB if it was not created previously, or move it to a new
617 * <container, screen, cellX, cellY>
618 */
619 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700620 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400621 if (item.container == ItemInfo.NO_ID) {
622 // From all apps
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700623 addItemToDatabase(context, item, container, screenId, cellX, cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400624 } else {
625 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700626 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 }
628 }
629
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700630 static void checkItemInfoLocked(
631 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
632 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
633 if (modelItem != null && item != modelItem) {
634 // check all the data is consistent
635 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
636 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
637 ShortcutInfo shortcut = (ShortcutInfo) item;
638 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
639 modelShortcut.intent.filterEquals(shortcut.intent) &&
640 modelShortcut.id == shortcut.id &&
641 modelShortcut.itemType == shortcut.itemType &&
642 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700643 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700644 modelShortcut.cellX == shortcut.cellX &&
645 modelShortcut.cellY == shortcut.cellY &&
646 modelShortcut.spanX == shortcut.spanX &&
647 modelShortcut.spanY == shortcut.spanY &&
648 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
649 (modelShortcut.dropPos != null &&
650 shortcut.dropPos != null &&
651 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
652 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
653 // For all intents and purposes, this is the same object
654 return;
655 }
656 }
657
658 // the modelItem needs to match up perfectly with item if our model is
659 // to be consistent with the database-- for now, just require
660 // modelItem == item or the equality check above
661 String msg = "item: " + ((item != null) ? item.toString() : "null") +
662 "modelItem: " +
663 ((modelItem != null) ? modelItem.toString() : "null") +
664 "Error: ItemInfo passed to checkItemInfo doesn't match original";
665 RuntimeException e = new RuntimeException(msg);
666 if (stackTrace != null) {
667 e.setStackTrace(stackTrace);
668 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800669 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700670 }
671 }
672
Michael Jurka816474f2012-06-25 14:49:02 -0700673 static void checkItemInfo(final ItemInfo item) {
674 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
675 final long itemId = item.id;
676 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700677 public void run() {
678 synchronized (sBgLock) {
679 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700680 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700681 }
682 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700683 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700684 }
685
Michael Jurkac9d95c52011-08-29 14:03:34 -0700686 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
687 final ItemInfo item, final String callingFunction) {
688 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700689 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700690 final ContentResolver cr = context.getContentResolver();
691
Adam Cohen487f7dd2012-06-28 18:12:10 -0700692 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700693 Runnable r = new Runnable() {
694 public void run() {
695 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700696 updateItemArrays(item, itemId, stackTrace);
697 }
698 };
699 runOnWorkerThread(r);
700 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700701
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700702 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
703 final ArrayList<ItemInfo> items, final String callingFunction) {
704 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700705
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700706 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
707 Runnable r = new Runnable() {
708 public void run() {
709 ArrayList<ContentProviderOperation> ops =
710 new ArrayList<ContentProviderOperation>();
711 int count = items.size();
712 for (int i = 0; i < count; i++) {
713 ItemInfo item = items.get(i);
714 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700715 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700716 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700717
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700718 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
719 updateItemArrays(item, itemId, stackTrace);
720
721 }
722 try {
723 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
724 } catch (Exception e) {
725 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700726 }
727 }
728 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700729 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700730 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700731
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700732 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
733 // Lock on mBgLock *after* the db operation
734 synchronized (sBgLock) {
735 checkItemInfoLocked(itemId, item, stackTrace);
736
737 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
738 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
739 // Item is in a folder, make sure this folder exists
740 if (!sBgFolders.containsKey(item.container)) {
741 // An items container is being set to a that of an item which is not in
742 // the list of Folders.
743 String msg = "item: " + item + " container being set to: " +
744 item.container + ", not in the list of folders";
745 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700746 }
747 }
748
749 // Items are added/removed from the corresponding FolderInfo elsewhere, such
750 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
751 // that are on the desktop, as appropriate
752 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800753 if (modelItem != null &&
754 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
755 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700756 switch (modelItem.itemType) {
757 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
758 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
759 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
760 if (!sBgWorkspaceItems.contains(modelItem)) {
761 sBgWorkspaceItems.add(modelItem);
762 }
763 break;
764 default:
765 break;
766 }
767 } else {
768 sBgWorkspaceItems.remove(modelItem);
769 }
770 }
771 }
772
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800773 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400774 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700775 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700776 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700777 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400778 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400779 item.cellX = cellX;
780 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700781
Winson Chung3d503fb2011-07-13 17:25:49 -0700782 // We store hotseat items in canonical form which is this orientation invariant position
783 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700784 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700785 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700786 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700787 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700788 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700789 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400790
791 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400792 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700793 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
794 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800795 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700796 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400797
Michael Jurkac9d95c52011-08-29 14:03:34 -0700798 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700799 }
800
801 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700802 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
803 * cellX, cellY have already been updated on the ItemInfos.
804 */
805 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
806 final long container, final int screen) {
807
808 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
809 int count = items.size();
810
811 for (int i = 0; i < count; i++) {
812 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700813 item.container = container;
814
815 // We store hotseat items in canonical form which is this orientation invariant position
816 // in the hotseat
817 if (context instanceof Launcher && screen < 0 &&
818 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700819 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700820 item.cellY);
821 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700822 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700823 }
824
825 final ContentValues values = new ContentValues();
826 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
827 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
828 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800829 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700830 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700831
832 contentValues.add(values);
833 }
834 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
835 }
836
837 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700838 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800839 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700840 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700841 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700842 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800843 item.cellX = cellX;
844 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700845 item.spanX = spanX;
846 item.spanY = spanY;
847
848 // We store hotseat items in canonical form which is this orientation invariant position
849 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700850 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700851 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700852 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700853 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700855 }
Adam Cohend4844c32011-02-18 19:25:06 -0800856
Adam Cohend4844c32011-02-18 19:25:06 -0800857 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800858 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700859 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
860 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800861 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700862 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
863 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700864 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800865
Michael Jurka816474f2012-06-25 14:49:02 -0700866 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700867 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700868
869 /**
870 * Update an item to the database in a specified container.
871 */
872 static void updateItemInDatabase(Context context, final ItemInfo item) {
873 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100874 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700875 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800876 }
877
878 /**
Sunny Goyal756adbc2015-04-16 15:20:51 -0700879 * Returns true if the shortcuts already exists on the workspace. This must be called after
880 * the workspace has been loaded. We identify a shortcut by its intent.
881 * TODO: Throw exception is above condition is not met.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800882 */
Sunny Goyal756adbc2015-04-16 15:20:51 -0700883 @Thunk static boolean shortcutExists(Context context, Intent intent, UserHandleCompat user) {
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700884 final Intent intentWithPkg, intentWithoutPkg;
Sunny Goyal756adbc2015-04-16 15:20:51 -0700885 final String packageName;
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700886 if (intent.getComponent() != null) {
887 // If component is not null, an intent with null package will produce
888 // the same result and should also be a match.
Sunny Goyal756adbc2015-04-16 15:20:51 -0700889 packageName = intent.getComponent().getPackageName();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700890 if (intent.getPackage() != null) {
891 intentWithPkg = intent;
892 intentWithoutPkg = new Intent(intent).setPackage(null);
893 } else {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700894 intentWithPkg = new Intent(intent).setPackage(packageName);
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700895 intentWithoutPkg = intent;
896 }
897 } else {
898 intentWithPkg = intent;
899 intentWithoutPkg = intent;
Sunny Goyal756adbc2015-04-16 15:20:51 -0700900 packageName = intent.getPackage();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700901 }
Sunny Goyal756adbc2015-04-16 15:20:51 -0700902
903 synchronized (sBgLock) {
Sunny Goyale2df0622015-04-24 11:27:00 -0700904 for (ItemInfo item : sBgItemsIdMap) {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700905 if (item instanceof ShortcutInfo) {
906 ShortcutInfo info = (ShortcutInfo) item;
907 if (intentWithPkg.equals(info.getIntent())
908 || intentWithoutPkg.equals(info.getIntent())) {
909 return true;
910 }
911 }
912 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800913 }
Sunny Goyal756adbc2015-04-16 15:20:51 -0700914 return false;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700915 }
916
Joe Onorato9c1289c2009-08-17 11:03:03 -0400917 /**
918 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
919 */
Sunny Goyale2df0622015-04-24 11:27:00 -0700920 FolderInfo getFolderById(Context context, LongArrayMap<FolderInfo> folderList, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400921 final ContentResolver cr = context.getContentResolver();
922 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
923 "_id=? and (itemType=? or itemType=?)",
924 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700925 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700926
Joe Onorato9c1289c2009-08-17 11:03:03 -0400927 try {
928 if (c.moveToFirst()) {
929 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
930 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
931 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
932 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
933 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
934 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700935 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800936
Joe Onorato9c1289c2009-08-17 11:03:03 -0400937 FolderInfo folderInfo = null;
938 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700939 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
940 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400941 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700942 }
943
Joe Onorato9c1289c2009-08-17 11:03:03 -0400944 folderInfo.title = c.getString(titleIndex);
945 folderInfo.id = id;
946 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700948 folderInfo.cellX = c.getInt(cellXIndex);
949 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700950 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400951
952 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700953 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400954 } finally {
955 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700956 }
957
958 return null;
959 }
960
Joe Onorato9c1289c2009-08-17 11:03:03 -0400961 /**
962 * Add an item to the database in a specified container. Sets the container, screen, cellX and
963 * cellY fields of the item. Also assigns an ID to the item.
964 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700965 public static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700966 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968 item.cellX = cellX;
969 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700970 // We store hotseat items in canonical form which is this orientation invariant position
971 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700972 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700973 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700974 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700975 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700976 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700977 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978
979 final ContentValues values = new ContentValues();
980 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +0100981 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982
Michael Jurka414300a2013-08-27 15:42:35 +0200983 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700984 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -0700985
Jason Monk8e19cf22014-03-20 15:06:57 -0400986 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700987 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700988 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700989 cr.insert(LauncherSettings.Favorites.CONTENT_URI, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700991 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -0700992 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -0400993 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700994 sBgItemsIdMap.put(item.id, item);
995 switch (item.itemType) {
996 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
997 sBgFolders.put(item.id, (FolderInfo) item);
998 // Fall through
999 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1000 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1001 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1002 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1003 sBgWorkspaceItems.add(item);
1004 } else {
1005 if (!sBgFolders.containsKey(item.container)) {
1006 // Adding an item to a folder that doesn't exist.
1007 String msg = "adding item: " + item + " to a folder that " +
1008 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001009 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001010 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001011 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001012 break;
1013 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1014 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1015 break;
1016 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 }
1018 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001019 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001020 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001021 }
1022
Joe Onorato9c1289c2009-08-17 11:03:03 -04001023 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001024 * Creates a new unique child id, for a given cell span across all layouts.
1025 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001026 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001027 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001028 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001029 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001030 }
1031
Sunny Goyal34942622014-08-29 17:20:55 -07001032 private static ArrayList<ItemInfo> getItemsByPackageName(
1033 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001034 ItemInfoFilter filter = new ItemInfoFilter() {
1035 @Override
1036 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1037 return cn.getPackageName().equals(pn) && info.user.equals(user);
1038 }
1039 };
Sunny Goyale2df0622015-04-24 11:27:00 -07001040 return filterItemInfos(sBgItemsIdMap, filter);
Sunny Goyal34942622014-08-29 17:20:55 -07001041 }
1042
1043 /**
1044 * Removes all the items from the database corresponding to the specified package.
1045 */
1046 static void deletePackageFromDatabase(Context context, final String pn,
1047 final UserHandleCompat user) {
1048 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001049 }
1050
1051 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001052 * Removes the specified item from the database
1053 * @param context
1054 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001055 */
Sunny Goyalfa401a12015-04-10 13:45:42 -07001056 public static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001057 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1058 items.add(item);
1059 deleteItemsFromDatabase(context, items);
1060 }
1061
1062 /**
1063 * Removes the specified items from the database
1064 * @param context
1065 * @param item
1066 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001067 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001068 final ContentResolver cr = context.getContentResolver();
Michael Jurka83df1882011-08-31 20:59:26 -07001069 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001070 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001071 for (ItemInfo item : items) {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001072 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001073 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001074
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001075 // Lock on mBgLock *after* the db operation
1076 synchronized (sBgLock) {
1077 switch (item.itemType) {
1078 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1079 sBgFolders.remove(item.id);
Sunny Goyale2df0622015-04-24 11:27:00 -07001080 for (ItemInfo info: sBgItemsIdMap) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001081 if (info.container == item.id) {
1082 // We are deleting a folder which still contains items that
1083 // think they are contained by that folder.
1084 String msg = "deleting a folder (" + item + ") which still " +
1085 "contains items (" + info + ")";
1086 Log.e(TAG, msg);
1087 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001088 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001089 sBgWorkspaceItems.remove(item);
1090 break;
1091 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1092 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1093 sBgWorkspaceItems.remove(item);
1094 break;
1095 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1096 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1097 break;
1098 }
1099 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001100 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001101 }
1102 }
Michael Jurka83df1882011-08-31 20:59:26 -07001103 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001104 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001105 }
1106
1107 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001108 * Update the order of the workspace screens in the database. The array list contains
1109 * a list of screen ids in the order that they should appear.
1110 */
Winson Chungc9168342013-06-26 14:54:55 -07001111 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001112 // Log to disk
1113 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1114 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1115
Winson Chung64359a52013-07-08 17:17:08 -07001116 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001117 final ContentResolver cr = context.getContentResolver();
1118 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1119
1120 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001121 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001122 while (iter.hasNext()) {
1123 long id = iter.next();
1124 if (id < 0) {
1125 iter.remove();
1126 }
1127 }
1128
1129 Runnable r = new Runnable() {
1130 @Override
1131 public void run() {
Yura085c8532014-02-11 15:15:29 +00001132 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001133 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001134 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001135 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001136 for (int i = 0; i < count; i++) {
1137 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001138 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001139 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1140 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001141 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001142 }
Yura085c8532014-02-11 15:15:29 +00001143
1144 try {
1145 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1146 } catch (Exception ex) {
1147 throw new RuntimeException(ex);
1148 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001149
Winson Chungba9c37f2013-08-30 14:11:37 -07001150 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001151 sBgWorkspaceScreens.clear();
1152 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001153 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 }
1155 };
1156 runOnWorkerThread(r);
1157 }
1158
1159 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001160 * Remove the contents of the specified folder from the database
1161 */
Sunny Goyalfa401a12015-04-10 13:45:42 -07001162 public static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001163 final ContentResolver cr = context.getContentResolver();
1164
Michael Jurkac9d95c52011-08-29 14:03:34 -07001165 Runnable r = new Runnable() {
1166 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001167 cr.delete(LauncherSettings.Favorites.getContentUri(info.id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001168 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001169 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001170 sBgItemsIdMap.remove(info.id);
1171 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001172 sBgWorkspaceItems.remove(info);
1173 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001174
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001175 cr.delete(LauncherSettings.Favorites.CONTENT_URI,
Michael Jurkac9d95c52011-08-29 14:03:34 -07001176 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001177 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001178 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001179 for (ItemInfo childInfo : info.contents) {
1180 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001181 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001182 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001183 }
1184 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001185 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001186 }
1187
1188 /**
1189 * Set this as the current Launcher activity object for the loader.
1190 */
1191 public void initialize(Callbacks callbacks) {
1192 synchronized (mLock) {
Sunny Goyald33860f2015-04-23 16:02:20 -07001193 // Disconnect any of the callbacks and drawables associated with ItemInfos on the
1194 // workspace to prevent leaking Launcher activities on orientation change.
1195 unbindItemInfosAndClearQueuedBindRunnables();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196 mCallbacks = new WeakReference<Callbacks>(callbacks);
1197 }
1198 }
1199
Kenny Guyed131872014-04-30 03:02:21 +01001200 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001201 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001202 int op = PackageUpdatedTask.OP_UPDATE;
1203 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1204 user));
1205 }
1206
1207 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001208 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001209 int op = PackageUpdatedTask.OP_REMOVE;
1210 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1211 user));
1212 }
1213
1214 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001215 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001216 int op = PackageUpdatedTask.OP_ADD;
1217 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1218 user));
1219 }
1220
1221 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001222 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001223 boolean replacing) {
1224 if (!replacing) {
1225 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1226 user));
1227 if (mAppsCanBeOnRemoveableStorage) {
1228 // Only rebind if we support removable storage. It catches the
1229 // case where
1230 // apps on the external sd card need to be reloaded
1231 startLoaderFromBackground();
1232 }
1233 } else {
1234 // If we are replacing then just update the packages in the list
1235 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1236 packageNames, user));
1237 }
1238 }
1239
1240 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001241 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001242 boolean replacing) {
1243 if (!replacing) {
1244 enqueuePackageUpdated(new PackageUpdatedTask(
1245 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1246 user));
1247 }
Kenny Guyed131872014-04-30 03:02:21 +01001248 }
1249
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001250 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001251 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1252 * ACTION_PACKAGE_CHANGED.
1253 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001254 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001255 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001256 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001257
Joe Onorato36115782010-06-17 13:28:48 -04001258 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001259 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001260 // If we have changed locale we need to clear out the labels in all apps/workspace.
1261 forceReload();
1262 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1263 // Check if configuration change was an mcc/mnc change which would affect app resources
1264 // and we would need to clear out the labels in all apps/workspace. Same handling as
1265 // above for ACTION_LOCALE_CHANGED
1266 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001267 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001268 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001269 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001270 forceReload();
1271 }
1272 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001273 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001274 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1275 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001276 Callbacks callbacks = getCallback();
1277 if (callbacks != null) {
1278 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001279 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001280 }
1281 }
1282
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001283 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001284 resetLoadedState(true, true);
1285
Reena Lee93f824a2011-09-23 17:20:28 -07001286 // Do this here because if the launcher activity is running it will be restarted.
1287 // If it's not running startLoaderFromBackground will merely tell it that it needs
1288 // to reload.
1289 startLoaderFromBackground();
1290 }
1291
Winson Chungf0c6ae02012-03-21 16:10:31 -07001292 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1293 synchronized (mLock) {
1294 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1295 // mWorkspaceLoaded to true later
1296 stopLoaderLocked();
1297 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1298 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1299 }
1300 }
1301
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001302 /**
1303 * When the launcher is in the background, it's possible for it to miss paired
1304 * configuration changes. So whenever we trigger the loader from the background
1305 * tell the launcher that it needs to re-run the loader when it comes back instead
1306 * of doing it now.
1307 */
1308 public void startLoaderFromBackground() {
1309 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001310 Callbacks callbacks = getCallback();
1311 if (callbacks != null) {
1312 // Only actually run the loader if they're not paused.
1313 if (!callbacks.setLoadOnResume()) {
1314 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001315 }
1316 }
1317 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001318 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001319 }
Joe Onorato36115782010-06-17 13:28:48 -04001320 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001321
Reena Lee93f824a2011-09-23 17:20:28 -07001322 // If there is already a loader task running, tell it to stop.
1323 // returns true if isLaunching() was true on the old task
1324 private boolean stopLoaderLocked() {
1325 boolean isLaunching = false;
1326 LoaderTask oldTask = mLoaderTask;
1327 if (oldTask != null) {
1328 if (oldTask.isLaunching()) {
1329 isLaunching = true;
1330 }
1331 oldTask.stopLocked();
1332 }
1333 return isLaunching;
1334 }
1335
Adam Cohen1a85c582014-09-30 09:48:49 -07001336 public boolean isCurrentCallbacks(Callbacks callbacks) {
1337 return (mCallbacks != null && mCallbacks.get() == callbacks);
1338 }
1339
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001340 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001341 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1342 }
1343
1344 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Sunny Goyal756adbc2015-04-16 15:20:51 -07001345 // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
1346 InstallShortcutReceiver.enableInstallQueue();
Joe Onorato36115782010-06-17 13:28:48 -04001347 synchronized (mLock) {
1348 if (DEBUG_LOADERS) {
1349 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1350 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001351
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001352 // Clear any deferred bind-runnables from the synchronized load process
1353 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001354 synchronized (mDeferredBindRunnables) {
1355 mDeferredBindRunnables.clear();
1356 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001357
Joe Onorato36115782010-06-17 13:28:48 -04001358 // Don't bother to start the thread if we know it's not going to do anything
1359 if (mCallbacks != null && mCallbacks.get() != null) {
1360 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001361 // also, don't downgrade isLaunching if we're already running
1362 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001363 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001364 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1365 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001366 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1367 } else {
1368 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1369 sWorker.post(mLoaderTask);
1370 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001371 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001372 }
1373 }
1374
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001375 void bindRemainingSynchronousPages() {
1376 // Post the remaining side pages to be loaded
1377 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001378 Runnable[] deferredBindRunnables = null;
1379 synchronized (mDeferredBindRunnables) {
1380 deferredBindRunnables = mDeferredBindRunnables.toArray(
1381 new Runnable[mDeferredBindRunnables.size()]);
1382 mDeferredBindRunnables.clear();
1383 }
1384 for (final Runnable r : deferredBindRunnables) {
Sunny Goyald33860f2015-04-23 16:02:20 -07001385 mHandler.post(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001386 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 }
1388 }
1389
Joe Onorato36115782010-06-17 13:28:48 -04001390 public void stopLoader() {
1391 synchronized (mLock) {
1392 if (mLoaderTask != null) {
1393 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001394 }
1395 }
Joe Onorato36115782010-06-17 13:28:48 -04001396 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001397
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001398 /**
1399 * Loads the workspace screen ids in an ordered list.
1400 */
Adam Cohen091440a2015-03-18 14:16:05 -07001401 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001402 final ContentResolver contentResolver = context.getContentResolver();
1403 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001404
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001405 // Get screens ordered by rank.
1406 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1407 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1408 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001409 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001410 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001411 while (sc.moveToNext()) {
1412 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001413 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001414 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001415 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1416 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001417 }
1418 }
1419 } finally {
1420 sc.close();
1421 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001422 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001423 }
1424
Michael Jurkac57b7a82011-08-09 22:02:20 -07001425 public boolean isAllAppsLoaded() {
1426 return mAllAppsLoaded;
1427 }
1428
Winson Chung36a62fe2012-05-06 18:04:42 -07001429 boolean isLoadingWorkspace() {
1430 synchronized (mLock) {
1431 if (mLoaderTask != null) {
1432 return mLoaderTask.isLoadingWorkspace();
1433 }
1434 }
1435 return false;
1436 }
1437
Joe Onorato36115782010-06-17 13:28:48 -04001438 /**
1439 * Runnable for the thread that loads the contents of the launcher:
1440 * - workspace icons
1441 * - widgets
1442 * - all apps icons
1443 */
1444 private class LoaderTask implements Runnable {
1445 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001446 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001447 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001448 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001449 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001450 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001451
Dan Sandlerd5024042014-01-09 15:01:33 -05001452 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001453 mContext = context;
1454 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001455 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001456 }
1457
Joe Onorato36115782010-06-17 13:28:48 -04001458 boolean isLaunching() {
1459 return mIsLaunching;
1460 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001461
Winson Chung36a62fe2012-05-06 18:04:42 -07001462 boolean isLoadingWorkspace() {
1463 return mIsLoadingAndBindingWorkspace;
1464 }
1465
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001466 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001467 mIsLoadingAndBindingWorkspace = true;
1468
Joe Onorato36115782010-06-17 13:28:48 -04001469 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001470 if (DEBUG_LOADERS) {
1471 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001472 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001473
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001474 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001475 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001476 synchronized (LoaderTask.this) {
1477 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001478 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001479 }
1480 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001481 }
1482 }
1483
Joe Onorato36115782010-06-17 13:28:48 -04001484 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001485 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001486 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001487
Joe Onorato36115782010-06-17 13:28:48 -04001488 private void waitForIdle() {
1489 // Wait until the either we're stopped or the other threads are done.
1490 // This way we don't start loading all apps until the workspace has settled
1491 // down.
1492 synchronized (LoaderTask.this) {
1493 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001494
Joe Onorato36115782010-06-17 13:28:48 -04001495 mHandler.postIdle(new Runnable() {
1496 public void run() {
1497 synchronized (LoaderTask.this) {
1498 mLoadAndBindStepFinished = true;
1499 if (DEBUG_LOADERS) {
1500 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001501 }
Joe Onorato36115782010-06-17 13:28:48 -04001502 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001503 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001504 }
Joe Onorato36115782010-06-17 13:28:48 -04001505 });
1506
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001507 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001508 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001509 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1510 // wait no longer than 1sec at a time
1511 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001512 } catch (InterruptedException ex) {
1513 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001514 }
1515 }
Joe Onorato36115782010-06-17 13:28:48 -04001516 if (DEBUG_LOADERS) {
1517 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001518 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001519 + "ms for previous step to finish binding");
1520 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001521 }
Joe Onorato36115782010-06-17 13:28:48 -04001522 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001523
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001524 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001525 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001526 // Ensure that we have a valid page index to load synchronously
1527 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1528 "valid page index");
1529 }
1530 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1531 // Ensure that we don't try and bind a specified page when the pages have not been
1532 // loaded already (we should load everything asynchronously in that case)
1533 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1534 }
1535 synchronized (mLock) {
1536 if (mIsLoaderTaskRunning) {
1537 // Ensure that we are never running the background loading at this point since
1538 // we also touch the background collections
1539 throw new RuntimeException("Error! Background loading is already running");
1540 }
1541 }
1542
1543 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1544 // data structures, we can't allow any other thread to touch that data, but because
1545 // this call is synchronous, we can get away with not locking).
1546
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001547 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001548 // operations from the previous activity. We need to ensure that all queued operations
1549 // are executed before any synchronous binding work is done.
1550 mHandler.flush();
1551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001552 // Divide the set of loaded items into those that we are binding synchronously, and
1553 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001554 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001555 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1556 // arise from that.
1557 onlyBindAllApps();
1558 }
1559
Joe Onorato36115782010-06-17 13:28:48 -04001560 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001561 synchronized (mLock) {
1562 mIsLoaderTaskRunning = true;
1563 }
Joe Onorato36115782010-06-17 13:28:48 -04001564 // Optimize for end-user experience: if the Launcher is up and // running with the
1565 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1566 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001567 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001568 // Elevate priority when Home launches for the first time to avoid
1569 // starving at boot time. Staring at a blank home is not cool.
1570 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001571 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1572 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001573 android.os.Process.setThreadPriority(mIsLaunching
1574 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1575 }
Winson Chung64359a52013-07-08 17:17:08 -07001576 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001577 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001578
Joe Onorato36115782010-06-17 13:28:48 -04001579 if (mStopped) {
1580 break keep_running;
1581 }
1582
1583 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1584 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001585 synchronized (mLock) {
1586 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001587 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001588 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1589 }
1590 }
Joe Onorato36115782010-06-17 13:28:48 -04001591 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001592
1593 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001594 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1595 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001596
Sunny Goyal5b0e6692015-03-19 14:31:19 -07001597 // Remove entries for packages which changed while the launcher was dead.
1598 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews();
1599
Winson Chung7ed37742011-09-08 15:45:51 -07001600 // Restore the default thread priority after we are done loading items
1601 synchronized (mLock) {
1602 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603 }
Joe Onorato36115782010-06-17 13:28:48 -04001604 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001605
Joe Onorato36115782010-06-17 13:28:48 -04001606 // Clear out this reference, otherwise we end up holding it until all of the
1607 // callback runnables are done.
1608 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001609
Joe Onorato36115782010-06-17 13:28:48 -04001610 synchronized (mLock) {
1611 // If we are still the last one to be scheduled, remove ourselves.
1612 if (mLoaderTask == this) {
1613 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001614 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001615 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001616 }
Joe Onorato36115782010-06-17 13:28:48 -04001617 }
1618
1619 public void stopLocked() {
1620 synchronized (LoaderTask.this) {
1621 mStopped = true;
1622 this.notify();
1623 }
1624 }
1625
1626 /**
1627 * Gets the callbacks object. If we've been stopped, or if the launcher object
1628 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1629 * object that was around when the deferred message was scheduled, and if there's
1630 * a new Callbacks object around then also return null. This will save us from
1631 * calling onto it with data that will be ignored.
1632 */
1633 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1634 synchronized (mLock) {
1635 if (mStopped) {
1636 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001637 }
Joe Onorato36115782010-06-17 13:28:48 -04001638
1639 if (mCallbacks == null) {
1640 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001641 }
Joe Onorato36115782010-06-17 13:28:48 -04001642
1643 final Callbacks callbacks = mCallbacks.get();
1644 if (callbacks != oldCallbacks) {
1645 return null;
1646 }
1647 if (callbacks == null) {
1648 Log.w(TAG, "no mCallbacks");
1649 return null;
1650 }
1651
1652 return callbacks;
1653 }
1654 }
1655
1656 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyale2df0622015-04-24 11:27:00 -07001657 private boolean checkItemPlacement(LongArrayMap<ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001658 LauncherAppState app = LauncherAppState.getInstance();
1659 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001660 final int countX = (int) grid.numColumns;
1661 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001662
Adam Cohendcd297f2013-06-18 13:13:40 -07001663 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001664 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001665 // Return early if we detect that an item is under the hotseat button
1666 if (mCallbacks == null ||
1667 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001668 Log.e(TAG, "Error loading shortcut into hotseat " + item
1669 + " into position (" + item.screenId + ":" + item.cellX + ","
1670 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001671 return false;
1672 }
1673
Dan Sandler295ae182013-12-10 16:05:47 -05001674 final ItemInfo[][] hotseatItems =
1675 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1676
Adam Cohenae4409d2013-11-26 10:34:59 -08001677 if (item.screenId >= grid.numHotseatIcons) {
1678 Log.e(TAG, "Error loading shortcut " + item
1679 + " into hotseat position " + item.screenId
1680 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1681 + ")");
1682 return false;
1683 }
1684
Dan Sandler295ae182013-12-10 16:05:47 -05001685 if (hotseatItems != null) {
1686 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001687 Log.e(TAG, "Error loading shortcut into hotseat " + item
1688 + " into position (" + item.screenId + ":" + item.cellX + ","
1689 + item.cellY + ") occupied by "
1690 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1691 [(int) item.screenId][0]);
1692 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001693 } else {
1694 hotseatItems[(int) item.screenId][0] = item;
1695 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001696 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001697 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001698 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001699 items[(int) item.screenId][0] = item;
1700 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001701 return true;
1702 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001703 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1704 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001705 return true;
1706 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001707
Adam Cohendcd297f2013-06-18 13:13:40 -07001708 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001709 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001710 occupied.put(item.screenId, items);
1711 }
1712
Dan Sandler295ae182013-12-10 16:05:47 -05001713 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001714 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1715 item.cellX < 0 || item.cellY < 0 ||
1716 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1717 Log.e(TAG, "Error loading shortcut " + item
1718 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1719 + item.cellX + "," + item.cellY
1720 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1721 return false;
1722 }
1723
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001724 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001725 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1726 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001727 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001728 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001730 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001731 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001733 return false;
1734 }
1735 }
1736 }
1737 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1738 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001739 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001740 }
1741 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001742
Joe Onorato36115782010-06-17 13:28:48 -04001743 return true;
1744 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001745
Winson Chungba9c37f2013-08-30 14:11:37 -07001746 /** Clears all the sBg data structures */
1747 private void clearSBgDataStructures() {
1748 synchronized (sBgLock) {
1749 sBgWorkspaceItems.clear();
1750 sBgAppWidgets.clear();
1751 sBgFolders.clear();
1752 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001753 sBgWorkspaceScreens.clear();
1754 }
1755 }
1756
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001757 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001758 // Log to disk
1759 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1760
Joe Onorato36115782010-06-17 13:28:48 -04001761 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001762
Joe Onorato36115782010-06-17 13:28:48 -04001763 final Context context = mContext;
1764 final ContentResolver contentResolver = context.getContentResolver();
1765 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001766 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001767 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1768 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001769 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001770
Winson Chung892c74d2013-08-22 16:15:50 -07001771 LauncherAppState app = LauncherAppState.getInstance();
1772 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1773 int countX = (int) grid.numColumns;
1774 int countY = (int) grid.numRows;
1775
Dan Sandlerd5024042014-01-09 15:01:33 -05001776 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1777 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1778 LauncherAppState.getLauncherProvider().deleteDatabase();
1779 }
1780
1781 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1782 // append the user's Launcher2 shortcuts
1783 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1784 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1785 } else {
1786 // Make sure the default workspace is loaded
1787 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001788 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001789 }
Adam Cohene25af792013-06-06 23:08:25 -07001790
Winson Chung2abf94d2012-07-18 18:16:38 -07001791 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001792 clearSBgDataStructures();
Sunny Goyal756adbc2015-04-16 15:20:51 -07001793 final HashMap<String, Integer> installingPkgs = PackageInstallerCompat
Sunny Goyal94485362014-09-18 16:13:58 -07001794 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001795
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001796 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001797 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001798 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001799 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001800 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001801
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001802 // +1 for the hotseat (it can be larger than the workspace)
1803 // Load workspace in reverse order to ensure that latest items are loaded first (and
1804 // before any earlier duplicates)
Sunny Goyale2df0622015-04-24 11:27:00 -07001805 final LongArrayMap<ItemInfo[][]> occupied = new LongArrayMap<>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001806
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001807 try {
1808 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1809 final int intentIndex = c.getColumnIndexOrThrow
1810 (LauncherSettings.Favorites.INTENT);
1811 final int titleIndex = c.getColumnIndexOrThrow
1812 (LauncherSettings.Favorites.TITLE);
1813 final int iconTypeIndex = c.getColumnIndexOrThrow(
1814 LauncherSettings.Favorites.ICON_TYPE);
1815 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1816 final int iconPackageIndex = c.getColumnIndexOrThrow(
1817 LauncherSettings.Favorites.ICON_PACKAGE);
1818 final int iconResourceIndex = c.getColumnIndexOrThrow(
1819 LauncherSettings.Favorites.ICON_RESOURCE);
1820 final int containerIndex = c.getColumnIndexOrThrow(
1821 LauncherSettings.Favorites.CONTAINER);
1822 final int itemTypeIndex = c.getColumnIndexOrThrow(
1823 LauncherSettings.Favorites.ITEM_TYPE);
1824 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1825 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001826 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1827 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 final int screenIndex = c.getColumnIndexOrThrow(
1829 LauncherSettings.Favorites.SCREEN);
1830 final int cellXIndex = c.getColumnIndexOrThrow
1831 (LauncherSettings.Favorites.CELLX);
1832 final int cellYIndex = c.getColumnIndexOrThrow
1833 (LauncherSettings.Favorites.CELLY);
1834 final int spanXIndex = c.getColumnIndexOrThrow
1835 (LauncherSettings.Favorites.SPANX);
1836 final int spanYIndex = c.getColumnIndexOrThrow(
1837 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001838 final int rankIndex = c.getColumnIndexOrThrow(
1839 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001840 final int restoredIndex = c.getColumnIndexOrThrow(
1841 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001842 final int profileIdIndex = c.getColumnIndexOrThrow(
1843 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001844 final int optionsIndex = c.getColumnIndexOrThrow(
1845 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001846
Sunny Goyal7f834d22015-04-21 10:10:23 -07001847 final LongSparseArray<UserHandleCompat> allUsers = new LongSparseArray<>();
1848 for (UserHandleCompat user : mUserManager.getUserProfiles()) {
1849 allUsers.put(mUserManager.getSerialNumberForUser(user), user);
1850 }
1851
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001852 ShortcutInfo info;
1853 String intentDescription;
1854 LauncherAppWidgetInfo appWidgetInfo;
1855 int container;
1856 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001857 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001858 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001859 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001860
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001861 while (!mStopped && c.moveToNext()) {
1862 try {
1863 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001864 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001865 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001866
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001867 switch (itemType) {
1868 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1869 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001870 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001872 serialNumber = c.getInt(profileIdIndex);
Sunny Goyal7f834d22015-04-21 10:10:23 -07001873 user = allUsers.get(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001874 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001875 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001876 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001877 if (user == null) {
1878 // User has been deleted remove the item.
1879 itemsToRemove.add(id);
1880 continue;
1881 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001882 try {
1883 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001884 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001885 if (cn != null && cn.getPackageName() != null) {
1886 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1887 cn.getPackageName(), user);
1888 boolean validComponent = validPkg &&
1889 launcherApps.isActivityEnabledForProfile(cn, user);
1890
1891 if (validComponent) {
1892 if (restored) {
1893 // no special handling necessary for this item
1894 restoredRows.add(id);
1895 restored = false;
1896 }
1897 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001898 intent = null;
1899 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1900 // We allow auto install apps to have their intent
1901 // updated after an install.
1902 intent = manager.getLaunchIntentForPackage(
1903 cn.getPackageName());
1904 if (intent != null) {
1905 ContentValues values = new ContentValues();
1906 values.put(LauncherSettings.Favorites.INTENT,
1907 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001908 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001909 }
1910 }
1911
1912 if (intent == null) {
1913 // The app is installed but the component is no
1914 // longer available.
1915 Launcher.addDumpLog(TAG,
1916 "Invalid component removed: " + cn, true);
1917 itemsToRemove.add(id);
1918 continue;
1919 } else {
1920 // no special handling necessary for this item
1921 restoredRows.add(id);
1922 restored = false;
1923 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001924 } else if (restored) {
1925 // Package is not yet available but might be
1926 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001927 Launcher.addDumpLog(TAG,
1928 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001929
1930 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1931 // Restore has started once.
Sunny Goyal756adbc2015-04-16 15:20:51 -07001932 } else if (installingPkgs.containsKey(cn.getPackageName())) {
Sunny Goyal94485362014-09-18 16:13:58 -07001933 // App restore has started. Update the flag
1934 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1935 ContentValues values = new ContentValues();
1936 values.put(LauncherSettings.Favorites.RESTORED,
1937 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001938 updateItem(id, values);
1939 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1940 // This is a common app. Try to replace this.
1941 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1942 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1943 if (parser.findDefaultApp()) {
1944 // Default app found. Replace it.
1945 intent = parser.parsedIntent;
1946 cn = intent.getComponent();
1947 ContentValues values = parser.parsedValues;
1948 values.put(LauncherSettings.Favorites.RESTORED, 0);
1949 updateItem(id, values);
1950 restored = false;
1951 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001952
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001953 } else if (REMOVE_UNRESTORED_ICONS) {
1954 Launcher.addDumpLog(TAG,
1955 "Unrestored package removed: " + cn, true);
1956 itemsToRemove.add(id);
1957 continue;
1958 }
Sunny Goyal94485362014-09-18 16:13:58 -07001959 } else if (REMOVE_UNRESTORED_ICONS) {
1960 Launcher.addDumpLog(TAG,
1961 "Unrestored package removed: " + cn, true);
1962 itemsToRemove.add(id);
1963 continue;
1964 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001965 } else if (launcherApps.isAppEnabled(
1966 manager, cn.getPackageName(),
1967 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1968 // Package is present but not available.
1969 allowMissingTarget = true;
1970 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1971 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001972 // SdCard is not ready yet. Package might get available,
1973 // once it is ready.
1974 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1975 + " (check again later)", true);
1976 HashSet<String> pkgs = sPendingPackages.get(user);
1977 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001978 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001979 sPendingPackages.put(user, pkgs);
1980 }
1981 pkgs.add(cn.getPackageName());
1982 allowMissingTarget = true;
1983 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07001984
1985 } else {
1986 // Do not wait for external media load anymore.
1987 // Log the invalid package, and remove it
1988 Launcher.addDumpLog(TAG,
1989 "Invalid package removed: " + cn, true);
1990 itemsToRemove.add(id);
1991 continue;
Winson Chungee055712013-07-30 14:46:24 -07001992 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07001993 } else if (cn == null) {
1994 // For shortcuts with no component, keep them as they are
1995 restoredRows.add(id);
1996 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07001997 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001998 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05001999 Launcher.addDumpLog(TAG,
2000 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002001 continue;
2002 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002003
Sunny Goyal34b65272015-03-11 16:56:52 -07002004 container = c.getInt(containerIndex);
2005 boolean useLowResIcon = container >= 0 &&
2006 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2007
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002008 if (itemReplaced) {
2009 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002010 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002011 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002012 } else {
2013 // Don't replace items for other profiles.
2014 itemsToRemove.add(id);
2015 continue;
2016 }
2017 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002018 if (user.equals(UserHandleCompat.myUserHandle())) {
2019 Launcher.addDumpLog(TAG,
2020 "constructing info for partially restored package",
2021 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002022 info = getRestoredItemInfo(c, titleIndex, intent,
2023 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002024 intent = getRestoredItemIntent(c, context, intent);
2025 } else {
2026 // Don't restore items for other profiles.
2027 itemsToRemove.add(id);
2028 continue;
2029 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002030 } else if (itemType ==
2031 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002032 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002033 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002034 } else {
2035 info = getShortcutInfo(c, context, iconTypeIndex,
2036 iconPackageIndex, iconResourceIndex, iconIndex,
2037 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002038
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002039 // App shortcuts that used to be automatically added to Launcher
2040 // didn't always have the correct intent flags set, so do that
2041 // here
2042 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002043 intent.getCategories() != null &&
2044 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002045 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002046 intent.addFlags(
2047 Intent.FLAG_ACTIVITY_NEW_TASK |
2048 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2049 }
Michael Jurka96879562012-03-22 05:54:33 -07002050 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002051
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002052 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002053 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002056 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 info.cellX = c.getInt(cellXIndex);
2058 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002059 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002060 info.spanX = 1;
2061 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002062 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002063 info.isDisabled = disabledState;
2064 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2065 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2066 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002067
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002069 if (!checkItemPlacement(occupied, info)) {
2070 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 break;
2072 }
2073
Sunny Goyal756adbc2015-04-16 15:20:51 -07002074 if (restored) {
2075 ComponentName cn = info.getTargetComponent();
2076 if (cn != null) {
2077 Integer progress = installingPkgs.get(cn.getPackageName());
2078 if (progress != null) {
2079 info.setInstallProgress(progress);
2080 } else {
2081 info.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
2082 }
2083 }
2084 }
2085
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 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;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002117 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002118
Daniel Sandler8802e962010-05-26 16:28:16 -04002119 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002120 if (!checkItemPlacement(occupied, folderInfo)) {
2121 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002122 break;
2123 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002124
Joe Onorato9c1289c2009-08-17 11:03:03 -04002125 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2127 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2128 sBgWorkspaceItems.add(folderInfo);
2129 break;
Joe Onorato36115782010-06-17 13:28:48 -04002130 }
Joe Onorato17a89222011-02-08 17:26:11 -08002131
Chris Wrenf4d08112014-01-16 18:13:56 -05002132 if (restored) {
2133 // no special handling required for restored folders
2134 restoredRows.add(id);
2135 }
2136
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2138 sBgFolders.put(folderInfo.id, folderInfo);
2139 break;
2140
2141 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002142 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002144 boolean customWidget = itemType ==
2145 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2146
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 int appWidgetId = c.getInt(appWidgetIdIndex);
Sunny Goyal7f834d22015-04-21 10:10:23 -07002148 serialNumber = c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002149 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002150 id = c.getLong(idIndex);
Sunny Goyal7f834d22015-04-21 10:10:23 -07002151 user = allUsers.get(serialNumber);
2152 if (user == null) {
2153 itemsToRemove.add(id);
2154 continue;
2155 }
2156
Sunny Goyalff572272014-07-23 13:58:07 -07002157 final ComponentName component =
2158 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002159
Sunny Goyal651077b2014-06-30 14:15:31 -07002160 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002161 final boolean isIdValid = (restoreStatus &
2162 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Sunny Goyalff572272014-07-23 13:58:07 -07002163 final boolean wasProviderReady = (restoreStatus &
2164 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002165
Adam Cohen59400422014-03-05 18:07:04 -08002166 final LauncherAppWidgetProviderInfo provider =
2167 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002168 ComponentName.unflattenFromString(savedProvider),
Sunny Goyal7f834d22015-04-21 10:10:23 -07002169 user);
Sunny Goyalff572272014-07-23 13:58:07 -07002170
2171 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002172 if (!isSafeMode && !customWidget &&
2173 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002174 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002175 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002176
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002177 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002178 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 itemsToRemove.add(id);
2180 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002181 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002182 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2183 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002184
2185 if (!customWidget) {
2186 int[] minSpan =
2187 Launcher.getMinSpanForWidget(context, provider);
2188 appWidgetInfo.minSpanX = minSpan[0];
2189 appWidgetInfo.minSpanY = minSpan[1];
2190 }
Sunny Goyalff572272014-07-23 13:58:07 -07002191
2192 int status = restoreStatus;
2193 if (!wasProviderReady) {
2194 // If provider was not previously ready, update the
2195 // status and UI flag.
2196
2197 // Id would be valid only if the widget restore broadcast was received.
2198 if (isIdValid) {
2199 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2200 } else {
2201 status &= ~LauncherAppWidgetInfo
2202 .FLAG_PROVIDER_NOT_READY;
2203 }
2204 }
2205 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002206 } else {
2207 Log.v(TAG, "Widget restore pending id=" + id
2208 + " appWidgetId=" + appWidgetId
2209 + " status =" + restoreStatus);
2210 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002211 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002212 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal756adbc2015-04-16 15:20:51 -07002213 Integer installProgress = installingPkgs.get(component.getPackageName());
Sunny Goyal94485362014-09-18 16:13:58 -07002214
2215 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2216 // Restore has started once.
Sunny Goyal756adbc2015-04-16 15:20:51 -07002217 } else if (installProgress != null) {
Sunny Goyal94485362014-09-18 16:13:58 -07002218 // App restore has started. Update the flag
2219 appWidgetInfo.restoreStatus |=
2220 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002221 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002222 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002223 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002224 itemsToRemove.add(id);
2225 continue;
2226 }
Sunny Goyal756adbc2015-04-16 15:20:51 -07002227
2228 appWidgetInfo.installProgress =
2229 installProgress == null ? 0 : installProgress;
Sunny Goyal651077b2014-06-30 14:15:31 -07002230 }
Sunny Goyalff572272014-07-23 13:58:07 -07002231
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002233 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002234 appWidgetInfo.cellX = c.getInt(cellXIndex);
2235 appWidgetInfo.cellY = c.getInt(cellYIndex);
2236 appWidgetInfo.spanX = c.getInt(spanXIndex);
2237 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002238
Adam Cohen59400422014-03-05 18:07:04 -08002239 if (!customWidget) {
2240 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2241 appWidgetInfo.minSpanX = minSpan[0];
2242 appWidgetInfo.minSpanY = minSpan[1];
2243 }
2244
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002245 container = c.getInt(containerIndex);
2246 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2247 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2248 Log.e(TAG, "Widget found where container != " +
2249 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2250 continue;
2251 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002252
Adam Cohene25af792013-06-06 23:08:25 -07002253 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002254 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002255 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2256 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002257 break;
2258 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002259
Adam Cohen59400422014-03-05 18:07:04 -08002260 if (!customWidget) {
2261 String providerName =
2262 appWidgetInfo.providerName.flattenToString();
2263 if (!providerName.equals(savedProvider) ||
2264 (appWidgetInfo.restoreStatus != restoreStatus)) {
2265 ContentValues values = new ContentValues();
2266 values.put(
2267 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2268 providerName);
2269 values.put(LauncherSettings.Favorites.RESTORED,
2270 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002271 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002272 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002273 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002274 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2275 sBgAppWidgets.add(appWidgetInfo);
2276 }
Joe Onorato36115782010-06-17 13:28:48 -04002277 break;
2278 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002279 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002280 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002281 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002282 }
2283 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002284 if (c != null) {
2285 c.close();
2286 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 }
2288
Winson Chungba9c37f2013-08-30 14:11:37 -07002289 // Break early if we've stopped loading
2290 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002291 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002292 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002293 }
2294
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002295 if (itemsToRemove.size() > 0) {
2296 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002297 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002298 // Remove dead items
2299 for (long id : itemsToRemove) {
2300 if (DEBUG_LOADERS) {
2301 Log.d(TAG, "Removed id = " + id);
2302 }
2303 // Don't notify content observers
2304 try {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002305 client.delete(LauncherSettings.Favorites.getContentUri(id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002306 } catch (RemoteException e) {
2307 Log.w(TAG, "Could not remove id = " + id);
2308 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002309 }
2310 }
2311
Chris Wrenf4d08112014-01-16 18:13:56 -05002312 if (restoredRows.size() > 0) {
2313 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002314 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002315 // Update restored items that no longer require special handling
2316 try {
2317 StringBuilder selectionBuilder = new StringBuilder();
2318 selectionBuilder.append(LauncherSettings.Favorites._ID);
2319 selectionBuilder.append(" IN (");
2320 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2321 selectionBuilder.append(")");
2322 ContentValues values = new ContentValues();
2323 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002324 updater.update(LauncherSettings.Favorites.CONTENT_URI,
Chris Wrenf4d08112014-01-16 18:13:56 -05002325 values, selectionBuilder.toString(), null);
2326 } catch (RemoteException e) {
2327 Log.w(TAG, "Could not update restored rows");
2328 }
2329 }
2330
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002331 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2332 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002333 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002334 null, sWorker);
2335 }
2336
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002337 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2338 // Log to disk
2339 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2340 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002341
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002342 // Remove any empty screens
2343 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
Sunny Goyale2df0622015-04-24 11:27:00 -07002344 for (ItemInfo item: sBgItemsIdMap) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002345 long screenId = item.screenId;
2346 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2347 unusedScreens.contains(screenId)) {
2348 unusedScreens.remove(screenId);
2349 }
2350 }
2351
2352 // If there are any empty screens remove them, and update.
2353 if (unusedScreens.size() != 0) {
2354 // Log to disk
2355 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2356 TextUtils.join(", ", unusedScreens), true);
2357
2358 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002359 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002360 }
2361
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 if (DEBUG_LOADERS) {
2363 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2364 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002365 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002366 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002367 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002368
Sunny Goyale2df0622015-04-24 11:27:00 -07002369 for (int i = 0; i < nScreens; i++) {
2370 long screenId = occupied.keyAt(i);
Winson Chungc9168342013-06-26 14:54:55 -07002371 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002372 line += " | ";
2373 }
Sunny Goyale2df0622015-04-24 11:27:00 -07002374 ItemInfo[][] screen = occupied.valueAt(i);
Winson Chung892c74d2013-08-22 16:15:50 -07002375 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002376 if (x < screen.length && y < screen[x].length) {
2377 line += (screen[x][y] != null) ? "#" : ".";
2378 } else {
2379 line += "!";
2380 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002381 }
Joe Onorato36115782010-06-17 13:28:48 -04002382 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002383 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002384 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002385 }
Joe Onorato36115782010-06-17 13:28:48 -04002386 }
Adam Cohene25af792013-06-06 23:08:25 -07002387 }
2388
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002389 /**
2390 * Partially updates the item without any notification. Must be called on the worker thread.
2391 */
2392 private void updateItem(long itemId, ContentValues update) {
2393 mContext.getContentResolver().update(
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002394 LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002395 update,
2396 BaseColumns._ID + "= ?",
2397 new String[]{Long.toString(itemId)});
2398 }
2399
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002400 /** Filters the set of items who are directly or indirectly (via another container) on the
2401 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002402 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 ArrayList<ItemInfo> allWorkspaceItems,
2404 ArrayList<ItemInfo> currentScreenItems,
2405 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002406 // Purge any null ItemInfos
2407 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2408 while (iter.hasNext()) {
2409 ItemInfo i = iter.next();
2410 if (i == null) {
2411 iter.remove();
2412 }
2413 }
2414
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002415 // Order the set of items by their containers first, this allows use to walk through the
2416 // list sequentially, build up a list of containers that are in the specified screen,
2417 // as well as all items in those containers.
2418 Set<Long> itemsOnScreen = new HashSet<Long>();
2419 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2420 @Override
2421 public int compare(ItemInfo lhs, ItemInfo rhs) {
2422 return (int) (lhs.container - rhs.container);
2423 }
2424 });
2425 for (ItemInfo info : allWorkspaceItems) {
2426 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002427 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002428 currentScreenItems.add(info);
2429 itemsOnScreen.add(info.id);
2430 } else {
2431 otherScreenItems.add(info);
2432 }
2433 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2434 currentScreenItems.add(info);
2435 itemsOnScreen.add(info.id);
2436 } else {
2437 if (itemsOnScreen.contains(info.container)) {
2438 currentScreenItems.add(info);
2439 itemsOnScreen.add(info.id);
2440 } else {
2441 otherScreenItems.add(info);
2442 }
2443 }
2444 }
2445 }
2446
2447 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002448 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002449 ArrayList<LauncherAppWidgetInfo> appWidgets,
2450 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2451 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452
2453 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002454 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002455 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002456 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 currentScreenWidgets.add(widget);
2458 } else {
2459 otherScreenWidgets.add(widget);
2460 }
2461 }
2462 }
2463
2464 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002465 private void filterCurrentFolders(long currentScreenId,
Sunny Goyale2df0622015-04-24 11:27:00 -07002466 LongArrayMap<ItemInfo> itemsIdMap,
2467 LongArrayMap<FolderInfo> folders,
2468 LongArrayMap<FolderInfo> currentScreenFolders,
2469 LongArrayMap<FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002470
Sunny Goyale2df0622015-04-24 11:27:00 -07002471 int total = folders.size();
2472 for (int i = 0; i < total; i++) {
2473 long id = folders.keyAt(i);
2474 FolderInfo folder = folders.valueAt(i);
2475
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002476 ItemInfo info = itemsIdMap.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002477 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002478 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002479 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 currentScreenFolders.put(id, folder);
2481 } else {
2482 otherScreenFolders.put(id, folder);
2483 }
2484 }
2485 }
2486
2487 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2488 * right) */
2489 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002490 final LauncherAppState app = LauncherAppState.getInstance();
2491 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002492 // XXX: review this
2493 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002494 @Override
2495 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002496 int cellCountX = (int) grid.numColumns;
2497 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002498 int screenOffset = cellCountX * cellCountY;
2499 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002500 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002501 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002502 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002503 rhs.cellY * cellCountX + rhs.cellX);
2504 return (int) (lr - rr);
2505 }
2506 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002507 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002508
Adam Cohendcd297f2013-06-18 13:13:40 -07002509 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2510 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002511 final Runnable r = new Runnable() {
2512 @Override
2513 public void run() {
2514 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2515 if (callbacks != null) {
2516 callbacks.bindScreens(orderedScreens);
2517 }
2518 }
2519 };
Sunny Goyald33860f2015-04-23 16:02:20 -07002520 runOnMainThread(r);
Adam Cohendcd297f2013-06-18 13:13:40 -07002521 }
2522
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2524 final ArrayList<ItemInfo> workspaceItems,
2525 final ArrayList<LauncherAppWidgetInfo> appWidgets,
Sunny Goyale2df0622015-04-24 11:27:00 -07002526 final LongArrayMap<FolderInfo> folders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002527 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002528
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529 final boolean postOnMainThread = (deferredBindRunnables != null);
2530
2531 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002532 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002534 final int start = i;
2535 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002536 final Runnable r = new Runnable() {
2537 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002538 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002539 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002540 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002541 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2542 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002543 }
2544 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 };
2546 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002547 synchronized (deferredBindRunnables) {
2548 deferredBindRunnables.add(r);
2549 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002550 } else {
Sunny Goyald33860f2015-04-23 16:02:20 -07002551 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552 }
Joe Onorato36115782010-06-17 13:28:48 -04002553 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002554
2555 // Bind the folders
2556 if (!folders.isEmpty()) {
2557 final Runnable r = new Runnable() {
2558 public void run() {
2559 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2560 if (callbacks != null) {
2561 callbacks.bindFolders(folders);
2562 }
2563 }
2564 };
2565 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002566 synchronized (deferredBindRunnables) {
2567 deferredBindRunnables.add(r);
2568 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569 } else {
Sunny Goyald33860f2015-04-23 16:02:20 -07002570 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002571 }
2572 }
2573
2574 // Bind the widgets, one at a time
2575 N = appWidgets.size();
2576 for (int i = 0; i < N; i++) {
2577 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2578 final Runnable r = new Runnable() {
2579 public void run() {
2580 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2581 if (callbacks != null) {
2582 callbacks.bindAppWidget(widget);
2583 }
2584 }
2585 };
2586 if (postOnMainThread) {
2587 deferredBindRunnables.add(r);
2588 } else {
Sunny Goyald33860f2015-04-23 16:02:20 -07002589 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002590 }
2591 }
2592 }
2593
2594 /**
2595 * Binds all loaded data to actual views on the main thread.
2596 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002597 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002598 final long t = SystemClock.uptimeMillis();
2599 Runnable r;
2600
2601 // Don't use these two variables in any of the callback runnables.
2602 // Otherwise we hold a reference to them.
2603 final Callbacks oldCallbacks = mCallbacks.get();
2604 if (oldCallbacks == null) {
2605 // This launcher has exited and nobody bothered to tell us. Just bail.
2606 Log.w(TAG, "LoaderTask running with no launcher");
2607 return;
2608 }
2609
Winson Chung9b9fb962013-11-15 15:39:34 -08002610 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2612 ArrayList<LauncherAppWidgetInfo> appWidgets =
2613 new ArrayList<LauncherAppWidgetInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002614 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Sunny Goyale2df0622015-04-24 11:27:00 -07002615
2616 final LongArrayMap<FolderInfo> folders;
2617 final LongArrayMap<ItemInfo> itemsIdMap;
2618
Winson Chung2abf94d2012-07-18 18:16:38 -07002619 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002620 workspaceItems.addAll(sBgWorkspaceItems);
2621 appWidgets.addAll(sBgAppWidgets);
Adam Cohendcd297f2013-06-18 13:13:40 -07002622 orderedScreenIds.addAll(sBgWorkspaceScreens);
Sunny Goyale2df0622015-04-24 11:27:00 -07002623
2624 folders = sBgFolders.clone();
2625 itemsIdMap = sBgItemsIdMap.clone();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002626 }
2627
Derek Prothro7aff3992013-12-10 14:00:37 -05002628 final boolean isLoadingSynchronously =
2629 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002630 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002631 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002632 if (currScreen >= orderedScreenIds.size()) {
2633 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002634 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002635 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002636 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002637 final long currentScreenId = currentScreen < 0
2638 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002639
2640 // Load all the items that are on the current page first (and in the process, unbind
2641 // all the existing workspace items before we call startBinding() below.
2642 unbindWorkspaceItemsOnMainThread();
2643
2644 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002645 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2646 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2647 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2648 new ArrayList<LauncherAppWidgetInfo>();
2649 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2650 new ArrayList<LauncherAppWidgetInfo>();
Sunny Goyale2df0622015-04-24 11:27:00 -07002651 LongArrayMap<FolderInfo> currentFolders = new LongArrayMap<>();
2652 LongArrayMap<FolderInfo> otherFolders = new LongArrayMap<>();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653
Winson Chung9b9fb962013-11-15 15:39:34 -08002654 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002656 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002657 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002658 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002659 otherFolders);
2660 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2661 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2662
2663 // Tell the workspace that we're about to start binding items
2664 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002665 public void run() {
2666 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2667 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002669 }
2670 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671 };
Sunny Goyald33860f2015-04-23 16:02:20 -07002672 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002673
Adam Cohendcd297f2013-06-18 13:13:40 -07002674 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2675
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002676 // Load items on the current page
2677 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2678 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002679 if (isLoadingSynchronously) {
2680 r = new Runnable() {
2681 public void run() {
2682 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002683 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002684 callbacks.onPageBoundSynchronously(currentScreen);
2685 }
2686 }
2687 };
Sunny Goyald33860f2015-04-23 16:02:20 -07002688 runOnMainThread(r);
Adam Cohen1462de32012-07-24 22:34:36 -07002689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002690
Winson Chung4a2afa32012-07-19 14:53:05 -07002691 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2692 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002693 synchronized (mDeferredBindRunnables) {
2694 mDeferredBindRunnables.clear();
2695 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002696 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002697 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002698
2699 // Tell the workspace that we're done binding items
2700 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002701 public void run() {
2702 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2703 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002704 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002705 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002706
Winson Chung98e030b2012-05-07 16:01:11 -07002707 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002708 if (DEBUG_LOADERS) {
2709 Log.d(TAG, "bound workspace in "
2710 + (SystemClock.uptimeMillis()-t) + "ms");
2711 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002712
2713 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002714 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002715 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002716 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002717 synchronized (mDeferredBindRunnables) {
2718 mDeferredBindRunnables.add(r);
2719 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002720 } else {
Sunny Goyald33860f2015-04-23 16:02:20 -07002721 runOnMainThread(r);
Winson Chung4a2afa32012-07-19 14:53:05 -07002722 }
Joe Onorato36115782010-06-17 13:28:48 -04002723 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002724
Joe Onorato36115782010-06-17 13:28:48 -04002725 private void loadAndBindAllApps() {
2726 if (DEBUG_LOADERS) {
2727 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2728 }
2729 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002730 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002731 synchronized (LoaderTask.this) {
2732 if (mStopped) {
2733 return;
2734 }
2735 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002736 }
Joe Onorato36115782010-06-17 13:28:48 -04002737 } else {
2738 onlyBindAllApps();
2739 }
2740 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002741
Joe Onorato36115782010-06-17 13:28:48 -04002742 private void onlyBindAllApps() {
2743 final Callbacks oldCallbacks = mCallbacks.get();
2744 if (oldCallbacks == null) {
2745 // This launcher has exited and nobody bothered to tell us. Just bail.
2746 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2747 return;
2748 }
2749
2750 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002751 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002752 final ArrayList<AppInfo> list
2753 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002754 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002755 public void run() {
2756 final long t = SystemClock.uptimeMillis();
2757 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2758 if (callbacks != null) {
2759 callbacks.bindAllApplications(list);
2760 }
2761 if (DEBUG_LOADERS) {
2762 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2763 + (SystemClock.uptimeMillis()-t) + "ms");
2764 }
2765 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002766 };
2767 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002768 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002769 r.run();
2770 } else {
2771 mHandler.post(r);
2772 }
Joe Onorato36115782010-06-17 13:28:48 -04002773 }
2774
Winson Chung64359a52013-07-08 17:17:08 -07002775 private void loadAllApps() {
2776 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002777
Joe Onorato36115782010-06-17 13:28:48 -04002778 final Callbacks oldCallbacks = mCallbacks.get();
2779 if (oldCallbacks == null) {
2780 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002781 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002782 return;
2783 }
2784
2785 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2786 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2787
Kenny Guyed131872014-04-30 03:02:21 +01002788 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2789
Winson Chung64359a52013-07-08 17:17:08 -07002790 // Clear the list of apps
2791 mBgAllAppsList.clear();
Kenny Guyed131872014-04-30 03:02:21 +01002792 for (UserHandleCompat user : profiles) {
2793 // Query for the set of apps
2794 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2795 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2796 if (DEBUG_LOADERS) {
2797 Log.d(TAG, "getActivityList took "
2798 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2799 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2800 }
2801 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002802 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002803 if (apps == null || apps.isEmpty()) {
2804 return;
2805 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002806
2807 // Update icon cache
2808 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2809
2810 // If any package icon has changed (app was updated while launcher was dead),
2811 // update the corresponding shortcuts.
2812 if (!updatedPackages.isEmpty()) {
2813 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2814 synchronized (sBgLock) {
Sunny Goyale2df0622015-04-24 11:27:00 -07002815 for (ItemInfo info : sBgItemsIdMap) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002816 if (info instanceof ShortcutInfo && user.equals(info.user)
2817 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2818 ShortcutInfo si = (ShortcutInfo) info;
2819 ComponentName cn = si.getTargetComponent();
2820 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2821 si.updateIcon(mIconCache);
2822 updates.add(si);
2823 }
2824 }
2825 }
2826 }
2827
2828 if (!updates.isEmpty()) {
2829 final UserHandleCompat userFinal = user;
2830 mHandler.post(new Runnable() {
2831
2832 public void run() {
2833 Callbacks cb = getCallback();
2834 if (cb != null) {
2835 cb.bindShortcutsChanged(
2836 updates, new ArrayList<ShortcutInfo>(), userFinal);
2837 }
2838 }
2839 });
2840 }
Kenny Guyed131872014-04-30 03:02:21 +01002841 }
Joe Onorato36115782010-06-17 13:28:48 -04002842
Kenny Guyed131872014-04-30 03:02:21 +01002843 // Create the ApplicationInfos
2844 for (int i = 0; i < apps.size(); i++) {
2845 LauncherActivityInfoCompat app = apps.get(i);
2846 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002847 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002848 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002849
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002850 if (!user.equals(UserHandleCompat.myUserHandle())) {
2851 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
2852 if (heuristic != null) {
2853 heuristic.processUserApps(apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002854 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002855 }
Winson Chung64359a52013-07-08 17:17:08 -07002856 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002857 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002858 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2859 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002860
2861 // Post callback on main thread
2862 mHandler.post(new Runnable() {
2863 public void run() {
2864 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002865 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002866 if (callbacks != null) {
2867 callbacks.bindAllApplications(added);
2868 if (DEBUG_LOADERS) {
2869 Log.d(TAG, "bound " + added.size() + " apps in "
2870 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2871 }
2872 } else {
2873 Log.i(TAG, "not binding apps: no Launcher activity");
2874 }
2875 }
2876 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002877 // Cleanup any data stored for a deleted user.
2878 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Winson Chung64359a52013-07-08 17:17:08 -07002879
Joe Onorato36115782010-06-17 13:28:48 -04002880 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002881 Log.d(TAG, "Icons processed in "
2882 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002883 }
2884 }
2885
2886 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002887 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002888 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2889 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2890 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2891 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2892 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2893 }
Joe Onorato36115782010-06-17 13:28:48 -04002894 }
2895 }
2896
2897 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002898 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002899 }
2900
Adam Cohen091440a2015-03-18 14:16:05 -07002901 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002902
2903 @Override
2904 public void onReceive(Context context, Intent intent) {
2905 synchronized (sBgLock) {
2906 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2907 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002908 final PackageManager manager = context.getPackageManager();
2909 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2910 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002911 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2912 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002913 packagesRemoved.clear();
2914 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002915 for (String pkg : entry.getValue()) {
2916 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002917 boolean packageOnSdcard = launcherApps.isAppEnabled(
2918 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2919 if (packageOnSdcard) {
2920 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2921 packagesUnavailable.add(pkg);
2922 } else {
2923 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2924 packagesRemoved.add(pkg);
2925 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002926 }
2927 }
2928 if (!packagesRemoved.isEmpty()) {
2929 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2930 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2931 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002932 if (!packagesUnavailable.isEmpty()) {
2933 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2934 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2935 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 }
Sunny Goyal34942622014-08-29 17:20:55 -07002937 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002938 }
2939 }
2940 }
2941
Joe Onorato36115782010-06-17 13:28:48 -04002942 private class PackageUpdatedTask implements Runnable {
2943 int mOp;
2944 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002945 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002946
2947 public static final int OP_NONE = 0;
2948 public static final int OP_ADD = 1;
2949 public static final int OP_UPDATE = 2;
2950 public static final int OP_REMOVE = 3; // uninstlled
2951 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2952
2953
Kenny Guyed131872014-04-30 03:02:21 +01002954 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002955 mOp = op;
2956 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002957 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002958 }
2959
2960 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002961 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002962
2963 final String[] packages = mPackages;
2964 final int N = packages.length;
2965 switch (mOp) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002966 case OP_ADD: {
Joe Onorato36115782010-06-17 13:28:48 -04002967 for (int i=0; i<N; i++) {
2968 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002969 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002970 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002971 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002972
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002973 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2974 if (heuristic != null) {
2975 heuristic.processPackageAdd(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002976 }
Joe Onorato36115782010-06-17 13:28:48 -04002977 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002978 }
Joe Onorato36115782010-06-17 13:28:48 -04002979 case OP_UPDATE:
2980 for (int i=0; i<N; i++) {
2981 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002982 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002983 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002984 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002985 }
2986 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002987 case OP_REMOVE: {
2988 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2989 if (heuristic != null) {
2990 heuristic.processPackageRemoved(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002991 }
Joe Onorato36115782010-06-17 13:28:48 -04002992 for (int i=0; i<N; i++) {
2993 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002994 mIconCache.removeIconsForPkg(packages[i], mUser);
2995 }
2996 // Fall through
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002997 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002998 case OP_UNAVAILABLE:
2999 for (int i=0; i<N; i++) {
3000 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3001 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003002 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003003 }
3004 break;
3005 }
3006
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003007 ArrayList<AppInfo> added = null;
3008 ArrayList<AppInfo> modified = null;
3009 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003010
Adam Cohen487f7dd2012-06-28 18:12:10 -07003011 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003012 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003013 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003014 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003015 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003016 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003017 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003018 }
Winson Chung5d55f332012-07-16 20:45:03 -07003019 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003020 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003021 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003022 }
3023
Sunny Goyale0f58d72014-11-10 18:05:31 -08003024 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003025 if (callbacks == null) {
3026 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3027 return;
3028 }
3029
Sunny Goyal4390ace2014-10-13 11:33:11 -07003030 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3031 new HashMap<ComponentName, AppInfo>();
3032
Joe Onorato36115782010-06-17 13:28:48 -04003033 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003034 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003035 for (AppInfo ai : added) {
3036 addedOrUpdatedApps.put(ai.componentName, ai);
3037 }
Joe Onorato36115782010-06-17 13:28:48 -04003038 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003039
Joe Onorato36115782010-06-17 13:28:48 -04003040 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003041 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003042 for (AppInfo ai : modified) {
3043 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003044 }
3045
Joe Onorato36115782010-06-17 13:28:48 -04003046 mHandler.post(new Runnable() {
3047 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003048 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003049 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003050 callbacks.bindAppsUpdated(modifiedFinal);
3051 }
3052 }
3053 });
3054 }
Winson Chung83892cc2013-05-01 16:53:33 -07003055
Sunny Goyal4390ace2014-10-13 11:33:11 -07003056 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003057 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003058 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3059 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3060 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3061
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003062 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003063 synchronized (sBgLock) {
Sunny Goyale2df0622015-04-24 11:27:00 -07003064 for (ItemInfo info : sBgItemsIdMap) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003065 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3066 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003067 boolean infoUpdated = false;
3068 boolean shortcutUpdated = false;
3069
3070 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003071 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003072 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003073 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3074 si.iconResource.resourceName, mIconCache, context);
3075 if (icon != null) {
3076 si.setIcon(icon);
3077 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003078 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003079 }
3080 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003081
3082 ComponentName cn = si.getTargetComponent();
3083 if (cn != null && packageSet.contains(cn.getPackageName())) {
3084 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3085
3086 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003087 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3088 // Auto install icon
3089 PackageManager pm = context.getPackageManager();
3090 ResolveInfo matched = pm.resolveActivity(
3091 new Intent(Intent.ACTION_MAIN)
3092 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3093 PackageManager.MATCH_DEFAULT_ONLY);
3094 if (matched == null) {
3095 // Try to find the best match activity.
3096 Intent intent = pm.getLaunchIntentForPackage(
3097 cn.getPackageName());
3098 if (intent != null) {
3099 cn = intent.getComponent();
3100 appInfo = addedOrUpdatedApps.get(cn);
3101 }
3102
3103 if ((intent == null) || (appInfo == null)) {
3104 removedShortcuts.add(si);
3105 continue;
3106 }
3107 si.promisedIntent = intent;
3108 }
3109 }
3110
3111 // Restore the shortcut.
Sunny Goyalfa401a12015-04-10 13:45:42 -07003112 if (appInfo != null) {
3113 si.flags = appInfo.flags;
3114 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003115
Sunny Goyal756adbc2015-04-16 15:20:51 -07003116 si.intent = si.promisedIntent;
3117 si.promisedIntent = null;
3118 si.status = ShortcutInfo.DEFAULT;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003119 infoUpdated = true;
3120 si.updateIcon(mIconCache);
3121 }
3122
3123 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3124 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3125 si.updateIcon(mIconCache);
3126 si.title = appInfo.title.toString();
3127 si.contentDescription = appInfo.contentDescription;
3128 infoUpdated = true;
3129 }
3130
3131 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3132 // Since package was just updated, the target must be available now.
3133 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3134 shortcutUpdated = true;
3135 }
3136 }
3137
3138 if (infoUpdated || shortcutUpdated) {
3139 updatedShortcuts.add(si);
3140 }
3141 if (infoUpdated) {
3142 updateItemInDatabase(context, si);
3143 }
3144 } else if (info instanceof LauncherAppWidgetInfo) {
3145 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3146 if (mUser.equals(widgetInfo.user)
3147 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3148 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3149 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3150 widgets.add(widgetInfo);
3151 updateItemInDatabase(context, widgetInfo);
3152 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003153 }
3154 }
3155 }
3156
Sunny Goyal4390ace2014-10-13 11:33:11 -07003157 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3158 mHandler.post(new Runnable() {
3159
3160 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003161 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003162 if (callbacks == cb && cb != null) {
3163 callbacks.bindShortcutsChanged(
3164 updatedShortcuts, removedShortcuts, mUser);
3165 }
3166 }
3167 });
3168 if (!removedShortcuts.isEmpty()) {
3169 deleteItemsFromDatabase(context, removedShortcuts);
3170 }
3171 }
3172 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003173 mHandler.post(new Runnable() {
3174 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003175 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003176 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003177 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003178 }
3179 }
3180 });
3181 }
3182 }
3183
Winson Chungdf95eb12013-10-16 14:57:07 -07003184 final ArrayList<String> removedPackageNames =
3185 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003186 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003187 // Mark all packages in the broadcast to be removed
3188 removedPackageNames.addAll(Arrays.asList(packages));
3189 } else if (mOp == OP_UPDATE) {
3190 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003191 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003192 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003193 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003194 }
3195 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003196 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003197
Winson Chungdf95eb12013-10-16 14:57:07 -07003198 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003199 final int removeReason;
3200 if (mOp == OP_UNAVAILABLE) {
3201 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3202 } else {
3203 // Remove all the components associated with this package
3204 for (String pn : removedPackageNames) {
3205 deletePackageFromDatabase(context, pn, mUser);
3206 }
3207 // Remove all the specific components
3208 for (AppInfo a : removedApps) {
3209 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3210 deleteItemsFromDatabase(context, infos);
3211 }
3212 removeReason = 0;
3213 }
3214
Winson Chungdf95eb12013-10-16 14:57:07 -07003215 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003216 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003217 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003218 mHandler.post(new Runnable() {
3219 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003220 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003221 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003222 callbacks.bindComponentsRemoved(
3223 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003224 }
3225 }
3226 });
Joe Onoratobe386092009-11-17 17:32:16 -08003227 }
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003228 if (Build.VERSION.SDK_INT < 17) {
3229 loadAndBindWidgetsAndShortcuts(context, callbacks);
3230 }
Adam Cohen4caf2982013-08-20 18:54:31 -07003231 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003232 mHandler.post(new Runnable() {
3233 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003234 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003235 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003236 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003237 }
3238 }
3239 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003240 }
3241 }
3242
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003243 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3244 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003245 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003246 if (sBgWidgetProviders == null || refresh) {
3247 sBgWidgetProviders = new HashMap<>();
3248 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3249 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003250
Robin Lee26ace122015-03-16 19:41:43 +00003251 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3252 for (AppWidgetProviderInfo pInfo : widgets) {
3253 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3254 UserHandleCompat user = wm.getUser(info);
3255 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3256 }
3257
3258 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3259 for (CustomAppWidget widget : customWidgets) {
3260 info = new LauncherAppWidgetProviderInfo(context, widget);
3261 UserHandleCompat user = wm.getUser(info);
3262 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3263 }
Adam Cohen59400422014-03-05 18:07:04 -08003264 }
Adam Cohen59400422014-03-05 18:07:04 -08003265 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3266 }
3267 }
3268
Robin Lee26ace122015-03-16 19:41:43 +00003269 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3270 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003271 synchronized (sBgLock) {
3272 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003273 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003274 }
Robin Lee26ace122015-03-16 19:41:43 +00003275 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003276 }
3277 }
3278
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003279 public void loadAndBindWidgetsAndShortcuts(final Context context, final Callbacks callbacks) {
3280 runOnWorkerThread(new Runnable(){
3281 @Override
3282 public void run() {
3283 final ArrayList<Object> list =
3284 getSortedWidgetsAndShortcuts(context, true /* refresh */);
3285 mHandler.post(new Runnable() {
3286 @Override
3287 public void run() {
3288 Callbacks cb = getCallback();
3289 if (callbacks == cb && cb != null) {
3290 callbacks.bindPackagesUpdated(list);
3291 }
3292 }
3293 });
3294 }
3295 });
3296 }
3297
Winson Chungb745afb2015-03-02 11:51:23 -08003298 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003299 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003300 PackageManager packageManager = context.getPackageManager();
3301 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003302 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003303 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3304 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003305 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003306 return widgetsAndShortcuts;
3307 }
3308
Adam Cohen091440a2015-03-18 14:16:05 -07003309 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003310 UserHandleCompat user) {
3311 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3312 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003313 }
Adam Cohen556f6132014-01-15 15:18:08 -08003314
Kenny Guyed131872014-04-30 03:02:21 +01003315 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3316 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003317 if (cn == null) {
3318 return false;
3319 }
Kenny Guyed131872014-04-30 03:02:21 +01003320 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3321 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003322 return false;
3323 }
Kenny Guyed131872014-04-30 03:02:21 +01003324 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003325 }
3326
Adam Cohena28b78e2014-05-20 17:03:04 -07003327 public static boolean isValidPackage(Context context, String packageName,
3328 UserHandleCompat user) {
3329 if (packageName == null) {
3330 return false;
3331 }
3332 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3333 return launcherApps.isPackageEnabledForProfile(packageName, user);
3334 }
3335
Joe Onorato9c1289c2009-08-17 11:03:03 -04003336 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003337 * Make an ShortcutInfo object for a restored application or shortcut item that points
3338 * to a package that is not yet installed on the system.
3339 */
Sunny Goyal34942622014-08-29 17:20:55 -07003340 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003341 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003342 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003343 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003344 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003345
3346 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3347 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3348 if (!TextUtils.isEmpty(title)) {
3349 info.title = title;
3350 }
Sunny Goyal34942622014-08-29 17:20:55 -07003351 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3352 if (TextUtils.isEmpty(info.title)) {
3353 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3354 }
Sunny Goyal34942622014-08-29 17:20:55 -07003355 } else {
3356 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3357 }
3358
Kenny Guyc2bd8102014-06-30 12:30:31 +01003359 info.contentDescription = mUserManager.getBadgedLabelForUser(
3360 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003361 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003362 info.promisedIntent = intent;
Sunny Goyal756adbc2015-04-16 15:20:51 -07003363 info.status = promiseType;
Chris Wrenf4d08112014-01-16 18:13:56 -05003364 return info;
3365 }
3366
3367 /**
3368 * Make an Intent object for a restored application or shortcut item that points
3369 * to the market page for the item.
3370 */
Adam Cohen091440a2015-03-18 14:16:05 -07003371 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003372 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003373 return getMarketIntent(componentName.getPackageName());
3374 }
3375
3376 static Intent getMarketIntent(String packageName) {
3377 return new Intent(Intent.ACTION_VIEW)
3378 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003379 .scheme("market")
3380 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003381 .appendQueryParameter("id", packageName)
3382 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003383 }
3384
3385 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003386 * Make an ShortcutInfo object for a shortcut that is an application.
3387 *
3388 * If c is not null, then it will be used to fill in missing data like the title and icon.
3389 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003390 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003391 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003392 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003393 if (user == null) {
3394 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003395 return null;
3396 }
3397
Kenny Guyed131872014-04-30 03:02:21 +01003398 ComponentName componentName = intent.getComponent();
3399 if (componentName == null) {
3400 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3401 return null;
3402 }
3403
3404 Intent newIntent = new Intent(intent.getAction(), null);
3405 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3406 newIntent.setComponent(componentName);
3407 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003408 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003409 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3410 return null;
3411 }
3412
3413 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003414 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003415 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3416 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3417 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003418 }
3419
Joe Onorato56d82912010-03-07 14:32:10 -05003420 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003421 if (TextUtils.isEmpty(info.title) && c != null) {
3422 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003423 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003424
Joe Onorato56d82912010-03-07 14:32:10 -05003425 // fall back to the class name of the activity
3426 if (info.title == null) {
3427 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003428 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003429
Joe Onorato9c1289c2009-08-17 11:03:03 -04003430 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003431 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003432 info.contentDescription = mUserManager.getBadgedLabelForUser(
3433 info.title.toString(), info.user);
Sunny Goyalfa401a12015-04-10 13:45:42 -07003434 if (lai != null) {
3435 info.flags = AppInfo.initFlags(lai);
3436 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003437 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003438 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003439
Sunny Goyale2df0622015-04-24 11:27:00 -07003440 static ArrayList<ItemInfo> filterItemInfos(Iterable<ItemInfo> infos,
Winson Chung64359a52013-07-08 17:17:08 -07003441 ItemInfoFilter f) {
3442 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3443 for (ItemInfo i : infos) {
3444 if (i instanceof ShortcutInfo) {
3445 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003446 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003447 if (cn != null && f.filterItem(null, info, cn)) {
3448 filtered.add(info);
3449 }
3450 } else if (i instanceof FolderInfo) {
3451 FolderInfo info = (FolderInfo) i;
3452 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003453 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003454 if (cn != null && f.filterItem(info, s, cn)) {
3455 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003456 }
3457 }
Winson Chung64359a52013-07-08 17:17:08 -07003458 } else if (i instanceof LauncherAppWidgetInfo) {
3459 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3460 ComponentName cn = info.providerName;
3461 if (cn != null && f.filterItem(null, info, cn)) {
3462 filtered.add(info);
3463 }
Winson Chung8a435102012-08-30 17:16:53 -07003464 }
3465 }
Winson Chung64359a52013-07-08 17:17:08 -07003466 return new ArrayList<ItemInfo>(filtered);
3467 }
3468
Adam Cohen091440a2015-03-18 14:16:05 -07003469 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003470 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003471 ItemInfoFilter filter = new ItemInfoFilter() {
3472 @Override
3473 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003474 if (info.user == null) {
3475 return cn.equals(cname);
3476 } else {
3477 return cn.equals(cname) && info.user.equals(user);
3478 }
Winson Chung64359a52013-07-08 17:17:08 -07003479 }
3480 };
Sunny Goyale2df0622015-04-24 11:27:00 -07003481 return filterItemInfos(sBgItemsIdMap, filter);
Winson Chung64359a52013-07-08 17:17:08 -07003482 }
3483
Sunny Goyal1a745e82014-10-02 15:58:31 -07003484 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003485 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003486 */
Adam Cohen091440a2015-03-18 14:16:05 -07003487 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003488 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3489 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003490
Joe Onorato56d82912010-03-07 14:32:10 -05003491 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003492 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003493 // Non-app shortcuts are only supported for current user.
3494 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003495 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003496
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003497 // TODO: If there's an explicit component and we can't install that, delete it.
3498
Joe Onorato56d82912010-03-07 14:32:10 -05003499 info.title = c.getString(titleIndex);
3500
Joe Onorato9c1289c2009-08-17 11:03:03 -04003501 int iconType = c.getInt(iconTypeIndex);
3502 switch (iconType) {
3503 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3504 String packageName = c.getString(iconPackageIndex);
3505 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003506 info.customIcon = false;
3507 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003508 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003509 // the db
3510 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003511 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003512 }
3513 // the fallback icon
3514 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003515 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003516 info.usingFallbackIcon = true;
3517 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003518 break;
3519 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003520 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003521 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003522 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003523 info.customIcon = false;
3524 info.usingFallbackIcon = true;
3525 } else {
3526 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003527 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003528 break;
3529 default:
Kenny Guyed131872014-04-30 03:02:21 +01003530 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003531 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003532 info.customIcon = false;
3533 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003534 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003535 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003536 return info;
3537 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003538
Sunny Goyal2350bc92014-10-14 16:42:54 -07003539 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003540 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3541 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3542 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3543
Adam Cohend9198822011-11-22 16:42:47 -08003544 if (intent == null) {
3545 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3546 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3547 return null;
3548 }
3549
Joe Onorato0589f0f2010-02-08 13:44:00 -08003550 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003551 boolean customIcon = false;
3552 ShortcutIconResource iconResource = null;
3553
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003554 if (bitmap instanceof Bitmap) {
3555 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003556 customIcon = true;
3557 } else {
3558 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003559 if (extra instanceof ShortcutIconResource) {
3560 iconResource = (ShortcutIconResource) extra;
3561 icon = Utilities.createIconBitmap(iconResource.packageName,
3562 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003563 }
3564 }
3565
Michael Jurkac9d95c52011-08-29 14:03:34 -07003566 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003567
Kenny Guyed131872014-04-30 03:02:21 +01003568 // Only support intents for current user for now. Intents sent from other
3569 // users wouldn't get here without intent forwarding anyway.
3570 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003571 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003572 icon = mIconCache.getDefaultIcon(info.user);
3573 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003574 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003575 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003576
Joe Onorato0589f0f2010-02-08 13:44:00 -08003577 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003578 info.contentDescription = mUserManager.getBadgedLabelForUser(
3579 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003580 info.intent = intent;
3581 info.customIcon = customIcon;
3582 info.iconResource = iconResource;
3583
3584 return info;
3585 }
3586
Joe Onorato9c1289c2009-08-17 11:03:03 -04003587 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003588 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003589 * or make a new one.
3590 */
Sunny Goyale2df0622015-04-24 11:27:00 -07003591 @Thunk static FolderInfo findOrMakeFolder(LongArrayMap<FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003592 // See if a placeholder was created for us already
3593 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003594 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003595 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003596 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003597 folders.put(id, folderInfo);
3598 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003599 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003600 }
3601
Winson Chung1ed747a2011-05-03 16:18:34 -07003602 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003603 private final AppWidgetManagerCompat mManager;
3604 private final PackageManager mPackageManager;
3605 private final HashMap<Object, String> mLabelCache;
3606 private final Collator mCollator;
3607
Hyunyoung Song3f471442015-04-08 19:01:34 -07003608 public WidgetAndShortcutNameComparator(Context context) {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003609 mManager = AppWidgetManagerCompat.getInstance(context);
3610 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003611 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003612 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003613 }
3614 public final int compare(Object a, Object b) {
3615 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003616 if (mLabelCache.containsKey(a)) {
3617 labelA = mLabelCache.get(a);
3618 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003619 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3620 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003621 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003622 mLabelCache.put(a, labelA);
3623 }
3624 if (mLabelCache.containsKey(b)) {
3625 labelB = mLabelCache.get(b);
3626 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003627 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003628 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003629 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003630 mLabelCache.put(b, labelB);
3631 }
Winson Chung11904872012-09-17 16:58:46 -07003632 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003633 }
3634 };
Joe Onoratobe386092009-11-17 17:32:16 -08003635
Sunny Goyal651077b2014-06-30 14:15:31 -07003636 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3637 return (provider != null) && (provider.provider != null)
3638 && (provider.provider.getPackageName() != null);
3639 }
3640
Joe Onoratobe386092009-11-17 17:32:16 -08003641 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003642 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003643 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3644 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3645 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3646 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003647 if (mLoaderTask != null) {
3648 mLoaderTask.dumpState();
3649 } else {
3650 Log.d(TAG, "mLoaderTask=null");
3651 }
Joe Onoratobe386092009-11-17 17:32:16 -08003652 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003653
3654 public Callbacks getCallback() {
3655 return mCallbacks != null ? mCallbacks.get() : null;
3656 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07003657
3658 /**
3659 * @return {@link FolderInfo} if its already loaded.
3660 */
3661 public FolderInfo findFolderById(Long folderId) {
3662 synchronized (sBgLock) {
3663 return sBgFolders.get(folderId);
3664 }
3665 }
Sunny Goyal756adbc2015-04-16 15:20:51 -07003666
3667 /**
3668 * @return the looper for the worker thread which can be used to start background tasks.
3669 */
3670 public static Looper getWorkerLooper() {
3671 return sWorkerThread.getLooper();
3672 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003673}