blob: 8cedcc5723889f16c41626e8f0c369ec7aa47aa9 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Robin Lee26ace122015-03-16 19:41:43 +000061import com.android.launcher3.util.ComponentKey;
Adam Cohen091440a2015-03-18 14:16:05 -070062import com.android.launcher3.util.Thunk;
Romain Guyedcce092010-03-04 13:03:17 -080063
Michael Jurkac2f801e2011-07-12 14:19:46 -070064import java.lang.ref.WeakReference;
65import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070066import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070067import java.text.Collator;
68import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070069import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070070import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070071import java.util.Collections;
72import java.util.Comparator;
73import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070074import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070075import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070076import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070077import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070078import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080/**
81 * Maintains in-memory state of the Launcher. It is expected that there should be only one
82 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070083 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 */
Kenny Guyed131872014-04-30 03:02:21 +010085public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010086 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040088 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070089 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080090 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040091
Joe Onorato9c1289c2009-08-17 11:03:03 -040092 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070093
Dan Sandlerd5024042014-01-09 15:01:33 -050094 public static final int LOADER_FLAG_NONE = 0;
95 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
96 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
97
Joe Onorato36115782010-06-17 13:28:48 -040098 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050099 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800100
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800102 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400103
Adam Cohen091440a2015-03-18 14:16:05 -0700104 @Thunk final LauncherAppState mApp;
105 @Thunk final Object mLock = new Object();
106 @Thunk DeferredHandler mHandler = new DeferredHandler();
107 @Thunk LoaderTask mLoaderTask;
108 @Thunk boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Sunny Goyale0f58d72014-11-10 18:05:31 -0800110 /**
111 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
112 */
113 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
114
Winson Chung81b52252012-08-27 15:34:29 -0700115 // Specific runnable types that are run on the main thread deferred handler, this allows us to
116 // clear all queued binding runnables when the Launcher activity is destroyed.
117 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
118 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
119
Jason Monkbbe1e242014-05-16 17:37:34 -0400120 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700121
Adam Cohen091440a2015-03-18 14:16:05 -0700122 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700123 static {
124 sWorkerThread.start();
125 }
Adam Cohen091440a2015-03-18 14:16:05 -0700126 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700127
Joe Onoratocc67f472010-06-08 10:54:30 -0700128 // We start off with everything not loaded. After that, we assume that
129 // our monitoring of the package manager provides all updates and we never
130 // need to do a requery. These are only ever touched from the loader thread.
Adam Cohen091440a2015-03-18 14:16:05 -0700131 @Thunk boolean mWorkspaceLoaded;
132 @Thunk boolean mAllAppsLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700133
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700134 // When we are loading pages synchronously, we can't just post the binding of items on the side
135 // pages as this delays the rotation process. Instead, we wait for a callback from the first
136 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
137 // a normal load, we also clear this set of Runnables.
138 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
139
Adam Cohen091440a2015-03-18 14:16:05 -0700140 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700142 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700143 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800144
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145 // The lock that must be acquired before referencing any static bg data structures. Unlike
146 // other locks, this one can generally be held long-term because we never expect any of these
147 // static data structures to be referenced outside of the worker thread except on the first
148 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700149 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
156 // created by LauncherModel that are directly on the home screen (however, no widgets or
157 // shortcuts within folders).
158 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159
Adam Cohen487f7dd2012-06-28 18:12:10 -0700160 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
161 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 new ArrayList<LauncherAppWidgetInfo>();
163
Adam Cohen487f7dd2012-06-28 18:12:10 -0700164 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
165 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700166
Adam Cohendcd297f2013-06-18 13:13:40 -0700167 // sBgWorkspaceScreens is the ordered set of workspace screens.
168 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
169
Adam Cohen59400422014-03-05 18:07:04 -0800170 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000171 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800172
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700173 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700174 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
175 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700176
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 // </ only access in worker thread >
178
Adam Cohen091440a2015-03-18 14:16:05 -0700179 @Thunk IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180
Reena Lee99a73f32011-10-24 17:27:37 -0700181 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700182
Adam Cohen091440a2015-03-18 14:16:05 -0700183 @Thunk final LauncherAppsCompat mLauncherApps;
184 @Thunk final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100185
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700187 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400188 public int getCurrentWorkspaceScreen();
189 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700190 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
191 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700192 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700193 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500194 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800195 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400196 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200197 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700198 public void bindAppsAdded(ArrayList<Long> newScreens,
199 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700200 ArrayList<ItemInfo> addAnimated,
201 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200202 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700203 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
204 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
205 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700206 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700207 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700208 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700209 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200210 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100211 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700212 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700213 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700214 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800215 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
216 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400217 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218
Winson Chung64359a52013-07-08 17:17:08 -0700219 public interface ItemInfoFilter {
220 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
221 }
222
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800223 public interface ScreenPosProvider {
224 int getScreenIndex(ArrayList<Long> screenIDs);
225 }
226
Bjorn Bringert1307f632013-10-03 22:31:03 +0100227 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800228 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400229
Winson Chungee055712013-07-30 14:46:24 -0700230 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700231 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400232 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
233 // resource string.
234 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
235 ProviderInfo providerInfo =
236 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
237 ProviderInfo redirectProvider =
238 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700239
240 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400241 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700242
243 if (mOldContentProviderExists) {
244 Log.d(TAG, "Old launcher provider exists.");
245 } else {
246 Log.d(TAG, "Old launcher provider does not exist.");
247 }
248
Daniel Sandlere4f98912013-06-25 15:13:26 -0400249 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100250 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800251 mIconCache = iconCache;
252
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400253 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700254 Configuration config = res.getConfiguration();
255 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100256 mLauncherApps = LauncherAppsCompat.getInstance(context);
257 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800258 }
259
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700260 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
261 * posted on the main thread handler. */
Adam Cohen091440a2015-03-18 14:16:05 -0700262 @Thunk void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700263 runOnMainThread(r, 0);
264 }
Adam Cohen091440a2015-03-18 14:16:05 -0700265 @Thunk void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700266 if (sWorkerThread.getThreadId() == Process.myTid()) {
267 // If we are on the worker thread, post onto the main handler
268 mHandler.post(r);
269 } else {
270 r.run();
271 }
272 }
273
274 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
275 * posted on the worker thread handler. */
276 private static void runOnWorkerThread(Runnable r) {
277 if (sWorkerThread.getThreadId() == Process.myTid()) {
278 r.run();
279 } else {
280 // If we are not on the worker thread, then post to the worker handler
281 sWorker.post(r);
282 }
283 }
284
Winson Chunge43a1e72014-01-15 10:33:02 -0800285 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
286 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800287 }
288
Sunny Goyale755d462014-07-22 13:48:29 -0700289 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500290 // Process the updated package state
291 Runnable r = new Runnable() {
292 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800293 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500294 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700295 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500296 }
297 }
298 };
299 mHandler.post(r);
300 }
301
Sunny Goyala22666f2014-09-18 13:25:15 -0700302 public void updatePackageBadge(final String packageName) {
303 // Process the updated package badge
304 Runnable r = new Runnable() {
305 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800306 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700307 if (callbacks != null) {
308 callbacks.updatePackageBadge(packageName);
309 }
310 }
311 };
312 mHandler.post(r);
313 }
314
Adam Cohen76a47a12014-02-05 11:47:43 -0800315 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800316 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800317
318 if (allAppsApps == null) {
319 throw new RuntimeException("allAppsApps must not be null");
320 }
321 if (allAppsApps.isEmpty()) {
322 return;
323 }
324
325 // Process the newly added applications and add them to the database first
326 Runnable r = new Runnable() {
327 public void run() {
328 runOnMainThread(new Runnable() {
329 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800330 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800331 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500332 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800333 }
334 }
335 });
336 }
337 };
338 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700339 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800340
341 public void addAndBindAddedWorkspaceApps(final Context context,
342 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800343 addAndBindAddedWorkspaceApps(context, workspaceApps,
344 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800345
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800346 @Override
347 public int getScreenIndex(ArrayList<Long> screenIDs) {
348 return screenIDs.isEmpty() ? 0 : 1;
349 }
350 }, 1, false);
351 }
352
353 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
354 int[] xy, int spanX, int spanY) {
355 LauncherAppState app = LauncherAppState.getInstance();
356 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
357 final int xCount = (int) grid.numColumns;
358 final int yCount = (int) grid.numRows;
359 boolean[][] occupied = new boolean[xCount][yCount];
360 if (occupiedPos != null) {
361 for (Rect r : occupiedPos) {
362 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
363 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
364 occupied[x][y] = true;
365 }
366 }
367 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800368 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800369 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
370 }
371
372 /**
373 * Find a position on the screen for the given size or adds a new screen.
374 * @return screenId and the coordinates for the item.
375 */
Adam Cohen091440a2015-03-18 14:16:05 -0700376 @Thunk static Pair<Long, int[]> findSpaceForItem(
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800377 Context context,
378 ScreenPosProvider preferredScreen,
379 int fallbackStartScreen,
380 ArrayList<Long> workspaceScreens,
381 ArrayList<Long> addedWorkspaceScreensFinal,
382 int spanX, int spanY) {
383 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
384 // loadWorkspace() may not have been called.
385 final ContentResolver cr = context.getContentResolver();
386 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
387 new String[] {
388 LauncherSettings.Favorites.SCREEN,
389 LauncherSettings.Favorites.CELLX,
390 LauncherSettings.Favorites.CELLY,
391 LauncherSettings.Favorites.SPANX,
392 LauncherSettings.Favorites.SPANY,
393 LauncherSettings.Favorites.CONTAINER
394 },
395 "container=?",
396 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
397 null);
398
399 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
400 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
401 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
402 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
403 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
404 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
405 try {
406 while (c.moveToNext()) {
407 Rect rect = new Rect();
408 rect.left = c.getInt(cellXIndex);
409 rect.top = c.getInt(cellYIndex);
410 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
411 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
412
413 long screenId = c.getInt(screenIndex);
414 ArrayList<Rect> items = screenItems.get(screenId);
415 if (items == null) {
416 items = new ArrayList<Rect>();
417 screenItems.put(screenId, items);
418 }
419 items.add(rect);
420 }
421 } catch (Exception e) {
422 screenItems.clear();
423 } finally {
424 c.close();
425 }
426
427 // Find appropriate space for the item.
428 long screenId = 0;
429 int[] cordinates = new int[2];
430 boolean found = false;
431
432 int screenCount = workspaceScreens.size();
433 // First check the preferred screen.
434 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
435 if (preferredScreenIndex < screenCount) {
436 screenId = workspaceScreens.get(preferredScreenIndex);
437 found = findNextAvailableIconSpaceInScreen(
438 screenItems.get(screenId), cordinates, spanX, spanY);
439 }
440
441 if (!found) {
442 // Search on any of the screens.
443 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
444 screenId = workspaceScreens.get(screen);
445 if (findNextAvailableIconSpaceInScreen(
446 screenItems.get(screenId), cordinates, spanX, spanY)) {
447 // We found a space for it
448 found = true;
449 break;
450 }
451 }
452 }
453
454 if (!found) {
455 // Still no position found. Add a new screen to the end.
456 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
457
458 // Save the screen id for binding in the workspace
459 workspaceScreens.add(screenId);
460 addedWorkspaceScreensFinal.add(screenId);
461
462 // If we still can't find an empty space, then God help us all!!!
463 if (!findNextAvailableIconSpaceInScreen(
464 screenItems.get(screenId), cordinates, spanX, spanY)) {
465 throw new RuntimeException("Can't find space to add the item");
466 }
467 }
468 return Pair.create(screenId, cordinates);
469 }
470
471 /**
472 * Adds the provided items to the workspace.
473 * @param preferredScreen the screen where we should try to add the app first
474 * @param fallbackStartScreen the screen to start search for empty space if
475 * preferredScreen is not available.
476 */
477 public void addAndBindPendingItem(
478 final Context context,
479 final PendingAddItemInfo addInfo,
480 final ScreenPosProvider preferredScreen,
481 final int fallbackStartScreen) {
482 final Callbacks callbacks = getCallback();
483 // Process the newly added applications and add them to the database first
484 Runnable r = new Runnable() {
485 public void run() {
486 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800487 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800488
489 // Find appropriate space for the item.
490 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
491 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
492 addInfo.spanX,
493 addInfo.spanY);
494 final long screenId = coords.first;
495 final int[] cordinates = coords.second;
496
497 // Update the workspace screens
498 updateWorkspaceScreenOrder(context, workspaceScreens);
499 runOnMainThread(new Runnable() {
500 public void run() {
501 Callbacks cb = getCallback();
502 if (callbacks == cb && cb != null) {
503 cb.bindAddScreens(addedWorkspaceScreensFinal);
504 cb.bindAddPendingItem(addInfo,
505 LauncherSettings.Favorites.CONTAINER_DESKTOP,
506 screenId, cordinates, addInfo.spanX, addInfo.spanY);
507 }
508 }
509 });
510 }
511 };
512 runOnWorkerThread(r);
513 }
514
515 /**
516 * Adds the provided items to the workspace.
517 * @param preferredScreen the screen where we should try to add the app first
518 * @param fallbackStartScreen the screen to start search for empty space if
519 * preferredScreen is not available.
520 */
521 public void addAndBindAddedWorkspaceApps(final Context context,
522 final ArrayList<ItemInfo> workspaceApps,
523 final ScreenPosProvider preferredScreen,
524 final int fallbackStartScreen,
525 final boolean allowDuplicate) {
526 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800527 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700528 return;
Winson Chung997a9232013-07-24 15:33:46 -0700529 }
Winson Chung64359a52013-07-08 17:17:08 -0700530 // Process the newly added applications and add them to the database first
531 Runnable r = new Runnable() {
532 public void run() {
533 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
534 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
535
Winson Chung76828c82013-08-19 15:43:29 -0700536 // Get the list of workspace screens. We need to append to this list and
537 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
538 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800539 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700540 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800541 for (ItemInfo item : workspaceApps) {
542 if (!allowDuplicate) {
543 // Short-circuit this logic if the icon exists somewhere on the workspace
544 if (shortcutExists(context, item.title.toString(),
545 item.getIntent(), item.user)) {
546 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700547 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800548 }
Winson Chung76828c82013-08-19 15:43:29 -0700549
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800550 // Find appropriate space for the item.
551 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
552 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
553 1, 1);
554 long screenId = coords.first;
555 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700556
Winson Chung997a9232013-07-24 15:33:46 -0700557 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800558 if (item instanceof ShortcutInfo) {
559 shortcutInfo = (ShortcutInfo) item;
560 } else if (item instanceof AppInfo) {
561 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700562 } else {
563 throw new RuntimeException("Unexpected info type");
564 }
Winson Chung94d67682013-09-25 16:29:40 -0700565
Winson Chung64359a52013-07-08 17:17:08 -0700566 // Add the shortcut to the db
567 addItemToDatabase(context, shortcutInfo,
568 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800569 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700570 // Save the ShortcutInfo for binding in the workspace
571 addedShortcutsFinal.add(shortcutInfo);
572 }
573 }
574
Winson Chung76828c82013-08-19 15:43:29 -0700575 // Update the workspace screens
576 updateWorkspaceScreenOrder(context, workspaceScreens);
577
Adam Cohen76a47a12014-02-05 11:47:43 -0800578 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700579 runOnMainThread(new Runnable() {
580 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800581 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700582 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700583 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
584 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700585 if (!addedShortcutsFinal.isEmpty()) {
586 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
587 long lastScreenId = info.screenId;
588 for (ItemInfo i : addedShortcutsFinal) {
589 if (i.screenId == lastScreenId) {
590 addAnimated.add(i);
591 } else {
592 addNotAnimated.add(i);
593 }
Winson Chung997a9232013-07-24 15:33:46 -0700594 }
595 }
Winson Chungd64d1762013-08-20 14:37:16 -0700596 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800597 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700598 }
Winson Chung64359a52013-07-08 17:17:08 -0700599 }
Winson Chung997a9232013-07-24 15:33:46 -0700600 });
601 }
Winson Chung64359a52013-07-08 17:17:08 -0700602 }
603 };
604 runOnWorkerThread(r);
605 }
606
Winson Chung81b52252012-08-27 15:34:29 -0700607 public void unbindItemInfosAndClearQueuedBindRunnables() {
608 if (sWorkerThread.getThreadId() == Process.myTid()) {
609 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
610 "main thread");
611 }
612
613 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400614 synchronized (mDeferredBindRunnables) {
615 mDeferredBindRunnables.clear();
616 }
Winson Chung81b52252012-08-27 15:34:29 -0700617 // Remove any queued bind runnables
618 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
619 // Unbind all the workspace items
620 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700621 }
622
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700623 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700624 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700625 // Ensure that we don't use the same workspace items data structure on the main thread
626 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700627 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
628 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700629 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700630 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
631 tmpAppWidgets.addAll(sBgAppWidgets);
632 }
633 Runnable r = new Runnable() {
634 @Override
635 public void run() {
636 for (ItemInfo item : tmpWorkspaceItems) {
637 item.unbind();
638 }
639 for (ItemInfo item : tmpAppWidgets) {
640 item.unbind();
641 }
642 }
643 };
644 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700645 }
646
Joe Onorato9c1289c2009-08-17 11:03:03 -0400647 /**
648 * Adds an item to the DB if it was not created previously, or move it to a new
649 * <container, screen, cellX, cellY>
650 */
651 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700652 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400653 if (item.container == ItemInfo.NO_ID) {
654 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700655 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400656 } else {
657 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800659 }
660 }
661
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700662 static void checkItemInfoLocked(
663 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
664 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
665 if (modelItem != null && item != modelItem) {
666 // check all the data is consistent
667 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
668 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
669 ShortcutInfo shortcut = (ShortcutInfo) item;
670 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
671 modelShortcut.intent.filterEquals(shortcut.intent) &&
672 modelShortcut.id == shortcut.id &&
673 modelShortcut.itemType == shortcut.itemType &&
674 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700675 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700676 modelShortcut.cellX == shortcut.cellX &&
677 modelShortcut.cellY == shortcut.cellY &&
678 modelShortcut.spanX == shortcut.spanX &&
679 modelShortcut.spanY == shortcut.spanY &&
680 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
681 (modelShortcut.dropPos != null &&
682 shortcut.dropPos != null &&
683 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
684 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
685 // For all intents and purposes, this is the same object
686 return;
687 }
688 }
689
690 // the modelItem needs to match up perfectly with item if our model is
691 // to be consistent with the database-- for now, just require
692 // modelItem == item or the equality check above
693 String msg = "item: " + ((item != null) ? item.toString() : "null") +
694 "modelItem: " +
695 ((modelItem != null) ? modelItem.toString() : "null") +
696 "Error: ItemInfo passed to checkItemInfo doesn't match original";
697 RuntimeException e = new RuntimeException(msg);
698 if (stackTrace != null) {
699 e.setStackTrace(stackTrace);
700 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800701 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700702 }
703 }
704
Michael Jurka816474f2012-06-25 14:49:02 -0700705 static void checkItemInfo(final ItemInfo item) {
706 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
707 final long itemId = item.id;
708 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700709 public void run() {
710 synchronized (sBgLock) {
711 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700712 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700713 }
714 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700715 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700716 }
717
Michael Jurkac9d95c52011-08-29 14:03:34 -0700718 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
719 final ItemInfo item, final String callingFunction) {
720 final long itemId = item.id;
721 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
722 final ContentResolver cr = context.getContentResolver();
723
Adam Cohen487f7dd2012-06-28 18:12:10 -0700724 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700725 Runnable r = new Runnable() {
726 public void run() {
727 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700728 updateItemArrays(item, itemId, stackTrace);
729 }
730 };
731 runOnWorkerThread(r);
732 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700733
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700734 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
735 final ArrayList<ItemInfo> items, final String callingFunction) {
736 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700737
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700738 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
739 Runnable r = new Runnable() {
740 public void run() {
741 ArrayList<ContentProviderOperation> ops =
742 new ArrayList<ContentProviderOperation>();
743 int count = items.size();
744 for (int i = 0; i < count; i++) {
745 ItemInfo item = items.get(i);
746 final long itemId = item.id;
747 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
748 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700749
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700750 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
751 updateItemArrays(item, itemId, stackTrace);
752
753 }
754 try {
755 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
756 } catch (Exception e) {
757 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700758 }
759 }
760 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700761 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700762 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700763
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700764 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
765 // Lock on mBgLock *after* the db operation
766 synchronized (sBgLock) {
767 checkItemInfoLocked(itemId, item, stackTrace);
768
769 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
770 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
771 // Item is in a folder, make sure this folder exists
772 if (!sBgFolders.containsKey(item.container)) {
773 // An items container is being set to a that of an item which is not in
774 // the list of Folders.
775 String msg = "item: " + item + " container being set to: " +
776 item.container + ", not in the list of folders";
777 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700778 }
779 }
780
781 // Items are added/removed from the corresponding FolderInfo elsewhere, such
782 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
783 // that are on the desktop, as appropriate
784 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800785 if (modelItem != null &&
786 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
787 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700788 switch (modelItem.itemType) {
789 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
790 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
791 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
792 if (!sBgWorkspaceItems.contains(modelItem)) {
793 sBgWorkspaceItems.add(modelItem);
794 }
795 break;
796 default:
797 break;
798 }
799 } else {
800 sBgWorkspaceItems.remove(modelItem);
801 }
802 }
803 }
804
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800805 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700807 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700808 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700809 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400811 item.cellX = cellX;
812 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700813
Winson Chung3d503fb2011-07-13 17:25:49 -0700814 // We store hotseat items in canonical form which is this orientation invariant position
815 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700817 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700818 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700819 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700821 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400822
823 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400824 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700825 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
826 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800827 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400829
Michael Jurkac9d95c52011-08-29 14:03:34 -0700830 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700831 }
832
833 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700834 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
835 * cellX, cellY have already been updated on the ItemInfos.
836 */
837 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
838 final long container, final int screen) {
839
840 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
841 int count = items.size();
842
843 for (int i = 0; i < count; i++) {
844 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700845 item.container = container;
846
847 // We store hotseat items in canonical form which is this orientation invariant position
848 // in the hotseat
849 if (context instanceof Launcher && screen < 0 &&
850 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700851 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700852 item.cellY);
853 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700855 }
856
857 final ContentValues values = new ContentValues();
858 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
859 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 Cohendcd297f2013-06-18 13:13:40 -0700862 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700863
864 contentValues.add(values);
865 }
866 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
867 }
868
869 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700870 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800871 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700872 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700873 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700874 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800875 item.cellX = cellX;
876 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700877 item.spanX = spanX;
878 item.spanY = spanY;
879
880 // We store hotseat items in canonical form which is this orientation invariant position
881 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700882 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700884 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700885 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700886 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700887 }
Adam Cohend4844c32011-02-18 19:25:06 -0800888
Adam Cohend4844c32011-02-18 19:25:06 -0800889 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800890 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700891 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
892 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800893 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700894 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
895 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700896 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800897
Michael Jurka816474f2012-06-25 14:49:02 -0700898 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700899 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700900
901 /**
902 * Update an item to the database in a specified container.
903 */
904 static void updateItemInDatabase(Context context, final ItemInfo item) {
905 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100906 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700907 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800908 }
909
910 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400911 * Returns true if the shortcuts already exists in the database.
912 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800913 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800914 static boolean shortcutExists(Context context, String title, Intent intent,
915 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400916 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700917 final Intent intentWithPkg, intentWithoutPkg;
918
919 if (intent.getComponent() != null) {
920 // If component is not null, an intent with null package will produce
921 // the same result and should also be a match.
922 if (intent.getPackage() != null) {
923 intentWithPkg = intent;
924 intentWithoutPkg = new Intent(intent).setPackage(null);
925 } else {
926 intentWithPkg = new Intent(intent).setPackage(
927 intent.getComponent().getPackageName());
928 intentWithoutPkg = intent;
929 }
930 } else {
931 intentWithPkg = intent;
932 intentWithoutPkg = intent;
933 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800934 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
935 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400936 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800937 new String[] { "title", "intent", "profileId" },
938 "title=? and (intent=? or intent=?) and profileId=?",
939 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
940 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400941 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800942 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400943 } finally {
944 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700946 }
947
Joe Onorato9c1289c2009-08-17 11:03:03 -0400948 /**
949 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
950 */
951 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
952 final ContentResolver cr = context.getContentResolver();
953 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
954 "_id=? and (itemType=? or itemType=?)",
955 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700956 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700957
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 try {
959 if (c.moveToFirst()) {
960 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
961 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
962 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
963 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
964 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
965 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700966 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800967
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968 FolderInfo folderInfo = null;
969 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700970 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
971 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400972 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700973 }
974
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975 folderInfo.title = c.getString(titleIndex);
976 folderInfo.id = id;
977 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700978 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700979 folderInfo.cellX = c.getInt(cellXIndex);
980 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700981 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982
983 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700984 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 } finally {
986 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700987 }
988
989 return null;
990 }
991
Joe Onorato9c1289c2009-08-17 11:03:03 -0400992 /**
993 * Add an item to the database in a specified container. Sets the container, screen, cellX and
994 * cellY fields of the item. Also assigns an ID to the item.
995 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700996 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700997 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999 item.cellX = cellX;
1000 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 // We store hotseat items in canonical form which is this orientation invariant position
1002 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001006 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001008 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
1010 final ContentValues values = new ContentValues();
1011 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001012 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013
Michael Jurka414300a2013-08-27 15:42:35 +02001014 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001016
Jason Monk8e19cf22014-03-20 15:06:57 -04001017 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001018 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001019 public void run() {
1020 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1021 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001022
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001023 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001024 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001025 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001026 sBgItemsIdMap.put(item.id, item);
1027 switch (item.itemType) {
1028 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1029 sBgFolders.put(item.id, (FolderInfo) item);
1030 // Fall through
1031 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1032 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1033 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1034 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1035 sBgWorkspaceItems.add(item);
1036 } else {
1037 if (!sBgFolders.containsKey(item.container)) {
1038 // Adding an item to a folder that doesn't exist.
1039 String msg = "adding item: " + item + " to a folder that " +
1040 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001041 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001043 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001044 break;
1045 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1046 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1047 break;
1048 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001049 }
1050 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001051 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001052 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001053 }
1054
Joe Onorato9c1289c2009-08-17 11:03:03 -04001055 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001056 * Creates a new unique child id, for a given cell span across all layouts.
1057 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001058 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001059 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001060 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001061 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001062 }
1063
Sunny Goyal34942622014-08-29 17:20:55 -07001064 private static ArrayList<ItemInfo> getItemsByPackageName(
1065 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001066 ItemInfoFilter filter = new ItemInfoFilter() {
1067 @Override
1068 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1069 return cn.getPackageName().equals(pn) && info.user.equals(user);
1070 }
1071 };
Sunny Goyal34942622014-08-29 17:20:55 -07001072 return filterItemInfos(sBgItemsIdMap.values(), filter);
1073 }
1074
1075 /**
1076 * Removes all the items from the database corresponding to the specified package.
1077 */
1078 static void deletePackageFromDatabase(Context context, final String pn,
1079 final UserHandleCompat user) {
1080 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001081 }
1082
1083 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001084 * Removes the specified item from the database
1085 * @param context
1086 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001087 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001088 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001089 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1090 items.add(item);
1091 deleteItemsFromDatabase(context, items);
1092 }
1093
1094 /**
1095 * Removes the specified items from the database
1096 * @param context
1097 * @param item
1098 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001099 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001100 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001101
Michael Jurka83df1882011-08-31 20:59:26 -07001102 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001103 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001104 for (ItemInfo item : items) {
1105 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1106 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001107
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001108 // Lock on mBgLock *after* the db operation
1109 synchronized (sBgLock) {
1110 switch (item.itemType) {
1111 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1112 sBgFolders.remove(item.id);
1113 for (ItemInfo info: sBgItemsIdMap.values()) {
1114 if (info.container == item.id) {
1115 // We are deleting a folder which still contains items that
1116 // think they are contained by that folder.
1117 String msg = "deleting a folder (" + item + ") which still " +
1118 "contains items (" + info + ")";
1119 Log.e(TAG, msg);
1120 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001122 sBgWorkspaceItems.remove(item);
1123 break;
1124 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1125 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1126 sBgWorkspaceItems.remove(item);
1127 break;
1128 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1129 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1130 break;
1131 }
1132 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001133 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001134 }
1135 }
Michael Jurka83df1882011-08-31 20:59:26 -07001136 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001137 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001138 }
1139
1140 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001141 * Update the order of the workspace screens in the database. The array list contains
1142 * a list of screen ids in the order that they should appear.
1143 */
Winson Chungc9168342013-06-26 14:54:55 -07001144 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001145 // Log to disk
1146 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1147 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1148
Winson Chung64359a52013-07-08 17:17:08 -07001149 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 final ContentResolver cr = context.getContentResolver();
1151 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1152
1153 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001154 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 while (iter.hasNext()) {
1156 long id = iter.next();
1157 if (id < 0) {
1158 iter.remove();
1159 }
1160 }
1161
1162 Runnable r = new Runnable() {
1163 @Override
1164 public void run() {
Yura085c8532014-02-11 15:15:29 +00001165 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001167 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001168 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 for (int i = 0; i < count; i++) {
1170 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001171 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1173 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001174 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001175 }
Yura085c8532014-02-11 15:15:29 +00001176
1177 try {
1178 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1179 } catch (Exception ex) {
1180 throw new RuntimeException(ex);
1181 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001182
Winson Chungba9c37f2013-08-30 14:11:37 -07001183 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001184 sBgWorkspaceScreens.clear();
1185 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001186 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001187 }
1188 };
1189 runOnWorkerThread(r);
1190 }
1191
1192 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193 * Remove the contents of the specified folder from the database
1194 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001195 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196 final ContentResolver cr = context.getContentResolver();
1197
Michael Jurkac9d95c52011-08-29 14:03:34 -07001198 Runnable r = new Runnable() {
1199 public void run() {
1200 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001202 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 sBgItemsIdMap.remove(info.id);
1204 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 sBgWorkspaceItems.remove(info);
1206 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001207
Michael Jurkac9d95c52011-08-29 14:03:34 -07001208 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1209 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001211 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001212 for (ItemInfo childInfo : info.contents) {
1213 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001215 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001216 }
1217 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001219 }
1220
1221 /**
1222 * Set this as the current Launcher activity object for the loader.
1223 */
1224 public void initialize(Callbacks callbacks) {
1225 synchronized (mLock) {
1226 mCallbacks = new WeakReference<Callbacks>(callbacks);
1227 }
1228 }
1229
Kenny Guyed131872014-04-30 03:02:21 +01001230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_UPDATE;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001239 int op = PackageUpdatedTask.OP_REMOVE;
1240 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1241 user));
1242 }
1243
1244 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001245 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001246 int op = PackageUpdatedTask.OP_ADD;
1247 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1248 user));
1249 }
1250
1251 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001252 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001253 boolean replacing) {
1254 if (!replacing) {
1255 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1256 user));
1257 if (mAppsCanBeOnRemoveableStorage) {
1258 // Only rebind if we support removable storage. It catches the
1259 // case where
1260 // apps on the external sd card need to be reloaded
1261 startLoaderFromBackground();
1262 }
1263 } else {
1264 // If we are replacing then just update the packages in the list
1265 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1266 packageNames, user));
1267 }
1268 }
1269
1270 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001271 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001272 boolean replacing) {
1273 if (!replacing) {
1274 enqueuePackageUpdated(new PackageUpdatedTask(
1275 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1276 user));
1277 }
Kenny Guyed131872014-04-30 03:02:21 +01001278 }
1279
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001280 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001281 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1282 * ACTION_PACKAGE_CHANGED.
1283 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001284 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001285 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001286 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001287
Joe Onorato36115782010-06-17 13:28:48 -04001288 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001289 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001290 // If we have changed locale we need to clear out the labels in all apps/workspace.
1291 forceReload();
1292 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1293 // Check if configuration change was an mcc/mnc change which would affect app resources
1294 // and we would need to clear out the labels in all apps/workspace. Same handling as
1295 // above for ACTION_LOCALE_CHANGED
1296 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001297 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001298 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001299 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001300 forceReload();
1301 }
1302 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001303 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001304 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1305 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001306 Callbacks callbacks = getCallback();
1307 if (callbacks != null) {
1308 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001309 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001310 }
1311 }
1312
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001313 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001314 resetLoadedState(true, true);
1315
Reena Lee93f824a2011-09-23 17:20:28 -07001316 // Do this here because if the launcher activity is running it will be restarted.
1317 // If it's not running startLoaderFromBackground will merely tell it that it needs
1318 // to reload.
1319 startLoaderFromBackground();
1320 }
1321
Winson Chungf0c6ae02012-03-21 16:10:31 -07001322 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1323 synchronized (mLock) {
1324 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1325 // mWorkspaceLoaded to true later
1326 stopLoaderLocked();
1327 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1328 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1329 }
1330 }
1331
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001332 /**
1333 * When the launcher is in the background, it's possible for it to miss paired
1334 * configuration changes. So whenever we trigger the loader from the background
1335 * tell the launcher that it needs to re-run the loader when it comes back instead
1336 * of doing it now.
1337 */
1338 public void startLoaderFromBackground() {
1339 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001340 Callbacks callbacks = getCallback();
1341 if (callbacks != null) {
1342 // Only actually run the loader if they're not paused.
1343 if (!callbacks.setLoadOnResume()) {
1344 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001345 }
1346 }
1347 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001348 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001349 }
Joe Onorato36115782010-06-17 13:28:48 -04001350 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001351
Reena Lee93f824a2011-09-23 17:20:28 -07001352 // If there is already a loader task running, tell it to stop.
1353 // returns true if isLaunching() was true on the old task
1354 private boolean stopLoaderLocked() {
1355 boolean isLaunching = false;
1356 LoaderTask oldTask = mLoaderTask;
1357 if (oldTask != null) {
1358 if (oldTask.isLaunching()) {
1359 isLaunching = true;
1360 }
1361 oldTask.stopLocked();
1362 }
1363 return isLaunching;
1364 }
1365
Adam Cohen1a85c582014-09-30 09:48:49 -07001366 public boolean isCurrentCallbacks(Callbacks callbacks) {
1367 return (mCallbacks != null && mCallbacks.get() == callbacks);
1368 }
1369
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001371 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1372 }
1373
1374 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001375 synchronized (mLock) {
1376 if (DEBUG_LOADERS) {
1377 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1378 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001379
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001380 // Clear any deferred bind-runnables from the synchronized load process
1381 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001382 synchronized (mDeferredBindRunnables) {
1383 mDeferredBindRunnables.clear();
1384 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001385
Joe Onorato36115782010-06-17 13:28:48 -04001386 // Don't bother to start the thread if we know it's not going to do anything
1387 if (mCallbacks != null && mCallbacks.get() != null) {
1388 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001389 // also, don't downgrade isLaunching if we're already running
1390 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001391 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001392 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1393 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001394 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1395 } else {
1396 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1397 sWorker.post(mLoaderTask);
1398 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001399 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001400 }
1401 }
1402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 void bindRemainingSynchronousPages() {
1404 // Post the remaining side pages to be loaded
1405 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001406 Runnable[] deferredBindRunnables = null;
1407 synchronized (mDeferredBindRunnables) {
1408 deferredBindRunnables = mDeferredBindRunnables.toArray(
1409 new Runnable[mDeferredBindRunnables.size()]);
1410 mDeferredBindRunnables.clear();
1411 }
1412 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001413 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001414 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001415 }
1416 }
1417
Joe Onorato36115782010-06-17 13:28:48 -04001418 public void stopLoader() {
1419 synchronized (mLock) {
1420 if (mLoaderTask != null) {
1421 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001422 }
1423 }
Joe Onorato36115782010-06-17 13:28:48 -04001424 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001425
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001426 /**
1427 * Loads the workspace screen ids in an ordered list.
1428 */
Adam Cohen091440a2015-03-18 14:16:05 -07001429 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001430 final ContentResolver contentResolver = context.getContentResolver();
1431 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001432
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001433 // Get screens ordered by rank.
1434 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1435 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1436 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001437 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001438 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001439 while (sc.moveToNext()) {
1440 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001441 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001442 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001443 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1444 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001445 }
1446 }
1447 } finally {
1448 sc.close();
1449 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001450 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001451 }
1452
Michael Jurkac57b7a82011-08-09 22:02:20 -07001453 public boolean isAllAppsLoaded() {
1454 return mAllAppsLoaded;
1455 }
1456
Winson Chung36a62fe2012-05-06 18:04:42 -07001457 boolean isLoadingWorkspace() {
1458 synchronized (mLock) {
1459 if (mLoaderTask != null) {
1460 return mLoaderTask.isLoadingWorkspace();
1461 }
1462 }
1463 return false;
1464 }
1465
Joe Onorato36115782010-06-17 13:28:48 -04001466 /**
1467 * Runnable for the thread that loads the contents of the launcher:
1468 * - workspace icons
1469 * - widgets
1470 * - all apps icons
1471 */
1472 private class LoaderTask implements Runnable {
1473 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001474 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001475 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001476 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001477 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001479
Dan Sandlerd5024042014-01-09 15:01:33 -05001480 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001481 mContext = context;
1482 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001483 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001484 }
1485
Joe Onorato36115782010-06-17 13:28:48 -04001486 boolean isLaunching() {
1487 return mIsLaunching;
1488 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Winson Chung36a62fe2012-05-06 18:04:42 -07001490 boolean isLoadingWorkspace() {
1491 return mIsLoadingAndBindingWorkspace;
1492 }
1493
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001494 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001495 mIsLoadingAndBindingWorkspace = true;
1496
Joe Onorato36115782010-06-17 13:28:48 -04001497 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001498 if (DEBUG_LOADERS) {
1499 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001500 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001501
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001502 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001503 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001504 synchronized (LoaderTask.this) {
1505 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001506 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001507 }
1508 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001509 }
1510 }
1511
Joe Onorato36115782010-06-17 13:28:48 -04001512 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001513 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001514 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001515
Joe Onorato36115782010-06-17 13:28:48 -04001516 private void waitForIdle() {
1517 // Wait until the either we're stopped or the other threads are done.
1518 // This way we don't start loading all apps until the workspace has settled
1519 // down.
1520 synchronized (LoaderTask.this) {
1521 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001522
Joe Onorato36115782010-06-17 13:28:48 -04001523 mHandler.postIdle(new Runnable() {
1524 public void run() {
1525 synchronized (LoaderTask.this) {
1526 mLoadAndBindStepFinished = true;
1527 if (DEBUG_LOADERS) {
1528 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001529 }
Joe Onorato36115782010-06-17 13:28:48 -04001530 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001532 }
Joe Onorato36115782010-06-17 13:28:48 -04001533 });
1534
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001535 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001536 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001537 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1538 // wait no longer than 1sec at a time
1539 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001540 } catch (InterruptedException ex) {
1541 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001542 }
1543 }
Joe Onorato36115782010-06-17 13:28:48 -04001544 if (DEBUG_LOADERS) {
1545 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001546 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001547 + "ms for previous step to finish binding");
1548 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001549 }
Joe Onorato36115782010-06-17 13:28:48 -04001550 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001552 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001553 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 // Ensure that we have a valid page index to load synchronously
1555 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1556 "valid page index");
1557 }
1558 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1559 // Ensure that we don't try and bind a specified page when the pages have not been
1560 // loaded already (we should load everything asynchronously in that case)
1561 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1562 }
1563 synchronized (mLock) {
1564 if (mIsLoaderTaskRunning) {
1565 // Ensure that we are never running the background loading at this point since
1566 // we also touch the background collections
1567 throw new RuntimeException("Error! Background loading is already running");
1568 }
1569 }
1570
1571 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1572 // data structures, we can't allow any other thread to touch that data, but because
1573 // this call is synchronous, we can get away with not locking).
1574
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001575 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001576 // operations from the previous activity. We need to ensure that all queued operations
1577 // are executed before any synchronous binding work is done.
1578 mHandler.flush();
1579
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001580 // Divide the set of loaded items into those that we are binding synchronously, and
1581 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001582 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1584 // arise from that.
1585 onlyBindAllApps();
1586 }
1587
Joe Onorato36115782010-06-17 13:28:48 -04001588 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 synchronized (mLock) {
1590 mIsLoaderTaskRunning = true;
1591 }
Joe Onorato36115782010-06-17 13:28:48 -04001592 // Optimize for end-user experience: if the Launcher is up and // running with the
1593 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1594 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001595 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001596 // Elevate priority when Home launches for the first time to avoid
1597 // starving at boot time. Staring at a blank home is not cool.
1598 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001599 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1600 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001601 android.os.Process.setThreadPriority(mIsLaunching
1602 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1603 }
Winson Chung64359a52013-07-08 17:17:08 -07001604 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001605 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001606
Joe Onorato36115782010-06-17 13:28:48 -04001607 if (mStopped) {
1608 break keep_running;
1609 }
1610
1611 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1612 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001613 synchronized (mLock) {
1614 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001615 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001616 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1617 }
1618 }
Joe Onorato36115782010-06-17 13:28:48 -04001619 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001620
1621 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001622 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1623 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001624
1625 // Restore the default thread priority after we are done loading items
1626 synchronized (mLock) {
1627 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1628 }
Joe Onorato36115782010-06-17 13:28:48 -04001629 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001630
Joe Onorato36115782010-06-17 13:28:48 -04001631 // Clear out this reference, otherwise we end up holding it until all of the
1632 // callback runnables are done.
1633 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001634
Joe Onorato36115782010-06-17 13:28:48 -04001635 synchronized (mLock) {
1636 // If we are still the last one to be scheduled, remove ourselves.
1637 if (mLoaderTask == this) {
1638 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001639 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001640 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001641 }
Joe Onorato36115782010-06-17 13:28:48 -04001642 }
1643
1644 public void stopLocked() {
1645 synchronized (LoaderTask.this) {
1646 mStopped = true;
1647 this.notify();
1648 }
1649 }
1650
1651 /**
1652 * Gets the callbacks object. If we've been stopped, or if the launcher object
1653 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1654 * object that was around when the deferred message was scheduled, and if there's
1655 * a new Callbacks object around then also return null. This will save us from
1656 * calling onto it with data that will be ignored.
1657 */
1658 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1659 synchronized (mLock) {
1660 if (mStopped) {
1661 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663
1664 if (mCallbacks == null) {
1665 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001666 }
Joe Onorato36115782010-06-17 13:28:48 -04001667
1668 final Callbacks callbacks = mCallbacks.get();
1669 if (callbacks != oldCallbacks) {
1670 return null;
1671 }
1672 if (callbacks == null) {
1673 Log.w(TAG, "no mCallbacks");
1674 return null;
1675 }
1676
1677 return callbacks;
1678 }
1679 }
1680
1681 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001682 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001683 LauncherAppState app = LauncherAppState.getInstance();
1684 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001685 final int countX = (int) grid.numColumns;
1686 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001687
Adam Cohendcd297f2013-06-18 13:13:40 -07001688 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001689 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001690 // Return early if we detect that an item is under the hotseat button
1691 if (mCallbacks == null ||
1692 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001693 Log.e(TAG, "Error loading shortcut into hotseat " + item
1694 + " into position (" + item.screenId + ":" + item.cellX + ","
1695 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001696 return false;
1697 }
1698
Dan Sandler295ae182013-12-10 16:05:47 -05001699 final ItemInfo[][] hotseatItems =
1700 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1701
Adam Cohenae4409d2013-11-26 10:34:59 -08001702 if (item.screenId >= grid.numHotseatIcons) {
1703 Log.e(TAG, "Error loading shortcut " + item
1704 + " into hotseat position " + item.screenId
1705 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1706 + ")");
1707 return false;
1708 }
1709
Dan Sandler295ae182013-12-10 16:05:47 -05001710 if (hotseatItems != null) {
1711 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001712 Log.e(TAG, "Error loading shortcut into hotseat " + item
1713 + " into position (" + item.screenId + ":" + item.cellX + ","
1714 + item.cellY + ") occupied by "
1715 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1716 [(int) item.screenId][0]);
1717 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001718 } else {
1719 hotseatItems[(int) item.screenId][0] = item;
1720 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001721 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001722 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001723 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001724 items[(int) item.screenId][0] = item;
1725 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001726 return true;
1727 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001728 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1729 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001730 return true;
1731 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001732
Adam Cohendcd297f2013-06-18 13:13:40 -07001733 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001734 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001735 occupied.put(item.screenId, items);
1736 }
1737
Dan Sandler295ae182013-12-10 16:05:47 -05001738 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001739 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1740 item.cellX < 0 || item.cellY < 0 ||
1741 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1742 Log.e(TAG, "Error loading shortcut " + item
1743 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1744 + item.cellX + "," + item.cellY
1745 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1746 return false;
1747 }
1748
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001749 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001750 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1751 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001752 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001753 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001755 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001756 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001757 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001758 return false;
1759 }
1760 }
1761 }
1762 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1763 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001764 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001765 }
1766 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001767
Joe Onorato36115782010-06-17 13:28:48 -04001768 return true;
1769 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001770
Winson Chungba9c37f2013-08-30 14:11:37 -07001771 /** Clears all the sBg data structures */
1772 private void clearSBgDataStructures() {
1773 synchronized (sBgLock) {
1774 sBgWorkspaceItems.clear();
1775 sBgAppWidgets.clear();
1776 sBgFolders.clear();
1777 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001778 sBgWorkspaceScreens.clear();
1779 }
1780 }
1781
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001782 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001783 // Log to disk
1784 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1785
Joe Onorato36115782010-06-17 13:28:48 -04001786 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001787
Joe Onorato36115782010-06-17 13:28:48 -04001788 final Context context = mContext;
1789 final ContentResolver contentResolver = context.getContentResolver();
1790 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001791 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001792 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1793 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001794 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001795
Winson Chung892c74d2013-08-22 16:15:50 -07001796 LauncherAppState app = LauncherAppState.getInstance();
1797 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1798 int countX = (int) grid.numColumns;
1799 int countY = (int) grid.numRows;
1800
Dan Sandlerd5024042014-01-09 15:01:33 -05001801 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1802 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1803 LauncherAppState.getLauncherProvider().deleteDatabase();
1804 }
1805
1806 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1807 // append the user's Launcher2 shortcuts
1808 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1809 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1810 } else {
1811 // Make sure the default workspace is loaded
1812 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001813 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001814 }
Adam Cohene25af792013-06-06 23:08:25 -07001815
Winson Chung2abf94d2012-07-18 18:16:38 -07001816 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001817 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001818 final HashSet<String> installingPkgs = PackageInstallerCompat
1819 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001820
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001821 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001822 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001823 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001824 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001825 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001826
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001827 // +1 for the hotseat (it can be larger than the workspace)
1828 // Load workspace in reverse order to ensure that latest items are loaded first (and
1829 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001830 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001831
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001832 try {
1833 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1834 final int intentIndex = c.getColumnIndexOrThrow
1835 (LauncherSettings.Favorites.INTENT);
1836 final int titleIndex = c.getColumnIndexOrThrow
1837 (LauncherSettings.Favorites.TITLE);
1838 final int iconTypeIndex = c.getColumnIndexOrThrow(
1839 LauncherSettings.Favorites.ICON_TYPE);
1840 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1841 final int iconPackageIndex = c.getColumnIndexOrThrow(
1842 LauncherSettings.Favorites.ICON_PACKAGE);
1843 final int iconResourceIndex = c.getColumnIndexOrThrow(
1844 LauncherSettings.Favorites.ICON_RESOURCE);
1845 final int containerIndex = c.getColumnIndexOrThrow(
1846 LauncherSettings.Favorites.CONTAINER);
1847 final int itemTypeIndex = c.getColumnIndexOrThrow(
1848 LauncherSettings.Favorites.ITEM_TYPE);
1849 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1850 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001851 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1852 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001853 final int screenIndex = c.getColumnIndexOrThrow(
1854 LauncherSettings.Favorites.SCREEN);
1855 final int cellXIndex = c.getColumnIndexOrThrow
1856 (LauncherSettings.Favorites.CELLX);
1857 final int cellYIndex = c.getColumnIndexOrThrow
1858 (LauncherSettings.Favorites.CELLY);
1859 final int spanXIndex = c.getColumnIndexOrThrow
1860 (LauncherSettings.Favorites.SPANX);
1861 final int spanYIndex = c.getColumnIndexOrThrow(
1862 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001863 final int rankIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001865 final int restoredIndex = c.getColumnIndexOrThrow(
1866 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001867 final int profileIdIndex = c.getColumnIndexOrThrow(
1868 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001869 final int optionsIndex = c.getColumnIndexOrThrow(
1870 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001871
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001872 ShortcutInfo info;
1873 String intentDescription;
1874 LauncherAppWidgetInfo appWidgetInfo;
1875 int container;
1876 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001877 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001878 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001879 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001880
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 while (!mStopped && c.moveToNext()) {
1882 try {
1883 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001884 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001885 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001886
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 switch (itemType) {
1888 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1889 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001890 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001891 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001892 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001893 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001894 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001895 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001896 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001897 if (user == null) {
1898 // User has been deleted remove the item.
1899 itemsToRemove.add(id);
1900 continue;
1901 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001902 try {
1903 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001904 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001905 if (cn != null && cn.getPackageName() != null) {
1906 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1907 cn.getPackageName(), user);
1908 boolean validComponent = validPkg &&
1909 launcherApps.isActivityEnabledForProfile(cn, user);
1910
1911 if (validComponent) {
1912 if (restored) {
1913 // no special handling necessary for this item
1914 restoredRows.add(id);
1915 restored = false;
1916 }
1917 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001918 intent = null;
1919 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1920 // We allow auto install apps to have their intent
1921 // updated after an install.
1922 intent = manager.getLaunchIntentForPackage(
1923 cn.getPackageName());
1924 if (intent != null) {
1925 ContentValues values = new ContentValues();
1926 values.put(LauncherSettings.Favorites.INTENT,
1927 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001928 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001929 }
1930 }
1931
1932 if (intent == null) {
1933 // The app is installed but the component is no
1934 // longer available.
1935 Launcher.addDumpLog(TAG,
1936 "Invalid component removed: " + cn, true);
1937 itemsToRemove.add(id);
1938 continue;
1939 } else {
1940 // no special handling necessary for this item
1941 restoredRows.add(id);
1942 restored = false;
1943 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001944 } else if (restored) {
1945 // Package is not yet available but might be
1946 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001947 Launcher.addDumpLog(TAG,
1948 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001949
1950 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1951 // Restore has started once.
1952 } else if (installingPkgs.contains(cn.getPackageName())) {
1953 // App restore has started. Update the flag
1954 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1955 ContentValues values = new ContentValues();
1956 values.put(LauncherSettings.Favorites.RESTORED,
1957 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001958 updateItem(id, values);
1959 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1960 // This is a common app. Try to replace this.
1961 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1962 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1963 if (parser.findDefaultApp()) {
1964 // Default app found. Replace it.
1965 intent = parser.parsedIntent;
1966 cn = intent.getComponent();
1967 ContentValues values = parser.parsedValues;
1968 values.put(LauncherSettings.Favorites.RESTORED, 0);
1969 updateItem(id, values);
1970 restored = false;
1971 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001972
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001973 } else if (REMOVE_UNRESTORED_ICONS) {
1974 Launcher.addDumpLog(TAG,
1975 "Unrestored package removed: " + cn, true);
1976 itemsToRemove.add(id);
1977 continue;
1978 }
Sunny Goyal94485362014-09-18 16:13:58 -07001979 } else if (REMOVE_UNRESTORED_ICONS) {
1980 Launcher.addDumpLog(TAG,
1981 "Unrestored package removed: " + cn, true);
1982 itemsToRemove.add(id);
1983 continue;
1984 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001985 } else if (launcherApps.isAppEnabled(
1986 manager, cn.getPackageName(),
1987 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1988 // Package is present but not available.
1989 allowMissingTarget = true;
1990 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1991 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001992 // SdCard is not ready yet. Package might get available,
1993 // once it is ready.
1994 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1995 + " (check again later)", true);
1996 HashSet<String> pkgs = sPendingPackages.get(user);
1997 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001998 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001999 sPendingPackages.put(user, pkgs);
2000 }
2001 pkgs.add(cn.getPackageName());
2002 allowMissingTarget = true;
2003 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002004
2005 } else {
2006 // Do not wait for external media load anymore.
2007 // Log the invalid package, and remove it
2008 Launcher.addDumpLog(TAG,
2009 "Invalid package removed: " + cn, true);
2010 itemsToRemove.add(id);
2011 continue;
Winson Chungee055712013-07-30 14:46:24 -07002012 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002013 } else if (cn == null) {
2014 // For shortcuts with no component, keep them as they are
2015 restoredRows.add(id);
2016 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002017 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002018 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002019 Launcher.addDumpLog(TAG,
2020 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002021 continue;
2022 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002023
Sunny Goyal34b65272015-03-11 16:56:52 -07002024 container = c.getInt(containerIndex);
2025 boolean useLowResIcon = container >= 0 &&
2026 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2027
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002028 if (itemReplaced) {
2029 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002030 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002031 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002032 } else {
2033 // Don't replace items for other profiles.
2034 itemsToRemove.add(id);
2035 continue;
2036 }
2037 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002038 if (user.equals(UserHandleCompat.myUserHandle())) {
2039 Launcher.addDumpLog(TAG,
2040 "constructing info for partially restored package",
2041 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002042 info = getRestoredItemInfo(c, titleIndex, intent,
2043 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002044 intent = getRestoredItemIntent(c, context, intent);
2045 } else {
2046 // Don't restore items for other profiles.
2047 itemsToRemove.add(id);
2048 continue;
2049 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002050 } else if (itemType ==
2051 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002052 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002053 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002054 } else {
2055 info = getShortcutInfo(c, context, iconTypeIndex,
2056 iconPackageIndex, iconResourceIndex, iconIndex,
2057 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002058
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002059 // App shortcuts that used to be automatically added to Launcher
2060 // didn't always have the correct intent flags set, so do that
2061 // here
2062 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002063 intent.getCategories() != null &&
2064 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002065 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 intent.addFlags(
2067 Intent.FLAG_ACTIVITY_NEW_TASK |
2068 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2069 }
Michael Jurka96879562012-03-22 05:54:33 -07002070 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002071
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002073 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002075 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002076 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 info.cellX = c.getInt(cellXIndex);
2078 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002079 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002080 info.spanX = 1;
2081 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002082 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002083 info.isDisabled = disabledState;
2084 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2085 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2086 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002087
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002089 if (!checkItemPlacement(occupied, info)) {
2090 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 break;
2092 }
2093
2094 switch (container) {
2095 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2096 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2097 sBgWorkspaceItems.add(info);
2098 break;
2099 default:
2100 // Item is in a user folder
2101 FolderInfo folderInfo =
2102 findOrMakeFolder(sBgFolders, container);
2103 folderInfo.add(info);
2104 break;
2105 }
2106 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002107 } else {
2108 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 }
2110 break;
2111
2112 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2113 id = c.getLong(idIndex);
2114 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2115
2116 folderInfo.title = c.getString(titleIndex);
2117 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002118 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002119 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002120 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 folderInfo.cellX = c.getInt(cellXIndex);
2122 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002123 folderInfo.spanX = 1;
2124 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002125 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002126
Daniel Sandler8802e962010-05-26 16:28:16 -04002127 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002128 if (!checkItemPlacement(occupied, folderInfo)) {
2129 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002130 break;
2131 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002132
Joe Onorato9c1289c2009-08-17 11:03:03 -04002133 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002134 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2135 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2136 sBgWorkspaceItems.add(folderInfo);
2137 break;
Joe Onorato36115782010-06-17 13:28:48 -04002138 }
Joe Onorato17a89222011-02-08 17:26:11 -08002139
Chris Wrenf4d08112014-01-16 18:13:56 -05002140 if (restored) {
2141 // no special handling required for restored folders
2142 restoredRows.add(id);
2143 }
2144
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002145 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2146 sBgFolders.put(folderInfo.id, folderInfo);
2147 break;
2148
2149 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002150 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002152 boolean customWidget = itemType ==
2153 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2154
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002155 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002156 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002157 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002158 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002159 final ComponentName component =
2160 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002161
Sunny Goyal651077b2014-06-30 14:15:31 -07002162 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002163 final boolean isIdValid = (restoreStatus &
2164 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002165
Sunny Goyalff572272014-07-23 13:58:07 -07002166 final boolean wasProviderReady = (restoreStatus &
2167 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002168
Adam Cohen59400422014-03-05 18:07:04 -08002169 final LauncherAppWidgetProviderInfo provider =
2170 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002171 ComponentName.unflattenFromString(savedProvider),
2172 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002173
2174 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002175 if (!isSafeMode && !customWidget &&
2176 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002177 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002178 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002179
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002180 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002181 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002182 itemsToRemove.add(id);
2183 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002184 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002185 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2186 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002187
2188 if (!customWidget) {
2189 int[] minSpan =
2190 Launcher.getMinSpanForWidget(context, provider);
2191 appWidgetInfo.minSpanX = minSpan[0];
2192 appWidgetInfo.minSpanY = minSpan[1];
2193 }
Sunny Goyalff572272014-07-23 13:58:07 -07002194
2195 int status = restoreStatus;
2196 if (!wasProviderReady) {
2197 // If provider was not previously ready, update the
2198 // status and UI flag.
2199
2200 // Id would be valid only if the widget restore broadcast was received.
2201 if (isIdValid) {
2202 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2203 } else {
2204 status &= ~LauncherAppWidgetInfo
2205 .FLAG_PROVIDER_NOT_READY;
2206 }
2207 }
2208 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002209 } else {
2210 Log.v(TAG, "Widget restore pending id=" + id
2211 + " appWidgetId=" + appWidgetId
2212 + " status =" + restoreStatus);
2213 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002214 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002215 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002216
2217 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2218 // Restore has started once.
2219 } else if (installingPkgs.contains(component.getPackageName())) {
2220 // App restore has started. Update the flag
2221 appWidgetInfo.restoreStatus |=
2222 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002223 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002224 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002225 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002226 itemsToRemove.add(id);
2227 continue;
2228 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002229 }
Sunny Goyalff572272014-07-23 13:58:07 -07002230
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002231 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002232 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002233 appWidgetInfo.cellX = c.getInt(cellXIndex);
2234 appWidgetInfo.cellY = c.getInt(cellYIndex);
2235 appWidgetInfo.spanX = c.getInt(spanXIndex);
2236 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002237
Adam Cohen59400422014-03-05 18:07:04 -08002238 if (!customWidget) {
2239 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2240 appWidgetInfo.minSpanX = minSpan[0];
2241 appWidgetInfo.minSpanY = minSpan[1];
2242 }
2243
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002244 container = c.getInt(containerIndex);
2245 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2246 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2247 Log.e(TAG, "Widget found where container != " +
2248 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2249 continue;
2250 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251
Adam Cohene25af792013-06-06 23:08:25 -07002252 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002253 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002254 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2255 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002256 break;
2257 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002258
Adam Cohen59400422014-03-05 18:07:04 -08002259 if (!customWidget) {
2260 String providerName =
2261 appWidgetInfo.providerName.flattenToString();
2262 if (!providerName.equals(savedProvider) ||
2263 (appWidgetInfo.restoreStatus != restoreStatus)) {
2264 ContentValues values = new ContentValues();
2265 values.put(
2266 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2267 providerName);
2268 values.put(LauncherSettings.Favorites.RESTORED,
2269 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002270 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002271 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002272 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002273 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2274 sBgAppWidgets.add(appWidgetInfo);
2275 }
Joe Onorato36115782010-06-17 13:28:48 -04002276 break;
2277 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002278 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002279 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002280 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 }
2282 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002283 if (c != null) {
2284 c.close();
2285 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002286 }
2287
Winson Chungba9c37f2013-08-30 14:11:37 -07002288 // Break early if we've stopped loading
2289 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002290 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002291 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002292 }
2293
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002294 if (itemsToRemove.size() > 0) {
2295 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002296 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002297 // Remove dead items
2298 for (long id : itemsToRemove) {
2299 if (DEBUG_LOADERS) {
2300 Log.d(TAG, "Removed id = " + id);
2301 }
2302 // Don't notify content observers
2303 try {
2304 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2305 null, null);
2306 } 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 Goyal34942622014-08-29 17:20:55 -07002324 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
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);
2344 for (ItemInfo item: sBgItemsIdMap.values()) {
2345 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
Daniel Sandler566da102013-06-25 23:43:45 -04002369 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002370 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002371 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002372 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002373 line += " | ";
2374 }
Winson Chung892c74d2013-08-22 16:15:50 -07002375 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002376 ItemInfo[][] screen = occupied.get(screenId);
2377 if (x < screen.length && y < screen[x].length) {
2378 line += (screen[x][y] != null) ? "#" : ".";
2379 } else {
2380 line += "!";
2381 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002382 }
Joe Onorato36115782010-06-17 13:28:48 -04002383 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002384 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002385 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002386 }
Joe Onorato36115782010-06-17 13:28:48 -04002387 }
Adam Cohene25af792013-06-06 23:08:25 -07002388 }
2389
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002390 /**
2391 * Partially updates the item without any notification. Must be called on the worker thread.
2392 */
2393 private void updateItem(long itemId, ContentValues update) {
2394 mContext.getContentResolver().update(
2395 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2396 update,
2397 BaseColumns._ID + "= ?",
2398 new String[]{Long.toString(itemId)});
2399 }
2400
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002401 /** Filters the set of items who are directly or indirectly (via another container) on the
2402 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002403 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002404 ArrayList<ItemInfo> allWorkspaceItems,
2405 ArrayList<ItemInfo> currentScreenItems,
2406 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002407 // Purge any null ItemInfos
2408 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2409 while (iter.hasNext()) {
2410 ItemInfo i = iter.next();
2411 if (i == null) {
2412 iter.remove();
2413 }
2414 }
2415
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002416 // Order the set of items by their containers first, this allows use to walk through the
2417 // list sequentially, build up a list of containers that are in the specified screen,
2418 // as well as all items in those containers.
2419 Set<Long> itemsOnScreen = new HashSet<Long>();
2420 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2421 @Override
2422 public int compare(ItemInfo lhs, ItemInfo rhs) {
2423 return (int) (lhs.container - rhs.container);
2424 }
2425 });
2426 for (ItemInfo info : allWorkspaceItems) {
2427 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002428 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002429 currentScreenItems.add(info);
2430 itemsOnScreen.add(info.id);
2431 } else {
2432 otherScreenItems.add(info);
2433 }
2434 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2435 currentScreenItems.add(info);
2436 itemsOnScreen.add(info.id);
2437 } else {
2438 if (itemsOnScreen.contains(info.container)) {
2439 currentScreenItems.add(info);
2440 itemsOnScreen.add(info.id);
2441 } else {
2442 otherScreenItems.add(info);
2443 }
2444 }
2445 }
2446 }
2447
2448 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002449 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002450 ArrayList<LauncherAppWidgetInfo> appWidgets,
2451 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2452 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453
2454 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002455 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002457 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002458 currentScreenWidgets.add(widget);
2459 } else {
2460 otherScreenWidgets.add(widget);
2461 }
2462 }
2463 }
2464
2465 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002466 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467 HashMap<Long, ItemInfo> itemsIdMap,
2468 HashMap<Long, FolderInfo> folders,
2469 HashMap<Long, FolderInfo> currentScreenFolders,
2470 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471
2472 for (long id : folders.keySet()) {
2473 ItemInfo info = itemsIdMap.get(id);
2474 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002475 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002476 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002477 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002478 currentScreenFolders.put(id, folder);
2479 } else {
2480 otherScreenFolders.put(id, folder);
2481 }
2482 }
2483 }
2484
2485 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2486 * right) */
2487 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002488 final LauncherAppState app = LauncherAppState.getInstance();
2489 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002490 // XXX: review this
2491 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002492 @Override
2493 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002494 int cellCountX = (int) grid.numColumns;
2495 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002496 int screenOffset = cellCountX * cellCountY;
2497 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002498 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002499 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002500 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002501 rhs.cellY * cellCountX + rhs.cellX);
2502 return (int) (lr - rr);
2503 }
2504 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002505 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002506
Adam Cohendcd297f2013-06-18 13:13:40 -07002507 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2508 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002509 final Runnable r = new Runnable() {
2510 @Override
2511 public void run() {
2512 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2513 if (callbacks != null) {
2514 callbacks.bindScreens(orderedScreens);
2515 }
2516 }
2517 };
2518 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2519 }
2520
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2522 final ArrayList<ItemInfo> workspaceItems,
2523 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2524 final HashMap<Long, FolderInfo> folders,
2525 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002526
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002527 final boolean postOnMainThread = (deferredBindRunnables != null);
2528
2529 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002530 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002531 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002532 final int start = i;
2533 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 final Runnable r = new Runnable() {
2535 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002536 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002537 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002538 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002539 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2540 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002541 }
2542 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002543 };
2544 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002545 synchronized (deferredBindRunnables) {
2546 deferredBindRunnables.add(r);
2547 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002548 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002549 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002550 }
Joe Onorato36115782010-06-17 13:28:48 -04002551 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552
2553 // Bind the folders
2554 if (!folders.isEmpty()) {
2555 final Runnable r = new Runnable() {
2556 public void run() {
2557 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2558 if (callbacks != null) {
2559 callbacks.bindFolders(folders);
2560 }
2561 }
2562 };
2563 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002564 synchronized (deferredBindRunnables) {
2565 deferredBindRunnables.add(r);
2566 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002567 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002568 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002569 }
2570 }
2571
2572 // Bind the widgets, one at a time
2573 N = appWidgets.size();
2574 for (int i = 0; i < N; i++) {
2575 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2576 final Runnable r = new Runnable() {
2577 public void run() {
2578 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2579 if (callbacks != null) {
2580 callbacks.bindAppWidget(widget);
2581 }
2582 }
2583 };
2584 if (postOnMainThread) {
2585 deferredBindRunnables.add(r);
2586 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002587 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002588 }
2589 }
2590 }
2591
2592 /**
2593 * Binds all loaded data to actual views on the main thread.
2594 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002595 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002596 final long t = SystemClock.uptimeMillis();
2597 Runnable r;
2598
2599 // Don't use these two variables in any of the callback runnables.
2600 // Otherwise we hold a reference to them.
2601 final Callbacks oldCallbacks = mCallbacks.get();
2602 if (oldCallbacks == null) {
2603 // This launcher has exited and nobody bothered to tell us. Just bail.
2604 Log.w(TAG, "LoaderTask running with no launcher");
2605 return;
2606 }
2607
Winson Chung9b9fb962013-11-15 15:39:34 -08002608 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002609 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2610 ArrayList<LauncherAppWidgetInfo> appWidgets =
2611 new ArrayList<LauncherAppWidgetInfo>();
2612 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2613 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002614 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002615 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 workspaceItems.addAll(sBgWorkspaceItems);
2617 appWidgets.addAll(sBgAppWidgets);
2618 folders.putAll(sBgFolders);
2619 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002620 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002621 }
2622
Derek Prothro7aff3992013-12-10 14:00:37 -05002623 final boolean isLoadingSynchronously =
2624 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002625 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002626 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002627 if (currScreen >= orderedScreenIds.size()) {
2628 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002629 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002630 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002631 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002632 final long currentScreenId = currentScreen < 0
2633 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002634
2635 // Load all the items that are on the current page first (and in the process, unbind
2636 // all the existing workspace items before we call startBinding() below.
2637 unbindWorkspaceItemsOnMainThread();
2638
2639 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2641 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2642 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2643 new ArrayList<LauncherAppWidgetInfo>();
2644 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2645 new ArrayList<LauncherAppWidgetInfo>();
2646 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2647 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2648
Winson Chung9b9fb962013-11-15 15:39:34 -08002649 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002650 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002651 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002652 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002653 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002654 otherFolders);
2655 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2656 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2657
2658 // Tell the workspace that we're about to start binding items
2659 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002660 public void run() {
2661 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2662 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002664 }
2665 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 };
Winson Chung81b52252012-08-27 15:34:29 -07002667 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668
Adam Cohendcd297f2013-06-18 13:13:40 -07002669 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2670
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671 // Load items on the current page
2672 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2673 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002674 if (isLoadingSynchronously) {
2675 r = new Runnable() {
2676 public void run() {
2677 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002678 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002679 callbacks.onPageBoundSynchronously(currentScreen);
2680 }
2681 }
2682 };
Winson Chung81b52252012-08-27 15:34:29 -07002683 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002684 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002685
Winson Chung4a2afa32012-07-19 14:53:05 -07002686 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2687 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002688 synchronized (mDeferredBindRunnables) {
2689 mDeferredBindRunnables.clear();
2690 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002691 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002692 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002693
2694 // Tell the workspace that we're done binding items
2695 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002696 public void run() {
2697 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2698 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002699 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002700 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002701
Winson Chung98e030b2012-05-07 16:01:11 -07002702 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002703 if (DEBUG_LOADERS) {
2704 Log.d(TAG, "bound workspace in "
2705 + (SystemClock.uptimeMillis()-t) + "ms");
2706 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002707
2708 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002709 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002710 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002711 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002712 synchronized (mDeferredBindRunnables) {
2713 mDeferredBindRunnables.add(r);
2714 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002715 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002716 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002717 }
Joe Onorato36115782010-06-17 13:28:48 -04002718 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002719
Joe Onorato36115782010-06-17 13:28:48 -04002720 private void loadAndBindAllApps() {
2721 if (DEBUG_LOADERS) {
2722 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2723 }
2724 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002725 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002726 synchronized (LoaderTask.this) {
2727 if (mStopped) {
2728 return;
2729 }
2730 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002731 }
Joe Onorato36115782010-06-17 13:28:48 -04002732 } else {
2733 onlyBindAllApps();
2734 }
2735 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002736
Joe Onorato36115782010-06-17 13:28:48 -04002737 private void onlyBindAllApps() {
2738 final Callbacks oldCallbacks = mCallbacks.get();
2739 if (oldCallbacks == null) {
2740 // This launcher has exited and nobody bothered to tell us. Just bail.
2741 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2742 return;
2743 }
2744
2745 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002746 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002747 final ArrayList<AppInfo> list
2748 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002749 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002750 public void run() {
2751 final long t = SystemClock.uptimeMillis();
2752 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2753 if (callbacks != null) {
2754 callbacks.bindAllApplications(list);
2755 }
2756 if (DEBUG_LOADERS) {
2757 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2758 + (SystemClock.uptimeMillis()-t) + "ms");
2759 }
2760 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002761 };
2762 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002763 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002764 r.run();
2765 } else {
2766 mHandler.post(r);
2767 }
Joe Onorato36115782010-06-17 13:28:48 -04002768 }
2769
Winson Chung64359a52013-07-08 17:17:08 -07002770 private void loadAllApps() {
2771 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002772
Joe Onorato36115782010-06-17 13:28:48 -04002773 final Callbacks oldCallbacks = mCallbacks.get();
2774 if (oldCallbacks == null) {
2775 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002776 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002777 return;
2778 }
2779
2780 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2781 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2782
Kenny Guyed131872014-04-30 03:02:21 +01002783 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2784
Winson Chung64359a52013-07-08 17:17:08 -07002785 // Clear the list of apps
2786 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002787 SharedPreferences prefs = mContext.getSharedPreferences(
2788 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002789 for (UserHandleCompat user : profiles) {
2790 // Query for the set of apps
2791 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2792 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2793 if (DEBUG_LOADERS) {
2794 Log.d(TAG, "getActivityList took "
2795 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2796 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2797 }
2798 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002799 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002800 if (apps == null || apps.isEmpty()) {
2801 return;
2802 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002803
2804 // Update icon cache
2805 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2806
2807 // If any package icon has changed (app was updated while launcher was dead),
2808 // update the corresponding shortcuts.
2809 if (!updatedPackages.isEmpty()) {
2810 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2811 synchronized (sBgLock) {
2812 for (ItemInfo info : sBgItemsIdMap.values()) {
2813 if (info instanceof ShortcutInfo && user.equals(info.user)
2814 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2815 ShortcutInfo si = (ShortcutInfo) info;
2816 ComponentName cn = si.getTargetComponent();
2817 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2818 si.updateIcon(mIconCache);
2819 updates.add(si);
2820 }
2821 }
2822 }
2823 }
2824
2825 if (!updates.isEmpty()) {
2826 final UserHandleCompat userFinal = user;
2827 mHandler.post(new Runnable() {
2828
2829 public void run() {
2830 Callbacks cb = getCallback();
2831 if (cb != null) {
2832 cb.bindShortcutsChanged(
2833 updates, new ArrayList<ShortcutInfo>(), userFinal);
2834 }
2835 }
2836 });
2837 }
Kenny Guyed131872014-04-30 03:02:21 +01002838 }
Joe Onorato36115782010-06-17 13:28:48 -04002839
Kenny Guyed131872014-04-30 03:02:21 +01002840 // Create the ApplicationInfos
2841 for (int i = 0; i < apps.size(); i++) {
2842 LauncherActivityInfoCompat app = apps.get(i);
2843 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002844 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002845 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002846
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002847 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002848 // Add shortcuts for packages which were installed while launcher was dead.
2849 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2850 + mUserManager.getSerialNumberForUser(user);
2851 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2852 HashSet<String> newPackageSet = new HashSet<String>();
2853
2854 for (LauncherActivityInfoCompat info : apps) {
2855 String packageName = info.getComponentName().getPackageName();
2856 if (!packagesAdded.contains(packageName)
2857 && !newPackageSet.contains(packageName)) {
2858 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2859 }
2860 newPackageSet.add(packageName);
2861 }
2862
2863 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2864 }
Winson Chung64359a52013-07-08 17:17:08 -07002865 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002866 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002867 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2868 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002869
2870 // Post callback on main thread
2871 mHandler.post(new Runnable() {
2872 public void run() {
2873 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002874 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002875 if (callbacks != null) {
2876 callbacks.bindAllApplications(added);
2877 if (DEBUG_LOADERS) {
2878 Log.d(TAG, "bound " + added.size() + " apps in "
2879 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2880 }
2881 } else {
2882 Log.i(TAG, "not binding apps: no Launcher activity");
2883 }
2884 }
2885 });
2886
Joe Onorato36115782010-06-17 13:28:48 -04002887 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002888 Log.d(TAG, "Icons processed in "
2889 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002890 }
2891 }
2892
2893 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002894 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002895 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2896 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2897 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2898 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2899 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2900 }
Joe Onorato36115782010-06-17 13:28:48 -04002901 }
2902 }
2903
2904 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002905 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002906 }
2907
Adam Cohen091440a2015-03-18 14:16:05 -07002908 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002909
2910 @Override
2911 public void onReceive(Context context, Intent intent) {
2912 synchronized (sBgLock) {
2913 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2914 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002915 final PackageManager manager = context.getPackageManager();
2916 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2917 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002918 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2919 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002920 packagesRemoved.clear();
2921 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002922 for (String pkg : entry.getValue()) {
2923 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002924 boolean packageOnSdcard = launcherApps.isAppEnabled(
2925 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2926 if (packageOnSdcard) {
2927 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2928 packagesUnavailable.add(pkg);
2929 } else {
2930 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2931 packagesRemoved.add(pkg);
2932 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002933 }
2934 }
2935 if (!packagesRemoved.isEmpty()) {
2936 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2937 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2938 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002939 if (!packagesUnavailable.isEmpty()) {
2940 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2941 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2942 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002943 }
Sunny Goyal34942622014-08-29 17:20:55 -07002944 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002945 }
2946 }
2947 }
2948
Joe Onorato36115782010-06-17 13:28:48 -04002949 private class PackageUpdatedTask implements Runnable {
2950 int mOp;
2951 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002952 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002953
2954 public static final int OP_NONE = 0;
2955 public static final int OP_ADD = 1;
2956 public static final int OP_UPDATE = 2;
2957 public static final int OP_REMOVE = 3; // uninstlled
2958 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2959
2960
Kenny Guyed131872014-04-30 03:02:21 +01002961 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002962 mOp = op;
2963 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002964 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002965 }
2966
2967 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002968 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002969
2970 final String[] packages = mPackages;
2971 final int N = packages.length;
2972 switch (mOp) {
2973 case OP_ADD:
2974 for (int i=0; i<N; i++) {
2975 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002976 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002977 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002978 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002979
2980 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002981 if (ADD_MANAGED_PROFILE_SHORTCUTS
2982 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002983 SharedPreferences prefs = context.getSharedPreferences(
2984 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2985 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2986 + mUserManager.getSerialNumberForUser(mUser);
2987 Set<String> shortcutSet = new HashSet<String>(
2988 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2989
2990 for (int i=0; i<N; i++) {
2991 if (!shortcutSet.contains(packages[i])) {
2992 shortcutSet.add(packages[i]);
2993 List<LauncherActivityInfoCompat> activities =
2994 mLauncherApps.getActivityList(packages[i], mUser);
2995 if (activities != null && !activities.isEmpty()) {
2996 InstallShortcutReceiver.queueInstallShortcut(
2997 activities.get(0), context);
2998 }
2999 }
3000 }
3001
3002 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3003 }
Joe Onorato36115782010-06-17 13:28:48 -04003004 break;
3005 case OP_UPDATE:
3006 for (int i=0; i<N; i++) {
3007 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003008 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003009 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003010 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003011 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003012 }
3013 break;
3014 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003015 // Remove the packageName for the set of auto-installed shortcuts. This
3016 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003017 if (ADD_MANAGED_PROFILE_SHORTCUTS
3018 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003019 SharedPreferences prefs = context.getSharedPreferences(
3020 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3021 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3022 + mUserManager.getSerialNumberForUser(mUser);
3023 HashSet<String> shortcutSet = new HashSet<String>(
3024 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3025 shortcutSet.removeAll(Arrays.asList(mPackages));
3026 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3027 }
Joe Onorato36115782010-06-17 13:28:48 -04003028 for (int i=0; i<N; i++) {
3029 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003030 mIconCache.removeIconsForPkg(packages[i], mUser);
3031 }
3032 // Fall through
3033 case OP_UNAVAILABLE:
3034 for (int i=0; i<N; i++) {
3035 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3036 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003037 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003038 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003039 }
3040 break;
3041 }
3042
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003043 ArrayList<AppInfo> added = null;
3044 ArrayList<AppInfo> modified = null;
3045 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003046
Adam Cohen487f7dd2012-06-28 18:12:10 -07003047 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003048 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003049 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003050 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003051 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003052 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003053 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003054 }
Winson Chung5d55f332012-07-16 20:45:03 -07003055 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003056 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003057 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003058 }
3059
Sunny Goyale0f58d72014-11-10 18:05:31 -08003060 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003061 if (callbacks == null) {
3062 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3063 return;
3064 }
3065
Sunny Goyal4390ace2014-10-13 11:33:11 -07003066 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3067 new HashMap<ComponentName, AppInfo>();
3068
Joe Onorato36115782010-06-17 13:28:48 -04003069 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003070 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003071 for (AppInfo ai : added) {
3072 addedOrUpdatedApps.put(ai.componentName, ai);
3073 }
Joe Onorato36115782010-06-17 13:28:48 -04003074 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003075
Joe Onorato36115782010-06-17 13:28:48 -04003076 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003077 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003078 for (AppInfo ai : modified) {
3079 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003080 }
3081
Joe Onorato36115782010-06-17 13:28:48 -04003082 mHandler.post(new Runnable() {
3083 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003084 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003085 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003086 callbacks.bindAppsUpdated(modifiedFinal);
3087 }
3088 }
3089 });
3090 }
Winson Chung83892cc2013-05-01 16:53:33 -07003091
Sunny Goyal4390ace2014-10-13 11:33:11 -07003092 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003093 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003094 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3095 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3096 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3097
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003098 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003099 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003100 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003101 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3102 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003103 boolean infoUpdated = false;
3104 boolean shortcutUpdated = false;
3105
3106 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003107 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003108 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003109 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3110 si.iconResource.resourceName, mIconCache, context);
3111 if (icon != null) {
3112 si.setIcon(icon);
3113 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003114 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003115 }
3116 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003117
3118 ComponentName cn = si.getTargetComponent();
3119 if (cn != null && packageSet.contains(cn.getPackageName())) {
3120 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3121
3122 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003123 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3124 // Auto install icon
3125 PackageManager pm = context.getPackageManager();
3126 ResolveInfo matched = pm.resolveActivity(
3127 new Intent(Intent.ACTION_MAIN)
3128 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3129 PackageManager.MATCH_DEFAULT_ONLY);
3130 if (matched == null) {
3131 // Try to find the best match activity.
3132 Intent intent = pm.getLaunchIntentForPackage(
3133 cn.getPackageName());
3134 if (intent != null) {
3135 cn = intent.getComponent();
3136 appInfo = addedOrUpdatedApps.get(cn);
3137 }
3138
3139 if ((intent == null) || (appInfo == null)) {
3140 removedShortcuts.add(si);
3141 continue;
3142 }
3143 si.promisedIntent = intent;
3144 }
3145 }
3146
3147 // Restore the shortcut.
3148 si.intent = si.promisedIntent;
3149 si.promisedIntent = null;
3150 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3151 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3152 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3153
3154 infoUpdated = true;
3155 si.updateIcon(mIconCache);
3156 }
3157
3158 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3159 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3160 si.updateIcon(mIconCache);
3161 si.title = appInfo.title.toString();
3162 si.contentDescription = appInfo.contentDescription;
3163 infoUpdated = true;
3164 }
3165
3166 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3167 // Since package was just updated, the target must be available now.
3168 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3169 shortcutUpdated = true;
3170 }
3171 }
3172
3173 if (infoUpdated || shortcutUpdated) {
3174 updatedShortcuts.add(si);
3175 }
3176 if (infoUpdated) {
3177 updateItemInDatabase(context, si);
3178 }
3179 } else if (info instanceof LauncherAppWidgetInfo) {
3180 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3181 if (mUser.equals(widgetInfo.user)
3182 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3183 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3184 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3185 widgets.add(widgetInfo);
3186 updateItemInDatabase(context, widgetInfo);
3187 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003188 }
3189 }
3190 }
3191
Sunny Goyal4390ace2014-10-13 11:33:11 -07003192 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3193 mHandler.post(new Runnable() {
3194
3195 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003196 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003197 if (callbacks == cb && cb != null) {
3198 callbacks.bindShortcutsChanged(
3199 updatedShortcuts, removedShortcuts, mUser);
3200 }
3201 }
3202 });
3203 if (!removedShortcuts.isEmpty()) {
3204 deleteItemsFromDatabase(context, removedShortcuts);
3205 }
3206 }
3207 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003208 mHandler.post(new Runnable() {
3209 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003210 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003211 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003212 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003213 }
3214 }
3215 });
3216 }
3217 }
3218
Winson Chungdf95eb12013-10-16 14:57:07 -07003219 final ArrayList<String> removedPackageNames =
3220 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003221 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003222 // Mark all packages in the broadcast to be removed
3223 removedPackageNames.addAll(Arrays.asList(packages));
3224 } else if (mOp == OP_UPDATE) {
3225 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003226 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003227 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003228 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003229 }
3230 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003231 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003232
Winson Chungdf95eb12013-10-16 14:57:07 -07003233 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003234 final int removeReason;
3235 if (mOp == OP_UNAVAILABLE) {
3236 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3237 } else {
3238 // Remove all the components associated with this package
3239 for (String pn : removedPackageNames) {
3240 deletePackageFromDatabase(context, pn, mUser);
3241 }
3242 // Remove all the specific components
3243 for (AppInfo a : removedApps) {
3244 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3245 deleteItemsFromDatabase(context, infos);
3246 }
3247 removeReason = 0;
3248 }
3249
Winson Chungdf95eb12013-10-16 14:57:07 -07003250 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003251 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003252 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003253 mHandler.post(new Runnable() {
3254 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003255 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003256 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003257 callbacks.bindComponentsRemoved(
3258 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003259 }
3260 }
3261 });
Joe Onoratobe386092009-11-17 17:32:16 -08003262 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003263
Michael Jurkac402cd92013-05-20 15:49:32 +02003264 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003265 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003266 mHandler.post(new Runnable() {
3267 @Override
3268 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003269 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003270 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003271 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003272 }
3273 }
3274 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003275
3276 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003277 mHandler.post(new Runnable() {
3278 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003279 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003280 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003281 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003282 }
3283 }
3284 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003285 }
3286 }
3287
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003288 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3289 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003290 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003291 if (sBgWidgetProviders == null || refresh) {
3292 sBgWidgetProviders = new HashMap<>();
3293 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3294 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003295
Robin Lee26ace122015-03-16 19:41:43 +00003296 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3297 for (AppWidgetProviderInfo pInfo : widgets) {
3298 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3299 UserHandleCompat user = wm.getUser(info);
3300 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3301 }
3302
3303 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3304 for (CustomAppWidget widget : customWidgets) {
3305 info = new LauncherAppWidgetProviderInfo(context, widget);
3306 UserHandleCompat user = wm.getUser(info);
3307 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3308 }
Adam Cohen59400422014-03-05 18:07:04 -08003309 }
Adam Cohen59400422014-03-05 18:07:04 -08003310 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3311 }
3312 }
3313
Robin Lee26ace122015-03-16 19:41:43 +00003314 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3315 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003316 synchronized (sBgLock) {
3317 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003318 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003319 }
Robin Lee26ace122015-03-16 19:41:43 +00003320 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003321 }
3322 }
3323
Winson Chungb745afb2015-03-02 11:51:23 -08003324 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003325 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003326 PackageManager packageManager = context.getPackageManager();
3327 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003328 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003329 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3330 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003331 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003332 return widgetsAndShortcuts;
3333 }
3334
Adam Cohen091440a2015-03-18 14:16:05 -07003335 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003336 UserHandleCompat user) {
3337 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3338 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003339 }
Adam Cohen556f6132014-01-15 15:18:08 -08003340
Kenny Guyed131872014-04-30 03:02:21 +01003341 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3342 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003343 if (cn == null) {
3344 return false;
3345 }
Kenny Guyed131872014-04-30 03:02:21 +01003346 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3347 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003348 return false;
3349 }
Kenny Guyed131872014-04-30 03:02:21 +01003350 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003351 }
3352
Adam Cohena28b78e2014-05-20 17:03:04 -07003353 public static boolean isValidPackage(Context context, String packageName,
3354 UserHandleCompat user) {
3355 if (packageName == null) {
3356 return false;
3357 }
3358 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3359 return launcherApps.isPackageEnabledForProfile(packageName, user);
3360 }
3361
Joe Onorato9c1289c2009-08-17 11:03:03 -04003362 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003363 * Make an ShortcutInfo object for a restored application or shortcut item that points
3364 * to a package that is not yet installed on the system.
3365 */
Sunny Goyal34942622014-08-29 17:20:55 -07003366 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003367 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003368 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003369 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003370 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003371
3372 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3373 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3374 if (!TextUtils.isEmpty(title)) {
3375 info.title = title;
3376 }
3377 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3378 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3379 if (TextUtils.isEmpty(info.title)) {
3380 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3381 }
3382 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3383 } else {
3384 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3385 }
3386
Kenny Guyc2bd8102014-06-30 12:30:31 +01003387 info.contentDescription = mUserManager.getBadgedLabelForUser(
3388 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003389 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003390 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003391 return info;
3392 }
3393
3394 /**
3395 * Make an Intent object for a restored application or shortcut item that points
3396 * to the market page for the item.
3397 */
Adam Cohen091440a2015-03-18 14:16:05 -07003398 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003399 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003400 return getMarketIntent(componentName.getPackageName());
3401 }
3402
3403 static Intent getMarketIntent(String packageName) {
3404 return new Intent(Intent.ACTION_VIEW)
3405 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003406 .scheme("market")
3407 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003408 .appendQueryParameter("id", packageName)
3409 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003410 }
3411
3412 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003413 * Make an ShortcutInfo object for a shortcut that is an application.
3414 *
3415 * If c is not null, then it will be used to fill in missing data like the title and icon.
3416 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003417 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003418 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003419 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003420 if (user == null) {
3421 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003422 return null;
3423 }
3424
Kenny Guyed131872014-04-30 03:02:21 +01003425 ComponentName componentName = intent.getComponent();
3426 if (componentName == null) {
3427 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3428 return null;
3429 }
3430
3431 Intent newIntent = new Intent(intent.getAction(), null);
3432 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3433 newIntent.setComponent(componentName);
3434 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003435 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003436 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3437 return null;
3438 }
3439
3440 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003441 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003442 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3443 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3444 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003445 }
3446
Joe Onorato56d82912010-03-07 14:32:10 -05003447 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003448 if (TextUtils.isEmpty(info.title) && c != null) {
3449 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003450 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003451
Joe Onorato56d82912010-03-07 14:32:10 -05003452 // fall back to the class name of the activity
3453 if (info.title == null) {
3454 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003455 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003456
Joe Onorato9c1289c2009-08-17 11:03:03 -04003457 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003458 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003459 info.contentDescription = mUserManager.getBadgedLabelForUser(
3460 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003461 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003462 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003463
Winson Chung64359a52013-07-08 17:17:08 -07003464 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3465 ItemInfoFilter f) {
3466 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3467 for (ItemInfo i : infos) {
3468 if (i instanceof ShortcutInfo) {
3469 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003470 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003471 if (cn != null && f.filterItem(null, info, cn)) {
3472 filtered.add(info);
3473 }
3474 } else if (i instanceof FolderInfo) {
3475 FolderInfo info = (FolderInfo) i;
3476 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003477 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003478 if (cn != null && f.filterItem(info, s, cn)) {
3479 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003480 }
3481 }
Winson Chung64359a52013-07-08 17:17:08 -07003482 } else if (i instanceof LauncherAppWidgetInfo) {
3483 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3484 ComponentName cn = info.providerName;
3485 if (cn != null && f.filterItem(null, info, cn)) {
3486 filtered.add(info);
3487 }
Winson Chung8a435102012-08-30 17:16:53 -07003488 }
3489 }
Winson Chung64359a52013-07-08 17:17:08 -07003490 return new ArrayList<ItemInfo>(filtered);
3491 }
3492
Adam Cohen091440a2015-03-18 14:16:05 -07003493 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003494 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003495 ItemInfoFilter filter = new ItemInfoFilter() {
3496 @Override
3497 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003498 if (info.user == null) {
3499 return cn.equals(cname);
3500 } else {
3501 return cn.equals(cname) && info.user.equals(user);
3502 }
Winson Chung64359a52013-07-08 17:17:08 -07003503 }
3504 };
3505 return filterItemInfos(sBgItemsIdMap.values(), filter);
3506 }
3507
Sunny Goyal1a745e82014-10-02 15:58:31 -07003508 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003509 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003510 */
Adam Cohen091440a2015-03-18 14:16:05 -07003511 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003512 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3513 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003514
Joe Onorato56d82912010-03-07 14:32:10 -05003515 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003516 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003517 // Non-app shortcuts are only supported for current user.
3518 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003519 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003520
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003521 // TODO: If there's an explicit component and we can't install that, delete it.
3522
Joe Onorato56d82912010-03-07 14:32:10 -05003523 info.title = c.getString(titleIndex);
3524
Joe Onorato9c1289c2009-08-17 11:03:03 -04003525 int iconType = c.getInt(iconTypeIndex);
3526 switch (iconType) {
3527 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3528 String packageName = c.getString(iconPackageIndex);
3529 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003530 info.customIcon = false;
3531 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003532 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003533 // the db
3534 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003535 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003536 }
3537 // the fallback icon
3538 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003539 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003540 info.usingFallbackIcon = true;
3541 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003542 break;
3543 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003544 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003545 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003546 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003547 info.customIcon = false;
3548 info.usingFallbackIcon = true;
3549 } else {
3550 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003551 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003552 break;
3553 default:
Kenny Guyed131872014-04-30 03:02:21 +01003554 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003555 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003556 info.customIcon = false;
3557 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003558 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003559 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003560 return info;
3561 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003562
Sunny Goyal2350bc92014-10-14 16:42:54 -07003563 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003564 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3565 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3566 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3567
Adam Cohend9198822011-11-22 16:42:47 -08003568 if (intent == null) {
3569 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3570 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3571 return null;
3572 }
3573
Joe Onorato0589f0f2010-02-08 13:44:00 -08003574 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003575 boolean customIcon = false;
3576 ShortcutIconResource iconResource = null;
3577
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003578 if (bitmap instanceof Bitmap) {
3579 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003580 customIcon = true;
3581 } else {
3582 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003583 if (extra instanceof ShortcutIconResource) {
3584 iconResource = (ShortcutIconResource) extra;
3585 icon = Utilities.createIconBitmap(iconResource.packageName,
3586 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003587 }
3588 }
3589
Michael Jurkac9d95c52011-08-29 14:03:34 -07003590 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003591
Kenny Guyed131872014-04-30 03:02:21 +01003592 // Only support intents for current user for now. Intents sent from other
3593 // users wouldn't get here without intent forwarding anyway.
3594 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003595 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003596 icon = mIconCache.getDefaultIcon(info.user);
3597 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003598 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003599 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003600
Joe Onorato0589f0f2010-02-08 13:44:00 -08003601 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003602 info.contentDescription = mUserManager.getBadgedLabelForUser(
3603 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003604 info.intent = intent;
3605 info.customIcon = customIcon;
3606 info.iconResource = iconResource;
3607
3608 return info;
3609 }
3610
Joe Onorato9c1289c2009-08-17 11:03:03 -04003611 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003612 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003613 * or make a new one.
3614 */
Adam Cohen091440a2015-03-18 14:16:05 -07003615 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003616 // See if a placeholder was created for us already
3617 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003618 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003619 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003620 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003621 folders.put(id, folderInfo);
3622 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003623 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003624 }
3625
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003626 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003627 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003628 return new Comparator<AppInfo>() {
3629 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003630 if (a.user.equals(b.user)) {
3631 int result = collator.compare(a.title.toString().trim(),
3632 b.title.toString().trim());
3633 if (result == 0) {
3634 result = a.componentName.compareTo(b.componentName);
3635 }
3636 return result;
3637 } else {
3638 // TODO Need to figure out rules for sorting
3639 // profiles, this puts work second.
3640 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003641 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003642 }
Winson Chung11904872012-09-17 16:58:46 -07003643 };
3644 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003645 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3646 = new Comparator<AppInfo>() {
3647 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003648 if (a.firstInstallTime < b.firstInstallTime) return 1;
3649 if (a.firstInstallTime > b.firstInstallTime) return -1;
3650 return 0;
3651 }
3652 };
Winson Chung5308f242011-08-18 12:12:41 -07003653 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3654 if (info.activityInfo != null) {
3655 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3656 } else {
3657 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3658 }
3659 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003660
Winson Chung1ed747a2011-05-03 16:18:34 -07003661 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003662 private final AppWidgetManagerCompat mManager;
3663 private final PackageManager mPackageManager;
3664 private final HashMap<Object, String> mLabelCache;
3665 private final Collator mCollator;
3666
3667 WidgetAndShortcutNameComparator(Context context) {
3668 mManager = AppWidgetManagerCompat.getInstance(context);
3669 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003670 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003671 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003672 }
3673 public final int compare(Object a, Object b) {
3674 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003675 if (mLabelCache.containsKey(a)) {
3676 labelA = mLabelCache.get(a);
3677 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003678 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3679 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003680 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003681 mLabelCache.put(a, labelA);
3682 }
3683 if (mLabelCache.containsKey(b)) {
3684 labelB = mLabelCache.get(b);
3685 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003686 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003687 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003688 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003689 mLabelCache.put(b, labelB);
3690 }
Winson Chung11904872012-09-17 16:58:46 -07003691 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003692 }
3693 };
Joe Onoratobe386092009-11-17 17:32:16 -08003694
Sunny Goyal651077b2014-06-30 14:15:31 -07003695 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3696 return (provider != null) && (provider.provider != null)
3697 && (provider.provider.getPackageName() != null);
3698 }
3699
Joe Onoratobe386092009-11-17 17:32:16 -08003700 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003701 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003702 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3703 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3704 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3705 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003706 if (mLoaderTask != null) {
3707 mLoaderTask.dumpState();
3708 } else {
3709 Log.d(TAG, "mLoaderTask=null");
3710 }
Joe Onoratobe386092009-11-17 17:32:16 -08003711 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003712
3713 public Callbacks getCallback() {
3714 return mCallbacks != null ? mCallbacks.get() : null;
3715 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003716}