blob: 1e16bafe8822bb901826f25c381e0f369cb665ee [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040086 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070087 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080088 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040089
Joe Onorato9c1289c2009-08-17 11:03:03 -040090 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070091
Dan Sandlerd5024042014-01-09 15:01:33 -050092 public static final int LOADER_FLAG_NONE = 0;
93 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
94 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
95
Joe Onorato36115782010-06-17 13:28:48 -040096 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050097 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080098
Winson Chungee055712013-07-30 14:46:24 -070099 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800100 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400101
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400102 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400103 private final Object mLock = new Object();
104 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400105 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700106 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
Sunny Goyale0f58d72014-11-10 18:05:31 -0800108 /**
109 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
110 */
111 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
112
Winson Chung81b52252012-08-27 15:34:29 -0700113 // Specific runnable types that are run on the main thread deferred handler, this allows us to
114 // clear all queued binding runnables when the Launcher activity is destroyed.
115 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
116 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
117
Jason Monkbbe1e242014-05-16 17:37:34 -0400118 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700119
Sunny Goyal34b65272015-03-11 16:56:52 -0700120 static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700121 static {
122 sWorkerThread.start();
123 }
124 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
125
Joe Onoratocc67f472010-06-08 10:54:30 -0700126 // We start off with everything not loaded. After that, we assume that
127 // our monitoring of the package manager provides all updates and we never
128 // need to do a requery. These are only ever touched from the loader thread.
129 private boolean mWorkspaceLoaded;
130 private boolean mAllAppsLoaded;
131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // When we are loading pages synchronously, we can't just post the binding of items on the side
133 // pages as this delays the rotation process. Instead, we wait for a callback from the first
134 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
135 // a normal load, we also clear this set of Runnables.
136 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
137
Joe Onorato9c1289c2009-08-17 11:03:03 -0400138 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700141 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800142
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700143 // The lock that must be acquired before referencing any static bg data structures. Unlike
144 // other locks, this one can generally be held long-term because we never expect any of these
145 // static data structures to be referenced outside of the worker thread except on the first
146 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700147 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
154 // created by LauncherModel that are directly on the home screen (however, no widgets or
155 // shortcuts within folders).
156 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
159 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 new ArrayList<LauncherAppWidgetInfo>();
161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
163 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700164
Adam Cohendcd297f2013-06-18 13:13:40 -0700165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Adam Cohen59400422014-03-05 18:07:04 -0800168 // sBgWidgetProviders is the set of widget providers including custom internal widgets
169 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800170
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700172 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
173 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700174
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 // </ only access in worker thread >
176
177 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
Reena Lee99a73f32011-10-24 17:27:37 -0700179 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700180
Kenny Guyed131872014-04-30 03:02:21 +0100181 private final LauncherAppsCompat mLauncherApps;
182 private final UserManagerCompat mUserManager;
183
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700185 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public int getCurrentWorkspaceScreen();
187 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
189 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700190 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700191 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500192 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800193 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400194 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200195 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700196 public void bindAppsAdded(ArrayList<Long> newScreens,
197 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700198 ArrayList<ItemInfo> addAnimated,
199 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200200 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700201 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
202 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
203 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700204 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700205 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700206 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700207 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200208 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100209 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700210 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700211 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700212 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800213 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
214 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400215 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
Winson Chung64359a52013-07-08 17:17:08 -0700217 public interface ItemInfoFilter {
218 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
219 }
220
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800221 public interface ScreenPosProvider {
222 int getScreenIndex(ArrayList<Long> screenIDs);
223 }
224
Bjorn Bringert1307f632013-10-03 22:31:03 +0100225 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800226 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400227
Winson Chungee055712013-07-30 14:46:24 -0700228 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700229 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400230 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
231 // resource string.
232 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
233 ProviderInfo providerInfo =
234 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
235 ProviderInfo redirectProvider =
236 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700237
238 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400239 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700240
241 if (mOldContentProviderExists) {
242 Log.d(TAG, "Old launcher provider exists.");
243 } else {
244 Log.d(TAG, "Old launcher provider does not exist.");
245 }
246
Daniel Sandlere4f98912013-06-25 15:13:26 -0400247 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100248 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800249 mIconCache = iconCache;
250
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400251 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700252 Configuration config = res.getConfiguration();
253 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100254 mLauncherApps = LauncherAppsCompat.getInstance(context);
255 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800256 }
257
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700258 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
259 * posted on the main thread handler. */
260 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700261 runOnMainThread(r, 0);
262 }
263 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700264 if (sWorkerThread.getThreadId() == Process.myTid()) {
265 // If we are on the worker thread, post onto the main handler
266 mHandler.post(r);
267 } else {
268 r.run();
269 }
270 }
271
272 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
273 * posted on the worker thread handler. */
274 private static void runOnWorkerThread(Runnable r) {
275 if (sWorkerThread.getThreadId() == Process.myTid()) {
276 r.run();
277 } else {
278 // If we are not on the worker thread, then post to the worker handler
279 sWorker.post(r);
280 }
281 }
282
Winson Chunge43a1e72014-01-15 10:33:02 -0800283 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
284 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800285 }
286
Sunny Goyale755d462014-07-22 13:48:29 -0700287 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500288 // Process the updated package state
289 Runnable r = new Runnable() {
290 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800291 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500292 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700293 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500294 }
295 }
296 };
297 mHandler.post(r);
298 }
299
Sunny Goyala22666f2014-09-18 13:25:15 -0700300 public void updatePackageBadge(final String packageName) {
301 // Process the updated package badge
302 Runnable r = new Runnable() {
303 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800304 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700305 if (callbacks != null) {
306 callbacks.updatePackageBadge(packageName);
307 }
308 }
309 };
310 mHandler.post(r);
311 }
312
Adam Cohen76a47a12014-02-05 11:47:43 -0800313 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800314 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800315
316 if (allAppsApps == null) {
317 throw new RuntimeException("allAppsApps must not be null");
318 }
319 if (allAppsApps.isEmpty()) {
320 return;
321 }
322
323 // Process the newly added applications and add them to the database first
324 Runnable r = new Runnable() {
325 public void run() {
326 runOnMainThread(new Runnable() {
327 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800328 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800329 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500330 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800331 }
332 }
333 });
334 }
335 };
336 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700337 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800338
339 public void addAndBindAddedWorkspaceApps(final Context context,
340 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800341 addAndBindAddedWorkspaceApps(context, workspaceApps,
342 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800343
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800344 @Override
345 public int getScreenIndex(ArrayList<Long> screenIDs) {
346 return screenIDs.isEmpty() ? 0 : 1;
347 }
348 }, 1, false);
349 }
350
351 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
352 int[] xy, int spanX, int spanY) {
353 LauncherAppState app = LauncherAppState.getInstance();
354 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
355 final int xCount = (int) grid.numColumns;
356 final int yCount = (int) grid.numRows;
357 boolean[][] occupied = new boolean[xCount][yCount];
358 if (occupiedPos != null) {
359 for (Rect r : occupiedPos) {
360 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
361 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
362 occupied[x][y] = true;
363 }
364 }
365 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800366 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800367 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
368 }
369
370 /**
371 * Find a position on the screen for the given size or adds a new screen.
372 * @return screenId and the coordinates for the item.
373 */
374 private static Pair<Long, int[]> findSpaceForItem(
375 Context context,
376 ScreenPosProvider preferredScreen,
377 int fallbackStartScreen,
378 ArrayList<Long> workspaceScreens,
379 ArrayList<Long> addedWorkspaceScreensFinal,
380 int spanX, int spanY) {
381 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
382 // loadWorkspace() may not have been called.
383 final ContentResolver cr = context.getContentResolver();
384 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
385 new String[] {
386 LauncherSettings.Favorites.SCREEN,
387 LauncherSettings.Favorites.CELLX,
388 LauncherSettings.Favorites.CELLY,
389 LauncherSettings.Favorites.SPANX,
390 LauncherSettings.Favorites.SPANY,
391 LauncherSettings.Favorites.CONTAINER
392 },
393 "container=?",
394 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
395 null);
396
397 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
398 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
399 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
400 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
401 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
402 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
403 try {
404 while (c.moveToNext()) {
405 Rect rect = new Rect();
406 rect.left = c.getInt(cellXIndex);
407 rect.top = c.getInt(cellYIndex);
408 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
409 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
410
411 long screenId = c.getInt(screenIndex);
412 ArrayList<Rect> items = screenItems.get(screenId);
413 if (items == null) {
414 items = new ArrayList<Rect>();
415 screenItems.put(screenId, items);
416 }
417 items.add(rect);
418 }
419 } catch (Exception e) {
420 screenItems.clear();
421 } finally {
422 c.close();
423 }
424
425 // Find appropriate space for the item.
426 long screenId = 0;
427 int[] cordinates = new int[2];
428 boolean found = false;
429
430 int screenCount = workspaceScreens.size();
431 // First check the preferred screen.
432 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
433 if (preferredScreenIndex < screenCount) {
434 screenId = workspaceScreens.get(preferredScreenIndex);
435 found = findNextAvailableIconSpaceInScreen(
436 screenItems.get(screenId), cordinates, spanX, spanY);
437 }
438
439 if (!found) {
440 // Search on any of the screens.
441 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
442 screenId = workspaceScreens.get(screen);
443 if (findNextAvailableIconSpaceInScreen(
444 screenItems.get(screenId), cordinates, spanX, spanY)) {
445 // We found a space for it
446 found = true;
447 break;
448 }
449 }
450 }
451
452 if (!found) {
453 // Still no position found. Add a new screen to the end.
454 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
455
456 // Save the screen id for binding in the workspace
457 workspaceScreens.add(screenId);
458 addedWorkspaceScreensFinal.add(screenId);
459
460 // If we still can't find an empty space, then God help us all!!!
461 if (!findNextAvailableIconSpaceInScreen(
462 screenItems.get(screenId), cordinates, spanX, spanY)) {
463 throw new RuntimeException("Can't find space to add the item");
464 }
465 }
466 return Pair.create(screenId, cordinates);
467 }
468
469 /**
470 * Adds the provided items to the workspace.
471 * @param preferredScreen the screen where we should try to add the app first
472 * @param fallbackStartScreen the screen to start search for empty space if
473 * preferredScreen is not available.
474 */
475 public void addAndBindPendingItem(
476 final Context context,
477 final PendingAddItemInfo addInfo,
478 final ScreenPosProvider preferredScreen,
479 final int fallbackStartScreen) {
480 final Callbacks callbacks = getCallback();
481 // Process the newly added applications and add them to the database first
482 Runnable r = new Runnable() {
483 public void run() {
484 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800485 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800486
487 // Find appropriate space for the item.
488 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
489 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
490 addInfo.spanX,
491 addInfo.spanY);
492 final long screenId = coords.first;
493 final int[] cordinates = coords.second;
494
495 // Update the workspace screens
496 updateWorkspaceScreenOrder(context, workspaceScreens);
497 runOnMainThread(new Runnable() {
498 public void run() {
499 Callbacks cb = getCallback();
500 if (callbacks == cb && cb != null) {
501 cb.bindAddScreens(addedWorkspaceScreensFinal);
502 cb.bindAddPendingItem(addInfo,
503 LauncherSettings.Favorites.CONTAINER_DESKTOP,
504 screenId, cordinates, addInfo.spanX, addInfo.spanY);
505 }
506 }
507 });
508 }
509 };
510 runOnWorkerThread(r);
511 }
512
513 /**
514 * Adds the provided items to the workspace.
515 * @param preferredScreen the screen where we should try to add the app first
516 * @param fallbackStartScreen the screen to start search for empty space if
517 * preferredScreen is not available.
518 */
519 public void addAndBindAddedWorkspaceApps(final Context context,
520 final ArrayList<ItemInfo> workspaceApps,
521 final ScreenPosProvider preferredScreen,
522 final int fallbackStartScreen,
523 final boolean allowDuplicate) {
524 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800525 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700526 return;
Winson Chung997a9232013-07-24 15:33:46 -0700527 }
Winson Chung64359a52013-07-08 17:17:08 -0700528 // Process the newly added applications and add them to the database first
529 Runnable r = new Runnable() {
530 public void run() {
531 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
532 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
533
Winson Chung76828c82013-08-19 15:43:29 -0700534 // Get the list of workspace screens. We need to append to this list and
535 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
536 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800537 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700538 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800539 for (ItemInfo item : workspaceApps) {
540 if (!allowDuplicate) {
541 // Short-circuit this logic if the icon exists somewhere on the workspace
542 if (shortcutExists(context, item.title.toString(),
543 item.getIntent(), item.user)) {
544 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700545 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800546 }
Winson Chung76828c82013-08-19 15:43:29 -0700547
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800548 // Find appropriate space for the item.
549 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
550 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
551 1, 1);
552 long screenId = coords.first;
553 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700554
Winson Chung997a9232013-07-24 15:33:46 -0700555 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800556 if (item instanceof ShortcutInfo) {
557 shortcutInfo = (ShortcutInfo) item;
558 } else if (item instanceof AppInfo) {
559 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700560 } else {
561 throw new RuntimeException("Unexpected info type");
562 }
Winson Chung94d67682013-09-25 16:29:40 -0700563
Winson Chung64359a52013-07-08 17:17:08 -0700564 // Add the shortcut to the db
565 addItemToDatabase(context, shortcutInfo,
566 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800567 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700568 // Save the ShortcutInfo for binding in the workspace
569 addedShortcutsFinal.add(shortcutInfo);
570 }
571 }
572
Winson Chung76828c82013-08-19 15:43:29 -0700573 // Update the workspace screens
574 updateWorkspaceScreenOrder(context, workspaceScreens);
575
Adam Cohen76a47a12014-02-05 11:47:43 -0800576 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700577 runOnMainThread(new Runnable() {
578 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800579 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700580 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700581 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
582 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700583 if (!addedShortcutsFinal.isEmpty()) {
584 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
585 long lastScreenId = info.screenId;
586 for (ItemInfo i : addedShortcutsFinal) {
587 if (i.screenId == lastScreenId) {
588 addAnimated.add(i);
589 } else {
590 addNotAnimated.add(i);
591 }
Winson Chung997a9232013-07-24 15:33:46 -0700592 }
593 }
Winson Chungd64d1762013-08-20 14:37:16 -0700594 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800595 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700596 }
Winson Chung64359a52013-07-08 17:17:08 -0700597 }
Winson Chung997a9232013-07-24 15:33:46 -0700598 });
599 }
Winson Chung64359a52013-07-08 17:17:08 -0700600 }
601 };
602 runOnWorkerThread(r);
603 }
604
Winson Chung81b52252012-08-27 15:34:29 -0700605 public void unbindItemInfosAndClearQueuedBindRunnables() {
606 if (sWorkerThread.getThreadId() == Process.myTid()) {
607 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
608 "main thread");
609 }
610
611 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400612 synchronized (mDeferredBindRunnables) {
613 mDeferredBindRunnables.clear();
614 }
Winson Chung81b52252012-08-27 15:34:29 -0700615 // Remove any queued bind runnables
616 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
617 // Unbind all the workspace items
618 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700619 }
620
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700621 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700622 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700623 // Ensure that we don't use the same workspace items data structure on the main thread
624 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700625 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
626 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700627 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700628 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
629 tmpAppWidgets.addAll(sBgAppWidgets);
630 }
631 Runnable r = new Runnable() {
632 @Override
633 public void run() {
634 for (ItemInfo item : tmpWorkspaceItems) {
635 item.unbind();
636 }
637 for (ItemInfo item : tmpAppWidgets) {
638 item.unbind();
639 }
640 }
641 };
642 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700643 }
644
Joe Onorato9c1289c2009-08-17 11:03:03 -0400645 /**
646 * Adds an item to the DB if it was not created previously, or move it to a new
647 * <container, screen, cellX, cellY>
648 */
649 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700650 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400651 if (item.container == ItemInfo.NO_ID) {
652 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400654 } else {
655 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700656 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800657 }
658 }
659
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700660 static void checkItemInfoLocked(
661 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
662 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
663 if (modelItem != null && item != modelItem) {
664 // check all the data is consistent
665 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
666 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
667 ShortcutInfo shortcut = (ShortcutInfo) item;
668 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
669 modelShortcut.intent.filterEquals(shortcut.intent) &&
670 modelShortcut.id == shortcut.id &&
671 modelShortcut.itemType == shortcut.itemType &&
672 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700673 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700674 modelShortcut.cellX == shortcut.cellX &&
675 modelShortcut.cellY == shortcut.cellY &&
676 modelShortcut.spanX == shortcut.spanX &&
677 modelShortcut.spanY == shortcut.spanY &&
678 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
679 (modelShortcut.dropPos != null &&
680 shortcut.dropPos != null &&
681 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
682 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
683 // For all intents and purposes, this is the same object
684 return;
685 }
686 }
687
688 // the modelItem needs to match up perfectly with item if our model is
689 // to be consistent with the database-- for now, just require
690 // modelItem == item or the equality check above
691 String msg = "item: " + ((item != null) ? item.toString() : "null") +
692 "modelItem: " +
693 ((modelItem != null) ? modelItem.toString() : "null") +
694 "Error: ItemInfo passed to checkItemInfo doesn't match original";
695 RuntimeException e = new RuntimeException(msg);
696 if (stackTrace != null) {
697 e.setStackTrace(stackTrace);
698 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800699 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700700 }
701 }
702
Michael Jurka816474f2012-06-25 14:49:02 -0700703 static void checkItemInfo(final ItemInfo item) {
704 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
705 final long itemId = item.id;
706 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700707 public void run() {
708 synchronized (sBgLock) {
709 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700710 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700711 }
712 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700713 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700714 }
715
Michael Jurkac9d95c52011-08-29 14:03:34 -0700716 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
717 final ItemInfo item, final String callingFunction) {
718 final long itemId = item.id;
719 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
720 final ContentResolver cr = context.getContentResolver();
721
Adam Cohen487f7dd2012-06-28 18:12:10 -0700722 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700723 Runnable r = new Runnable() {
724 public void run() {
725 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700726 updateItemArrays(item, itemId, stackTrace);
727 }
728 };
729 runOnWorkerThread(r);
730 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700731
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700732 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
733 final ArrayList<ItemInfo> items, final String callingFunction) {
734 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700735
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700736 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
737 Runnable r = new Runnable() {
738 public void run() {
739 ArrayList<ContentProviderOperation> ops =
740 new ArrayList<ContentProviderOperation>();
741 int count = items.size();
742 for (int i = 0; i < count; i++) {
743 ItemInfo item = items.get(i);
744 final long itemId = item.id;
745 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
746 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700747
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700748 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
749 updateItemArrays(item, itemId, stackTrace);
750
751 }
752 try {
753 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
754 } catch (Exception e) {
755 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700756 }
757 }
758 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700759 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700760 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700761
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700762 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
763 // Lock on mBgLock *after* the db operation
764 synchronized (sBgLock) {
765 checkItemInfoLocked(itemId, item, stackTrace);
766
767 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
768 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
769 // Item is in a folder, make sure this folder exists
770 if (!sBgFolders.containsKey(item.container)) {
771 // An items container is being set to a that of an item which is not in
772 // the list of Folders.
773 String msg = "item: " + item + " container being set to: " +
774 item.container + ", not in the list of folders";
775 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700776 }
777 }
778
779 // Items are added/removed from the corresponding FolderInfo elsewhere, such
780 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
781 // that are on the desktop, as appropriate
782 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800783 if (modelItem != null &&
784 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
785 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700786 switch (modelItem.itemType) {
787 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
788 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
789 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
790 if (!sBgWorkspaceItems.contains(modelItem)) {
791 sBgWorkspaceItems.add(modelItem);
792 }
793 break;
794 default:
795 break;
796 }
797 } else {
798 sBgWorkspaceItems.remove(modelItem);
799 }
800 }
801 }
802
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800803 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400804 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700805 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700806 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400808 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 item.cellX = cellX;
810 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700811
Winson Chung3d503fb2011-07-13 17:25:49 -0700812 // We store hotseat items in canonical form which is this orientation invariant position
813 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700815 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700817 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700818 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700819 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400820
821 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400822 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700823 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
824 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800825 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700826 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400827
Michael Jurkac9d95c52011-08-29 14:03:34 -0700828 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700829 }
830
831 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700832 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
833 * cellX, cellY have already been updated on the ItemInfos.
834 */
835 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
836 final long container, final int screen) {
837
838 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
839 int count = items.size();
840
841 for (int i = 0; i < count; i++) {
842 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700843 item.container = container;
844
845 // We store hotseat items in canonical form which is this orientation invariant position
846 // in the hotseat
847 if (context instanceof Launcher && screen < 0 &&
848 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700849 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700850 item.cellY);
851 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700852 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700853 }
854
855 final ContentValues values = new ContentValues();
856 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
857 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
858 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800859 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700860 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700861
862 contentValues.add(values);
863 }
864 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
865 }
866
867 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700868 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800869 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700870 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700871 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700872 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800873 item.cellX = cellX;
874 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700875 item.spanX = spanX;
876 item.spanY = spanY;
877
878 // We store hotseat items in canonical form which is this orientation invariant position
879 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700880 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700881 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700882 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700884 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700885 }
Adam Cohend4844c32011-02-18 19:25:06 -0800886
Adam Cohend4844c32011-02-18 19:25:06 -0800887 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800888 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700889 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
890 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800891 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700892 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
893 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700894 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800895
Michael Jurka816474f2012-06-25 14:49:02 -0700896 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700897 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700898
899 /**
900 * Update an item to the database in a specified container.
901 */
902 static void updateItemInDatabase(Context context, final ItemInfo item) {
903 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100904 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700905 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800906 }
907
908 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400909 * Returns true if the shortcuts already exists in the database.
910 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800911 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800912 static boolean shortcutExists(Context context, String title, Intent intent,
913 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400914 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700915 final Intent intentWithPkg, intentWithoutPkg;
916
917 if (intent.getComponent() != null) {
918 // If component is not null, an intent with null package will produce
919 // the same result and should also be a match.
920 if (intent.getPackage() != null) {
921 intentWithPkg = intent;
922 intentWithoutPkg = new Intent(intent).setPackage(null);
923 } else {
924 intentWithPkg = new Intent(intent).setPackage(
925 intent.getComponent().getPackageName());
926 intentWithoutPkg = intent;
927 }
928 } else {
929 intentWithPkg = intent;
930 intentWithoutPkg = intent;
931 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800932 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
933 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400934 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800935 new String[] { "title", "intent", "profileId" },
936 "title=? and (intent=? or intent=?) and profileId=?",
937 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
938 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400939 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800940 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400941 } finally {
942 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700944 }
945
Joe Onorato9c1289c2009-08-17 11:03:03 -0400946 /**
947 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
948 */
949 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
950 final ContentResolver cr = context.getContentResolver();
951 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
952 "_id=? and (itemType=? or itemType=?)",
953 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700954 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700955
Joe Onorato9c1289c2009-08-17 11:03:03 -0400956 try {
957 if (c.moveToFirst()) {
958 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
959 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
960 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
961 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
962 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
963 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700964 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800965
Joe Onorato9c1289c2009-08-17 11:03:03 -0400966 FolderInfo folderInfo = null;
967 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700968 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
969 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400970 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700971 }
972
Joe Onorato9c1289c2009-08-17 11:03:03 -0400973 folderInfo.title = c.getString(titleIndex);
974 folderInfo.id = id;
975 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700976 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700977 folderInfo.cellX = c.getInt(cellXIndex);
978 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700979 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980
981 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700982 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400983 } finally {
984 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700985 }
986
987 return null;
988 }
989
Joe Onorato9c1289c2009-08-17 11:03:03 -0400990 /**
991 * Add an item to the database in a specified container. Sets the container, screen, cellX and
992 * cellY fields of the item. Also assigns an ID to the item.
993 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700994 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700995 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997 item.cellX = cellX;
998 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700999 // We store hotseat items in canonical form which is this orientation invariant position
1000 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001006 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001007
1008 final ContentValues values = new ContentValues();
1009 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001010 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001011
Michael Jurka414300a2013-08-27 15:42:35 +02001012 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001014
Jason Monk8e19cf22014-03-20 15:06:57 -04001015 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001016 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001017 public void run() {
1018 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1019 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001020
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001021 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001022 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001023 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001024 sBgItemsIdMap.put(item.id, item);
1025 switch (item.itemType) {
1026 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1027 sBgFolders.put(item.id, (FolderInfo) item);
1028 // Fall through
1029 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1030 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1031 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1032 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1033 sBgWorkspaceItems.add(item);
1034 } else {
1035 if (!sBgFolders.containsKey(item.container)) {
1036 // Adding an item to a folder that doesn't exist.
1037 String msg = "adding item: " + item + " to a folder that " +
1038 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001039 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001040 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001041 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 break;
1043 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1044 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1045 break;
1046 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001047 }
1048 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001049 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001050 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001051 }
1052
Joe Onorato9c1289c2009-08-17 11:03:03 -04001053 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001054 * Creates a new unique child id, for a given cell span across all layouts.
1055 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001056 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001057 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001058 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001059 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001060 }
1061
Sunny Goyal34942622014-08-29 17:20:55 -07001062 private static ArrayList<ItemInfo> getItemsByPackageName(
1063 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001064 ItemInfoFilter filter = new ItemInfoFilter() {
1065 @Override
1066 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1067 return cn.getPackageName().equals(pn) && info.user.equals(user);
1068 }
1069 };
Sunny Goyal34942622014-08-29 17:20:55 -07001070 return filterItemInfos(sBgItemsIdMap.values(), filter);
1071 }
1072
1073 /**
1074 * Removes all the items from the database corresponding to the specified package.
1075 */
1076 static void deletePackageFromDatabase(Context context, final String pn,
1077 final UserHandleCompat user) {
1078 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001079 }
1080
1081 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001082 * Removes the specified item from the database
1083 * @param context
1084 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001085 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001086 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001087 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1088 items.add(item);
1089 deleteItemsFromDatabase(context, items);
1090 }
1091
1092 /**
1093 * Removes the specified items from the database
1094 * @param context
1095 * @param item
1096 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001097 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001098 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001099
Michael Jurka83df1882011-08-31 20:59:26 -07001100 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001101 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001102 for (ItemInfo item : items) {
1103 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1104 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001105
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001106 // Lock on mBgLock *after* the db operation
1107 synchronized (sBgLock) {
1108 switch (item.itemType) {
1109 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1110 sBgFolders.remove(item.id);
1111 for (ItemInfo info: sBgItemsIdMap.values()) {
1112 if (info.container == item.id) {
1113 // We are deleting a folder which still contains items that
1114 // think they are contained by that folder.
1115 String msg = "deleting a folder (" + item + ") which still " +
1116 "contains items (" + info + ")";
1117 Log.e(TAG, msg);
1118 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001119 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001120 sBgWorkspaceItems.remove(item);
1121 break;
1122 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1123 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1124 sBgWorkspaceItems.remove(item);
1125 break;
1126 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1127 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1128 break;
1129 }
1130 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001131 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001132 }
1133 }
Michael Jurka83df1882011-08-31 20:59:26 -07001134 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001135 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001136 }
1137
1138 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001139 * Update the order of the workspace screens in the database. The array list contains
1140 * a list of screen ids in the order that they should appear.
1141 */
Winson Chungc9168342013-06-26 14:54:55 -07001142 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001143 // Log to disk
1144 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1145 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1146
Winson Chung64359a52013-07-08 17:17:08 -07001147 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001148 final ContentResolver cr = context.getContentResolver();
1149 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1150
1151 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001152 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001153 while (iter.hasNext()) {
1154 long id = iter.next();
1155 if (id < 0) {
1156 iter.remove();
1157 }
1158 }
1159
1160 Runnable r = new Runnable() {
1161 @Override
1162 public void run() {
Yura085c8532014-02-11 15:15:29 +00001163 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001164 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001165 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001166 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001167 for (int i = 0; i < count; i++) {
1168 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001169 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001170 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1171 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001172 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001173 }
Yura085c8532014-02-11 15:15:29 +00001174
1175 try {
1176 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1177 } catch (Exception ex) {
1178 throw new RuntimeException(ex);
1179 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001180
Winson Chungba9c37f2013-08-30 14:11:37 -07001181 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001182 sBgWorkspaceScreens.clear();
1183 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001184 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001185 }
1186 };
1187 runOnWorkerThread(r);
1188 }
1189
1190 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001191 * Remove the contents of the specified folder from the database
1192 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001193 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001194 final ContentResolver cr = context.getContentResolver();
1195
Michael Jurkac9d95c52011-08-29 14:03:34 -07001196 Runnable r = new Runnable() {
1197 public void run() {
1198 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001199 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001200 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 sBgItemsIdMap.remove(info.id);
1202 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 sBgWorkspaceItems.remove(info);
1204 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001205
Michael Jurkac9d95c52011-08-29 14:03:34 -07001206 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1207 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001209 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 for (ItemInfo childInfo : info.contents) {
1211 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001212 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001213 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001214 }
1215 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001216 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001217 }
1218
1219 /**
1220 * Set this as the current Launcher activity object for the loader.
1221 */
1222 public void initialize(Callbacks callbacks) {
1223 synchronized (mLock) {
1224 mCallbacks = new WeakReference<Callbacks>(callbacks);
1225 }
1226 }
1227
Kenny Guyed131872014-04-30 03:02:21 +01001228 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001229 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001230 int op = PackageUpdatedTask.OP_UPDATE;
1231 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1232 user));
1233 }
1234
1235 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001236 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001237 int op = PackageUpdatedTask.OP_REMOVE;
1238 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1239 user));
1240 }
1241
1242 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001243 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001244 int op = PackageUpdatedTask.OP_ADD;
1245 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1246 user));
1247 }
1248
1249 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001250 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001251 boolean replacing) {
1252 if (!replacing) {
1253 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1254 user));
1255 if (mAppsCanBeOnRemoveableStorage) {
1256 // Only rebind if we support removable storage. It catches the
1257 // case where
1258 // apps on the external sd card need to be reloaded
1259 startLoaderFromBackground();
1260 }
1261 } else {
1262 // If we are replacing then just update the packages in the list
1263 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1264 packageNames, user));
1265 }
1266 }
1267
1268 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001269 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001270 boolean replacing) {
1271 if (!replacing) {
1272 enqueuePackageUpdated(new PackageUpdatedTask(
1273 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1274 user));
1275 }
Kenny Guyed131872014-04-30 03:02:21 +01001276 }
1277
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001278 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001279 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1280 * ACTION_PACKAGE_CHANGED.
1281 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001282 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001283 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001284 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001285
Joe Onorato36115782010-06-17 13:28:48 -04001286 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001287 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001288 // If we have changed locale we need to clear out the labels in all apps/workspace.
1289 forceReload();
1290 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1291 // Check if configuration change was an mcc/mnc change which would affect app resources
1292 // and we would need to clear out the labels in all apps/workspace. Same handling as
1293 // above for ACTION_LOCALE_CHANGED
1294 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001295 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001296 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001297 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001298 forceReload();
1299 }
1300 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001301 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001302 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1303 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001304 Callbacks callbacks = getCallback();
1305 if (callbacks != null) {
1306 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001307 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001308 }
1309 }
1310
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001311 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001312 resetLoadedState(true, true);
1313
Reena Lee93f824a2011-09-23 17:20:28 -07001314 // Do this here because if the launcher activity is running it will be restarted.
1315 // If it's not running startLoaderFromBackground will merely tell it that it needs
1316 // to reload.
1317 startLoaderFromBackground();
1318 }
1319
Winson Chungf0c6ae02012-03-21 16:10:31 -07001320 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1321 synchronized (mLock) {
1322 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1323 // mWorkspaceLoaded to true later
1324 stopLoaderLocked();
1325 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1326 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1327 }
1328 }
1329
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001330 /**
1331 * When the launcher is in the background, it's possible for it to miss paired
1332 * configuration changes. So whenever we trigger the loader from the background
1333 * tell the launcher that it needs to re-run the loader when it comes back instead
1334 * of doing it now.
1335 */
1336 public void startLoaderFromBackground() {
1337 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001338 Callbacks callbacks = getCallback();
1339 if (callbacks != null) {
1340 // Only actually run the loader if they're not paused.
1341 if (!callbacks.setLoadOnResume()) {
1342 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001343 }
1344 }
1345 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001346 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001347 }
Joe Onorato36115782010-06-17 13:28:48 -04001348 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001349
Reena Lee93f824a2011-09-23 17:20:28 -07001350 // If there is already a loader task running, tell it to stop.
1351 // returns true if isLaunching() was true on the old task
1352 private boolean stopLoaderLocked() {
1353 boolean isLaunching = false;
1354 LoaderTask oldTask = mLoaderTask;
1355 if (oldTask != null) {
1356 if (oldTask.isLaunching()) {
1357 isLaunching = true;
1358 }
1359 oldTask.stopLocked();
1360 }
1361 return isLaunching;
1362 }
1363
Adam Cohen1a85c582014-09-30 09:48:49 -07001364 public boolean isCurrentCallbacks(Callbacks callbacks) {
1365 return (mCallbacks != null && mCallbacks.get() == callbacks);
1366 }
1367
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001368 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001369 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1370 }
1371
1372 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001373 synchronized (mLock) {
1374 if (DEBUG_LOADERS) {
1375 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1376 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001377
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001378 // Clear any deferred bind-runnables from the synchronized load process
1379 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001380 synchronized (mDeferredBindRunnables) {
1381 mDeferredBindRunnables.clear();
1382 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001383
Joe Onorato36115782010-06-17 13:28:48 -04001384 // Don't bother to start the thread if we know it's not going to do anything
1385 if (mCallbacks != null && mCallbacks.get() != null) {
1386 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001387 // also, don't downgrade isLaunching if we're already running
1388 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001389 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001390 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1391 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001392 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1393 } else {
1394 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1395 sWorker.post(mLoaderTask);
1396 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001397 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001398 }
1399 }
1400
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001401 void bindRemainingSynchronousPages() {
1402 // Post the remaining side pages to be loaded
1403 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001404 Runnable[] deferredBindRunnables = null;
1405 synchronized (mDeferredBindRunnables) {
1406 deferredBindRunnables = mDeferredBindRunnables.toArray(
1407 new Runnable[mDeferredBindRunnables.size()]);
1408 mDeferredBindRunnables.clear();
1409 }
1410 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001411 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001412 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001413 }
1414 }
1415
Joe Onorato36115782010-06-17 13:28:48 -04001416 public void stopLoader() {
1417 synchronized (mLock) {
1418 if (mLoaderTask != null) {
1419 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001420 }
1421 }
Joe Onorato36115782010-06-17 13:28:48 -04001422 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001423
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001424 /**
1425 * Loads the workspace screen ids in an ordered list.
1426 */
1427 private static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001428 final ContentResolver contentResolver = context.getContentResolver();
1429 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001430
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001431 // Get screens ordered by rank.
1432 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1433 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1434 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001435 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001436 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001437 while (sc.moveToNext()) {
1438 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001439 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001440 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001441 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1442 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001443 }
1444 }
1445 } finally {
1446 sc.close();
1447 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001448 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001449 }
1450
Michael Jurkac57b7a82011-08-09 22:02:20 -07001451 public boolean isAllAppsLoaded() {
1452 return mAllAppsLoaded;
1453 }
1454
Winson Chung36a62fe2012-05-06 18:04:42 -07001455 boolean isLoadingWorkspace() {
1456 synchronized (mLock) {
1457 if (mLoaderTask != null) {
1458 return mLoaderTask.isLoadingWorkspace();
1459 }
1460 }
1461 return false;
1462 }
1463
Joe Onorato36115782010-06-17 13:28:48 -04001464 /**
1465 * Runnable for the thread that loads the contents of the launcher:
1466 * - workspace icons
1467 * - widgets
1468 * - all apps icons
1469 */
1470 private class LoaderTask implements Runnable {
1471 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001472 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001473 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001474 private boolean mStopped;
1475 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001476 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001477
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001479 mContext = context;
1480 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001481 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001482 }
1483
Joe Onorato36115782010-06-17 13:28:48 -04001484 boolean isLaunching() {
1485 return mIsLaunching;
1486 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001487
Winson Chung36a62fe2012-05-06 18:04:42 -07001488 boolean isLoadingWorkspace() {
1489 return mIsLoadingAndBindingWorkspace;
1490 }
1491
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001492 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001493 mIsLoadingAndBindingWorkspace = true;
1494
Joe Onorato36115782010-06-17 13:28:48 -04001495 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001496 if (DEBUG_LOADERS) {
1497 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001498 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001499
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001500 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001501 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001502 synchronized (LoaderTask.this) {
1503 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001504 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001505 }
1506 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001507 }
1508 }
1509
Joe Onorato36115782010-06-17 13:28:48 -04001510 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001511 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001512 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001513
Joe Onorato36115782010-06-17 13:28:48 -04001514 private void waitForIdle() {
1515 // Wait until the either we're stopped or the other threads are done.
1516 // This way we don't start loading all apps until the workspace has settled
1517 // down.
1518 synchronized (LoaderTask.this) {
1519 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001520
Joe Onorato36115782010-06-17 13:28:48 -04001521 mHandler.postIdle(new Runnable() {
1522 public void run() {
1523 synchronized (LoaderTask.this) {
1524 mLoadAndBindStepFinished = true;
1525 if (DEBUG_LOADERS) {
1526 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001527 }
Joe Onorato36115782010-06-17 13:28:48 -04001528 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001529 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001530 }
Joe Onorato36115782010-06-17 13:28:48 -04001531 });
1532
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001533 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001534 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001535 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1536 // wait no longer than 1sec at a time
1537 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001538 } catch (InterruptedException ex) {
1539 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001540 }
1541 }
Joe Onorato36115782010-06-17 13:28:48 -04001542 if (DEBUG_LOADERS) {
1543 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001544 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001545 + "ms for previous step to finish binding");
1546 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001547 }
Joe Onorato36115782010-06-17 13:28:48 -04001548 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001549
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001550 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001551 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001552 // Ensure that we have a valid page index to load synchronously
1553 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1554 "valid page index");
1555 }
1556 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1557 // Ensure that we don't try and bind a specified page when the pages have not been
1558 // loaded already (we should load everything asynchronously in that case)
1559 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1560 }
1561 synchronized (mLock) {
1562 if (mIsLoaderTaskRunning) {
1563 // Ensure that we are never running the background loading at this point since
1564 // we also touch the background collections
1565 throw new RuntimeException("Error! Background loading is already running");
1566 }
1567 }
1568
1569 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1570 // data structures, we can't allow any other thread to touch that data, but because
1571 // this call is synchronous, we can get away with not locking).
1572
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001573 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001574 // operations from the previous activity. We need to ensure that all queued operations
1575 // are executed before any synchronous binding work is done.
1576 mHandler.flush();
1577
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001578 // Divide the set of loaded items into those that we are binding synchronously, and
1579 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001580 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001581 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1582 // arise from that.
1583 onlyBindAllApps();
1584 }
1585
Joe Onorato36115782010-06-17 13:28:48 -04001586 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001587 synchronized (mLock) {
1588 mIsLoaderTaskRunning = true;
1589 }
Joe Onorato36115782010-06-17 13:28:48 -04001590 // Optimize for end-user experience: if the Launcher is up and // running with the
1591 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1592 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001593 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001594 // Elevate priority when Home launches for the first time to avoid
1595 // starving at boot time. Staring at a blank home is not cool.
1596 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001597 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1598 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001599 android.os.Process.setThreadPriority(mIsLaunching
1600 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1601 }
Winson Chung64359a52013-07-08 17:17:08 -07001602 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001603 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001604
Joe Onorato36115782010-06-17 13:28:48 -04001605 if (mStopped) {
1606 break keep_running;
1607 }
1608
1609 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1610 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001611 synchronized (mLock) {
1612 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001613 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001614 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1615 }
1616 }
Joe Onorato36115782010-06-17 13:28:48 -04001617 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001618
1619 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001620 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1621 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001622
1623 // Restore the default thread priority after we are done loading items
1624 synchronized (mLock) {
1625 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1626 }
Joe Onorato36115782010-06-17 13:28:48 -04001627 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001628
Joe Onorato36115782010-06-17 13:28:48 -04001629 // Clear out this reference, otherwise we end up holding it until all of the
1630 // callback runnables are done.
1631 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001632
Joe Onorato36115782010-06-17 13:28:48 -04001633 synchronized (mLock) {
1634 // If we are still the last one to be scheduled, remove ourselves.
1635 if (mLoaderTask == this) {
1636 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001637 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001638 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001639 }
Joe Onorato36115782010-06-17 13:28:48 -04001640 }
1641
1642 public void stopLocked() {
1643 synchronized (LoaderTask.this) {
1644 mStopped = true;
1645 this.notify();
1646 }
1647 }
1648
1649 /**
1650 * Gets the callbacks object. If we've been stopped, or if the launcher object
1651 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1652 * object that was around when the deferred message was scheduled, and if there's
1653 * a new Callbacks object around then also return null. This will save us from
1654 * calling onto it with data that will be ignored.
1655 */
1656 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1657 synchronized (mLock) {
1658 if (mStopped) {
1659 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001660 }
Joe Onorato36115782010-06-17 13:28:48 -04001661
1662 if (mCallbacks == null) {
1663 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001664 }
Joe Onorato36115782010-06-17 13:28:48 -04001665
1666 final Callbacks callbacks = mCallbacks.get();
1667 if (callbacks != oldCallbacks) {
1668 return null;
1669 }
1670 if (callbacks == null) {
1671 Log.w(TAG, "no mCallbacks");
1672 return null;
1673 }
1674
1675 return callbacks;
1676 }
1677 }
1678
1679 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001680 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001681 LauncherAppState app = LauncherAppState.getInstance();
1682 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001683 final int countX = (int) grid.numColumns;
1684 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001685
Adam Cohendcd297f2013-06-18 13:13:40 -07001686 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001687 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001688 // Return early if we detect that an item is under the hotseat button
1689 if (mCallbacks == null ||
1690 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001691 Log.e(TAG, "Error loading shortcut into hotseat " + item
1692 + " into position (" + item.screenId + ":" + item.cellX + ","
1693 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001694 return false;
1695 }
1696
Dan Sandler295ae182013-12-10 16:05:47 -05001697 final ItemInfo[][] hotseatItems =
1698 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1699
Adam Cohenae4409d2013-11-26 10:34:59 -08001700 if (item.screenId >= grid.numHotseatIcons) {
1701 Log.e(TAG, "Error loading shortcut " + item
1702 + " into hotseat position " + item.screenId
1703 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1704 + ")");
1705 return false;
1706 }
1707
Dan Sandler295ae182013-12-10 16:05:47 -05001708 if (hotseatItems != null) {
1709 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001710 Log.e(TAG, "Error loading shortcut into hotseat " + item
1711 + " into position (" + item.screenId + ":" + item.cellX + ","
1712 + item.cellY + ") occupied by "
1713 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1714 [(int) item.screenId][0]);
1715 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001716 } else {
1717 hotseatItems[(int) item.screenId][0] = item;
1718 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001719 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001720 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001721 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001722 items[(int) item.screenId][0] = item;
1723 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001724 return true;
1725 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001726 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1727 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001728 return true;
1729 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001730
Adam Cohendcd297f2013-06-18 13:13:40 -07001731 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001732 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001733 occupied.put(item.screenId, items);
1734 }
1735
Dan Sandler295ae182013-12-10 16:05:47 -05001736 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001737 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1738 item.cellX < 0 || item.cellY < 0 ||
1739 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1740 Log.e(TAG, "Error loading shortcut " + item
1741 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1742 + item.cellX + "," + item.cellY
1743 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1744 return false;
1745 }
1746
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001747 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001748 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1749 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001750 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001751 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001752 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001753 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001754 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001755 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001756 return false;
1757 }
1758 }
1759 }
1760 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1761 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001762 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001763 }
1764 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001765
Joe Onorato36115782010-06-17 13:28:48 -04001766 return true;
1767 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001768
Winson Chungba9c37f2013-08-30 14:11:37 -07001769 /** Clears all the sBg data structures */
1770 private void clearSBgDataStructures() {
1771 synchronized (sBgLock) {
1772 sBgWorkspaceItems.clear();
1773 sBgAppWidgets.clear();
1774 sBgFolders.clear();
1775 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001776 sBgWorkspaceScreens.clear();
1777 }
1778 }
1779
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001780 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001781 // Log to disk
1782 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1783
Joe Onorato36115782010-06-17 13:28:48 -04001784 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001785
Joe Onorato36115782010-06-17 13:28:48 -04001786 final Context context = mContext;
1787 final ContentResolver contentResolver = context.getContentResolver();
1788 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001789 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001790 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1791 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001792 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001793
Winson Chung892c74d2013-08-22 16:15:50 -07001794 LauncherAppState app = LauncherAppState.getInstance();
1795 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1796 int countX = (int) grid.numColumns;
1797 int countY = (int) grid.numRows;
1798
Dan Sandlerd5024042014-01-09 15:01:33 -05001799 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1800 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1801 LauncherAppState.getLauncherProvider().deleteDatabase();
1802 }
1803
1804 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1805 // append the user's Launcher2 shortcuts
1806 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1807 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1808 } else {
1809 // Make sure the default workspace is loaded
1810 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001811 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001812 }
Adam Cohene25af792013-06-06 23:08:25 -07001813
Winson Chung2abf94d2012-07-18 18:16:38 -07001814 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001815 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001816 final HashSet<String> installingPkgs = PackageInstallerCompat
1817 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001818
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001819 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001820 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001821 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001822 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001823 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001824
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001825 // +1 for the hotseat (it can be larger than the workspace)
1826 // Load workspace in reverse order to ensure that latest items are loaded first (and
1827 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001828 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001829
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001830 try {
1831 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1832 final int intentIndex = c.getColumnIndexOrThrow
1833 (LauncherSettings.Favorites.INTENT);
1834 final int titleIndex = c.getColumnIndexOrThrow
1835 (LauncherSettings.Favorites.TITLE);
1836 final int iconTypeIndex = c.getColumnIndexOrThrow(
1837 LauncherSettings.Favorites.ICON_TYPE);
1838 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1839 final int iconPackageIndex = c.getColumnIndexOrThrow(
1840 LauncherSettings.Favorites.ICON_PACKAGE);
1841 final int iconResourceIndex = c.getColumnIndexOrThrow(
1842 LauncherSettings.Favorites.ICON_RESOURCE);
1843 final int containerIndex = c.getColumnIndexOrThrow(
1844 LauncherSettings.Favorites.CONTAINER);
1845 final int itemTypeIndex = c.getColumnIndexOrThrow(
1846 LauncherSettings.Favorites.ITEM_TYPE);
1847 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1848 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001849 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1850 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001851 final int screenIndex = c.getColumnIndexOrThrow(
1852 LauncherSettings.Favorites.SCREEN);
1853 final int cellXIndex = c.getColumnIndexOrThrow
1854 (LauncherSettings.Favorites.CELLX);
1855 final int cellYIndex = c.getColumnIndexOrThrow
1856 (LauncherSettings.Favorites.CELLY);
1857 final int spanXIndex = c.getColumnIndexOrThrow
1858 (LauncherSettings.Favorites.SPANX);
1859 final int spanYIndex = c.getColumnIndexOrThrow(
1860 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001861 final int rankIndex = c.getColumnIndexOrThrow(
1862 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001863 final int restoredIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001865 final int profileIdIndex = c.getColumnIndexOrThrow(
1866 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001867 final int optionsIndex = c.getColumnIndexOrThrow(
1868 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001869
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001870 ShortcutInfo info;
1871 String intentDescription;
1872 LauncherAppWidgetInfo appWidgetInfo;
1873 int container;
1874 long id;
1875 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001876 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001877
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001878 while (!mStopped && c.moveToNext()) {
1879 try {
1880 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001881 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001882 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 switch (itemType) {
1885 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1886 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001887 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001888 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001889 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001890 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001891 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001892 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001893 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001894 if (user == null) {
1895 // User has been deleted remove the item.
1896 itemsToRemove.add(id);
1897 continue;
1898 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001899 try {
1900 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001901 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001902 if (cn != null && cn.getPackageName() != null) {
1903 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1904 cn.getPackageName(), user);
1905 boolean validComponent = validPkg &&
1906 launcherApps.isActivityEnabledForProfile(cn, user);
1907
1908 if (validComponent) {
1909 if (restored) {
1910 // no special handling necessary for this item
1911 restoredRows.add(id);
1912 restored = false;
1913 }
1914 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001915 intent = null;
1916 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1917 // We allow auto install apps to have their intent
1918 // updated after an install.
1919 intent = manager.getLaunchIntentForPackage(
1920 cn.getPackageName());
1921 if (intent != null) {
1922 ContentValues values = new ContentValues();
1923 values.put(LauncherSettings.Favorites.INTENT,
1924 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001925 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001926 }
1927 }
1928
1929 if (intent == null) {
1930 // The app is installed but the component is no
1931 // longer available.
1932 Launcher.addDumpLog(TAG,
1933 "Invalid component removed: " + cn, true);
1934 itemsToRemove.add(id);
1935 continue;
1936 } else {
1937 // no special handling necessary for this item
1938 restoredRows.add(id);
1939 restored = false;
1940 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001941 } else if (restored) {
1942 // Package is not yet available but might be
1943 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001944 Launcher.addDumpLog(TAG,
1945 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001946
1947 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1948 // Restore has started once.
1949 } else if (installingPkgs.contains(cn.getPackageName())) {
1950 // App restore has started. Update the flag
1951 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1952 ContentValues values = new ContentValues();
1953 values.put(LauncherSettings.Favorites.RESTORED,
1954 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001955 updateItem(id, values);
1956 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1957 // This is a common app. Try to replace this.
1958 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1959 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1960 if (parser.findDefaultApp()) {
1961 // Default app found. Replace it.
1962 intent = parser.parsedIntent;
1963 cn = intent.getComponent();
1964 ContentValues values = parser.parsedValues;
1965 values.put(LauncherSettings.Favorites.RESTORED, 0);
1966 updateItem(id, values);
1967 restored = false;
1968 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001969
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001970 } else if (REMOVE_UNRESTORED_ICONS) {
1971 Launcher.addDumpLog(TAG,
1972 "Unrestored package removed: " + cn, true);
1973 itemsToRemove.add(id);
1974 continue;
1975 }
Sunny Goyal94485362014-09-18 16:13:58 -07001976 } else if (REMOVE_UNRESTORED_ICONS) {
1977 Launcher.addDumpLog(TAG,
1978 "Unrestored package removed: " + cn, true);
1979 itemsToRemove.add(id);
1980 continue;
1981 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001982 } else if (launcherApps.isAppEnabled(
1983 manager, cn.getPackageName(),
1984 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1985 // Package is present but not available.
1986 allowMissingTarget = true;
1987 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1988 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001989 // SdCard is not ready yet. Package might get available,
1990 // once it is ready.
1991 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1992 + " (check again later)", true);
1993 HashSet<String> pkgs = sPendingPackages.get(user);
1994 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001995 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001996 sPendingPackages.put(user, pkgs);
1997 }
1998 pkgs.add(cn.getPackageName());
1999 allowMissingTarget = true;
2000 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002001
2002 } else {
2003 // Do not wait for external media load anymore.
2004 // Log the invalid package, and remove it
2005 Launcher.addDumpLog(TAG,
2006 "Invalid package removed: " + cn, true);
2007 itemsToRemove.add(id);
2008 continue;
Winson Chungee055712013-07-30 14:46:24 -07002009 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002010 } else if (cn == null) {
2011 // For shortcuts with no component, keep them as they are
2012 restoredRows.add(id);
2013 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002014 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002015 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002016 Launcher.addDumpLog(TAG,
2017 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002018 continue;
2019 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002020
Sunny Goyal34b65272015-03-11 16:56:52 -07002021 container = c.getInt(containerIndex);
2022 boolean useLowResIcon = container >= 0 &&
2023 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2024
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002025 if (itemReplaced) {
2026 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002027 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002028 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002029 } else {
2030 // Don't replace items for other profiles.
2031 itemsToRemove.add(id);
2032 continue;
2033 }
2034 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002035 if (user.equals(UserHandleCompat.myUserHandle())) {
2036 Launcher.addDumpLog(TAG,
2037 "constructing info for partially restored package",
2038 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002039 info = getRestoredItemInfo(c, titleIndex, intent,
2040 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002041 intent = getRestoredItemIntent(c, context, intent);
2042 } else {
2043 // Don't restore items for other profiles.
2044 itemsToRemove.add(id);
2045 continue;
2046 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002047 } else if (itemType ==
2048 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002049 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002050 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002051 } else {
2052 info = getShortcutInfo(c, context, iconTypeIndex,
2053 iconPackageIndex, iconResourceIndex, iconIndex,
2054 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002055
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002056 // App shortcuts that used to be automatically added to Launcher
2057 // didn't always have the correct intent flags set, so do that
2058 // here
2059 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002060 intent.getCategories() != null &&
2061 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002062 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002063 intent.addFlags(
2064 Intent.FLAG_ACTIVITY_NEW_TASK |
2065 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2066 }
Michael Jurka96879562012-03-22 05:54:33 -07002067 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002068
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002070 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002073 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 info.cellX = c.getInt(cellXIndex);
2075 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002076 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002077 info.spanX = 1;
2078 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002079 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002080 info.isDisabled = disabledState;
2081 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2082 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2083 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002084
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002086 if (!checkItemPlacement(occupied, info)) {
2087 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 break;
2089 }
2090
2091 switch (container) {
2092 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2093 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2094 sBgWorkspaceItems.add(info);
2095 break;
2096 default:
2097 // Item is in a user folder
2098 FolderInfo folderInfo =
2099 findOrMakeFolder(sBgFolders, container);
2100 folderInfo.add(info);
2101 break;
2102 }
2103 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002104 } else {
2105 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002106 }
2107 break;
2108
2109 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2110 id = c.getLong(idIndex);
2111 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2112
2113 folderInfo.title = c.getString(titleIndex);
2114 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002115 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002117 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 folderInfo.cellX = c.getInt(cellXIndex);
2119 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002120 folderInfo.spanX = 1;
2121 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002122 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002123
Daniel Sandler8802e962010-05-26 16:28:16 -04002124 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002125 if (!checkItemPlacement(occupied, folderInfo)) {
2126 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002127 break;
2128 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002129
Joe Onorato9c1289c2009-08-17 11:03:03 -04002130 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2132 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2133 sBgWorkspaceItems.add(folderInfo);
2134 break;
Joe Onorato36115782010-06-17 13:28:48 -04002135 }
Joe Onorato17a89222011-02-08 17:26:11 -08002136
Chris Wrenf4d08112014-01-16 18:13:56 -05002137 if (restored) {
2138 // no special handling required for restored folders
2139 restoredRows.add(id);
2140 }
2141
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2143 sBgFolders.put(folderInfo.id, folderInfo);
2144 break;
2145
2146 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002147 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002149 boolean customWidget = itemType ==
2150 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2151
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002152 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002153 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002154 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002155 final ComponentName component =
2156 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002157
Sunny Goyal651077b2014-06-30 14:15:31 -07002158 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002159 final boolean isIdValid = (restoreStatus &
2160 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002161
Sunny Goyalff572272014-07-23 13:58:07 -07002162 final boolean wasProviderReady = (restoreStatus &
2163 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002164
Adam Cohen59400422014-03-05 18:07:04 -08002165 final LauncherAppWidgetProviderInfo provider =
2166 LauncherModel.getProviderInfo(context,
2167 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002168
2169 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002170 if (!isSafeMode && !customWidget &&
2171 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002172 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002173 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002174
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002175 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002176 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002177 itemsToRemove.add(id);
2178 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002179 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002180 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2181 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002182
2183 if (!customWidget) {
2184 int[] minSpan =
2185 Launcher.getMinSpanForWidget(context, provider);
2186 appWidgetInfo.minSpanX = minSpan[0];
2187 appWidgetInfo.minSpanY = minSpan[1];
2188 }
Sunny Goyalff572272014-07-23 13:58:07 -07002189
2190 int status = restoreStatus;
2191 if (!wasProviderReady) {
2192 // If provider was not previously ready, update the
2193 // status and UI flag.
2194
2195 // Id would be valid only if the widget restore broadcast was received.
2196 if (isIdValid) {
2197 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2198 } else {
2199 status &= ~LauncherAppWidgetInfo
2200 .FLAG_PROVIDER_NOT_READY;
2201 }
2202 }
2203 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002204 } else {
2205 Log.v(TAG, "Widget restore pending id=" + id
2206 + " appWidgetId=" + appWidgetId
2207 + " status =" + restoreStatus);
2208 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002209 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002210 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002211
2212 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2213 // Restore has started once.
2214 } else if (installingPkgs.contains(component.getPackageName())) {
2215 // App restore has started. Update the flag
2216 appWidgetInfo.restoreStatus |=
2217 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002218 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002219 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002220 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002221 itemsToRemove.add(id);
2222 continue;
2223 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002224 }
Sunny Goyalff572272014-07-23 13:58:07 -07002225
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002226 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002227 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 appWidgetInfo.cellX = c.getInt(cellXIndex);
2229 appWidgetInfo.cellY = c.getInt(cellYIndex);
2230 appWidgetInfo.spanX = c.getInt(spanXIndex);
2231 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002232
Adam Cohen59400422014-03-05 18:07:04 -08002233 if (!customWidget) {
2234 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2235 appWidgetInfo.minSpanX = minSpan[0];
2236 appWidgetInfo.minSpanY = minSpan[1];
2237 }
2238
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002239 container = c.getInt(containerIndex);
2240 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2241 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2242 Log.e(TAG, "Widget found where container != " +
2243 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2244 continue;
2245 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002246
Adam Cohene25af792013-06-06 23:08:25 -07002247 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002248 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002249 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2250 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251 break;
2252 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002253
Adam Cohen59400422014-03-05 18:07:04 -08002254 if (!customWidget) {
2255 String providerName =
2256 appWidgetInfo.providerName.flattenToString();
2257 if (!providerName.equals(savedProvider) ||
2258 (appWidgetInfo.restoreStatus != restoreStatus)) {
2259 ContentValues values = new ContentValues();
2260 values.put(
2261 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2262 providerName);
2263 values.put(LauncherSettings.Favorites.RESTORED,
2264 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002265 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002266 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002267 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002268 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2269 sBgAppWidgets.add(appWidgetInfo);
2270 }
Joe Onorato36115782010-06-17 13:28:48 -04002271 break;
2272 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002273 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002274 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002275 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 }
2277 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002278 if (c != null) {
2279 c.close();
2280 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 }
2282
Winson Chungba9c37f2013-08-30 14:11:37 -07002283 // Break early if we've stopped loading
2284 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002285 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002286 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002287 }
2288
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 if (itemsToRemove.size() > 0) {
2290 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002291 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002292 // Remove dead items
2293 for (long id : itemsToRemove) {
2294 if (DEBUG_LOADERS) {
2295 Log.d(TAG, "Removed id = " + id);
2296 }
2297 // Don't notify content observers
2298 try {
2299 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2300 null, null);
2301 } catch (RemoteException e) {
2302 Log.w(TAG, "Could not remove id = " + id);
2303 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002304 }
2305 }
2306
Chris Wrenf4d08112014-01-16 18:13:56 -05002307 if (restoredRows.size() > 0) {
2308 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002309 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002310 // Update restored items that no longer require special handling
2311 try {
2312 StringBuilder selectionBuilder = new StringBuilder();
2313 selectionBuilder.append(LauncherSettings.Favorites._ID);
2314 selectionBuilder.append(" IN (");
2315 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2316 selectionBuilder.append(")");
2317 ContentValues values = new ContentValues();
2318 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002319 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002320 values, selectionBuilder.toString(), null);
2321 } catch (RemoteException e) {
2322 Log.w(TAG, "Could not update restored rows");
2323 }
2324 }
2325
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002326 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2327 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002328 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002329 null, sWorker);
2330 }
2331
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002332 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2333 // Log to disk
2334 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2335 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002336
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002337 // Remove any empty screens
2338 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2339 for (ItemInfo item: sBgItemsIdMap.values()) {
2340 long screenId = item.screenId;
2341 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2342 unusedScreens.contains(screenId)) {
2343 unusedScreens.remove(screenId);
2344 }
2345 }
2346
2347 // If there are any empty screens remove them, and update.
2348 if (unusedScreens.size() != 0) {
2349 // Log to disk
2350 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2351 TextUtils.join(", ", unusedScreens), true);
2352
2353 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002354 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 }
2356
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 if (DEBUG_LOADERS) {
2358 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2359 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002360 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002361 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002363
Daniel Sandler566da102013-06-25 23:43:45 -04002364 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002365 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002367 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002368 line += " | ";
2369 }
Winson Chung892c74d2013-08-22 16:15:50 -07002370 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002371 ItemInfo[][] screen = occupied.get(screenId);
2372 if (x < screen.length && y < screen[x].length) {
2373 line += (screen[x][y] != null) ? "#" : ".";
2374 } else {
2375 line += "!";
2376 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002377 }
Joe Onorato36115782010-06-17 13:28:48 -04002378 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002380 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002381 }
Joe Onorato36115782010-06-17 13:28:48 -04002382 }
Adam Cohene25af792013-06-06 23:08:25 -07002383 }
2384
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002385 /**
2386 * Partially updates the item without any notification. Must be called on the worker thread.
2387 */
2388 private void updateItem(long itemId, ContentValues update) {
2389 mContext.getContentResolver().update(
2390 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2391 update,
2392 BaseColumns._ID + "= ?",
2393 new String[]{Long.toString(itemId)});
2394 }
2395
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002396 /** Filters the set of items who are directly or indirectly (via another container) on the
2397 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002398 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002399 ArrayList<ItemInfo> allWorkspaceItems,
2400 ArrayList<ItemInfo> currentScreenItems,
2401 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002402 // Purge any null ItemInfos
2403 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2404 while (iter.hasNext()) {
2405 ItemInfo i = iter.next();
2406 if (i == null) {
2407 iter.remove();
2408 }
2409 }
2410
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002411 // Order the set of items by their containers first, this allows use to walk through the
2412 // list sequentially, build up a list of containers that are in the specified screen,
2413 // as well as all items in those containers.
2414 Set<Long> itemsOnScreen = new HashSet<Long>();
2415 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2416 @Override
2417 public int compare(ItemInfo lhs, ItemInfo rhs) {
2418 return (int) (lhs.container - rhs.container);
2419 }
2420 });
2421 for (ItemInfo info : allWorkspaceItems) {
2422 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002423 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002424 currentScreenItems.add(info);
2425 itemsOnScreen.add(info.id);
2426 } else {
2427 otherScreenItems.add(info);
2428 }
2429 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2430 currentScreenItems.add(info);
2431 itemsOnScreen.add(info.id);
2432 } else {
2433 if (itemsOnScreen.contains(info.container)) {
2434 currentScreenItems.add(info);
2435 itemsOnScreen.add(info.id);
2436 } else {
2437 otherScreenItems.add(info);
2438 }
2439 }
2440 }
2441 }
2442
2443 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002444 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002445 ArrayList<LauncherAppWidgetInfo> appWidgets,
2446 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2447 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002448
2449 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002450 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002452 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453 currentScreenWidgets.add(widget);
2454 } else {
2455 otherScreenWidgets.add(widget);
2456 }
2457 }
2458 }
2459
2460 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002461 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002462 HashMap<Long, ItemInfo> itemsIdMap,
2463 HashMap<Long, FolderInfo> folders,
2464 HashMap<Long, FolderInfo> currentScreenFolders,
2465 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466
2467 for (long id : folders.keySet()) {
2468 ItemInfo info = itemsIdMap.get(id);
2469 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002470 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002472 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473 currentScreenFolders.put(id, folder);
2474 } else {
2475 otherScreenFolders.put(id, folder);
2476 }
2477 }
2478 }
2479
2480 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2481 * right) */
2482 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002483 final LauncherAppState app = LauncherAppState.getInstance();
2484 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002485 // XXX: review this
2486 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002487 @Override
2488 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002489 int cellCountX = (int) grid.numColumns;
2490 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002491 int screenOffset = cellCountX * cellCountY;
2492 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002493 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002494 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002495 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002496 rhs.cellY * cellCountX + rhs.cellX);
2497 return (int) (lr - rr);
2498 }
2499 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002500 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002501
Adam Cohendcd297f2013-06-18 13:13:40 -07002502 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2503 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002504 final Runnable r = new Runnable() {
2505 @Override
2506 public void run() {
2507 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2508 if (callbacks != null) {
2509 callbacks.bindScreens(orderedScreens);
2510 }
2511 }
2512 };
2513 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2514 }
2515
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002516 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2517 final ArrayList<ItemInfo> workspaceItems,
2518 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2519 final HashMap<Long, FolderInfo> folders,
2520 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002521
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 final boolean postOnMainThread = (deferredBindRunnables != null);
2523
2524 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002525 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002527 final int start = i;
2528 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529 final Runnable r = new Runnable() {
2530 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002531 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002532 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002533 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002534 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2535 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002536 }
2537 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002538 };
2539 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002540 synchronized (deferredBindRunnables) {
2541 deferredBindRunnables.add(r);
2542 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002543 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002544 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 }
Joe Onorato36115782010-06-17 13:28:48 -04002546 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547
2548 // Bind the folders
2549 if (!folders.isEmpty()) {
2550 final Runnable r = new Runnable() {
2551 public void run() {
2552 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2553 if (callbacks != null) {
2554 callbacks.bindFolders(folders);
2555 }
2556 }
2557 };
2558 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002559 synchronized (deferredBindRunnables) {
2560 deferredBindRunnables.add(r);
2561 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002563 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002564 }
2565 }
2566
2567 // Bind the widgets, one at a time
2568 N = appWidgets.size();
2569 for (int i = 0; i < N; i++) {
2570 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2571 final Runnable r = new Runnable() {
2572 public void run() {
2573 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2574 if (callbacks != null) {
2575 callbacks.bindAppWidget(widget);
2576 }
2577 }
2578 };
2579 if (postOnMainThread) {
2580 deferredBindRunnables.add(r);
2581 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002582 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583 }
2584 }
2585 }
2586
2587 /**
2588 * Binds all loaded data to actual views on the main thread.
2589 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002590 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 final long t = SystemClock.uptimeMillis();
2592 Runnable r;
2593
2594 // Don't use these two variables in any of the callback runnables.
2595 // Otherwise we hold a reference to them.
2596 final Callbacks oldCallbacks = mCallbacks.get();
2597 if (oldCallbacks == null) {
2598 // This launcher has exited and nobody bothered to tell us. Just bail.
2599 Log.w(TAG, "LoaderTask running with no launcher");
2600 return;
2601 }
2602
Winson Chung9b9fb962013-11-15 15:39:34 -08002603 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002604 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2605 ArrayList<LauncherAppWidgetInfo> appWidgets =
2606 new ArrayList<LauncherAppWidgetInfo>();
2607 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2608 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002609 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002610 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 workspaceItems.addAll(sBgWorkspaceItems);
2612 appWidgets.addAll(sBgAppWidgets);
2613 folders.putAll(sBgFolders);
2614 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002615 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 }
2617
Derek Prothro7aff3992013-12-10 14:00:37 -05002618 final boolean isLoadingSynchronously =
2619 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002620 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002621 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002622 if (currScreen >= orderedScreenIds.size()) {
2623 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002624 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002625 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002626 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002627 final long currentScreenId = currentScreen < 0
2628 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002629
2630 // Load all the items that are on the current page first (and in the process, unbind
2631 // all the existing workspace items before we call startBinding() below.
2632 unbindWorkspaceItemsOnMainThread();
2633
2634 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002635 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2636 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2637 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2638 new ArrayList<LauncherAppWidgetInfo>();
2639 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2640 new ArrayList<LauncherAppWidgetInfo>();
2641 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2642 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2643
Winson Chung9b9fb962013-11-15 15:39:34 -08002644 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002645 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002646 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002647 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002648 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002649 otherFolders);
2650 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2651 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2652
2653 // Tell the workspace that we're about to start binding items
2654 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002655 public void run() {
2656 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2657 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002659 }
2660 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002661 };
Winson Chung81b52252012-08-27 15:34:29 -07002662 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663
Adam Cohendcd297f2013-06-18 13:13:40 -07002664 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2665
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 // Load items on the current page
2667 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2668 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002669 if (isLoadingSynchronously) {
2670 r = new Runnable() {
2671 public void run() {
2672 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002673 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002674 callbacks.onPageBoundSynchronously(currentScreen);
2675 }
2676 }
2677 };
Winson Chung81b52252012-08-27 15:34:29 -07002678 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002679 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002680
Winson Chung4a2afa32012-07-19 14:53:05 -07002681 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2682 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002683 synchronized (mDeferredBindRunnables) {
2684 mDeferredBindRunnables.clear();
2685 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002686 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002687 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002688
2689 // Tell the workspace that we're done binding items
2690 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002691 public void run() {
2692 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2693 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002694 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002695 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002696
Winson Chung98e030b2012-05-07 16:01:11 -07002697 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002698 if (DEBUG_LOADERS) {
2699 Log.d(TAG, "bound workspace in "
2700 + (SystemClock.uptimeMillis()-t) + "ms");
2701 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002702
2703 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002704 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002705 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002706 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002707 synchronized (mDeferredBindRunnables) {
2708 mDeferredBindRunnables.add(r);
2709 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002710 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002711 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002712 }
Joe Onorato36115782010-06-17 13:28:48 -04002713 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002714
Joe Onorato36115782010-06-17 13:28:48 -04002715 private void loadAndBindAllApps() {
2716 if (DEBUG_LOADERS) {
2717 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2718 }
2719 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002720 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002721 synchronized (LoaderTask.this) {
2722 if (mStopped) {
2723 return;
2724 }
2725 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002726 }
Joe Onorato36115782010-06-17 13:28:48 -04002727 } else {
2728 onlyBindAllApps();
2729 }
2730 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002731
Joe Onorato36115782010-06-17 13:28:48 -04002732 private void onlyBindAllApps() {
2733 final Callbacks oldCallbacks = mCallbacks.get();
2734 if (oldCallbacks == null) {
2735 // This launcher has exited and nobody bothered to tell us. Just bail.
2736 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2737 return;
2738 }
2739
2740 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002741 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002742 final ArrayList<AppInfo> list
2743 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002744 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002745 public void run() {
2746 final long t = SystemClock.uptimeMillis();
2747 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2748 if (callbacks != null) {
2749 callbacks.bindAllApplications(list);
2750 }
2751 if (DEBUG_LOADERS) {
2752 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2753 + (SystemClock.uptimeMillis()-t) + "ms");
2754 }
2755 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002756 };
2757 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002758 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002759 r.run();
2760 } else {
2761 mHandler.post(r);
2762 }
Joe Onorato36115782010-06-17 13:28:48 -04002763 }
2764
Winson Chung64359a52013-07-08 17:17:08 -07002765 private void loadAllApps() {
2766 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002767
Joe Onorato36115782010-06-17 13:28:48 -04002768 final Callbacks oldCallbacks = mCallbacks.get();
2769 if (oldCallbacks == null) {
2770 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002771 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002772 return;
2773 }
2774
2775 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2776 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2777
Kenny Guyed131872014-04-30 03:02:21 +01002778 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2779
Winson Chung64359a52013-07-08 17:17:08 -07002780 // Clear the list of apps
2781 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002782 SharedPreferences prefs = mContext.getSharedPreferences(
2783 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002784 for (UserHandleCompat user : profiles) {
2785 // Query for the set of apps
2786 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2787 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2788 if (DEBUG_LOADERS) {
2789 Log.d(TAG, "getActivityList took "
2790 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2791 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2792 }
2793 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002794 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002795 if (apps == null || apps.isEmpty()) {
2796 return;
2797 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002798
2799 // Update icon cache
2800 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2801
2802 // If any package icon has changed (app was updated while launcher was dead),
2803 // update the corresponding shortcuts.
2804 if (!updatedPackages.isEmpty()) {
2805 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2806 synchronized (sBgLock) {
2807 for (ItemInfo info : sBgItemsIdMap.values()) {
2808 if (info instanceof ShortcutInfo && user.equals(info.user)
2809 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2810 ShortcutInfo si = (ShortcutInfo) info;
2811 ComponentName cn = si.getTargetComponent();
2812 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2813 si.updateIcon(mIconCache);
2814 updates.add(si);
2815 }
2816 }
2817 }
2818 }
2819
2820 if (!updates.isEmpty()) {
2821 final UserHandleCompat userFinal = user;
2822 mHandler.post(new Runnable() {
2823
2824 public void run() {
2825 Callbacks cb = getCallback();
2826 if (cb != null) {
2827 cb.bindShortcutsChanged(
2828 updates, new ArrayList<ShortcutInfo>(), userFinal);
2829 }
2830 }
2831 });
2832 }
Kenny Guyed131872014-04-30 03:02:21 +01002833 }
Joe Onorato36115782010-06-17 13:28:48 -04002834
Kenny Guyed131872014-04-30 03:02:21 +01002835 // Create the ApplicationInfos
2836 for (int i = 0; i < apps.size(); i++) {
2837 LauncherActivityInfoCompat app = apps.get(i);
2838 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002839 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002840 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002841
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002842 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002843 // Add shortcuts for packages which were installed while launcher was dead.
2844 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2845 + mUserManager.getSerialNumberForUser(user);
2846 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2847 HashSet<String> newPackageSet = new HashSet<String>();
2848
2849 for (LauncherActivityInfoCompat info : apps) {
2850 String packageName = info.getComponentName().getPackageName();
2851 if (!packagesAdded.contains(packageName)
2852 && !newPackageSet.contains(packageName)) {
2853 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2854 }
2855 newPackageSet.add(packageName);
2856 }
2857
2858 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2859 }
Winson Chung64359a52013-07-08 17:17:08 -07002860 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002861 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002862 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2863 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002864
2865 // Post callback on main thread
2866 mHandler.post(new Runnable() {
2867 public void run() {
2868 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002869 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002870 if (callbacks != null) {
2871 callbacks.bindAllApplications(added);
2872 if (DEBUG_LOADERS) {
2873 Log.d(TAG, "bound " + added.size() + " apps in "
2874 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2875 }
2876 } else {
2877 Log.i(TAG, "not binding apps: no Launcher activity");
2878 }
2879 }
2880 });
2881
Joe Onorato36115782010-06-17 13:28:48 -04002882 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002883 Log.d(TAG, "Icons processed in "
2884 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002885 }
2886 }
2887
2888 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002889 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002890 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2891 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2892 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2893 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2894 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2895 }
Joe Onorato36115782010-06-17 13:28:48 -04002896 }
2897 }
2898
2899 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002900 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002901 }
2902
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002903 private class AppsAvailabilityCheck extends BroadcastReceiver {
2904
2905 @Override
2906 public void onReceive(Context context, Intent intent) {
2907 synchronized (sBgLock) {
2908 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2909 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002910 final PackageManager manager = context.getPackageManager();
2911 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2912 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002913 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2914 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002915 packagesRemoved.clear();
2916 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002917 for (String pkg : entry.getValue()) {
2918 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002919 boolean packageOnSdcard = launcherApps.isAppEnabled(
2920 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2921 if (packageOnSdcard) {
2922 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2923 packagesUnavailable.add(pkg);
2924 } else {
2925 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2926 packagesRemoved.add(pkg);
2927 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002928 }
2929 }
2930 if (!packagesRemoved.isEmpty()) {
2931 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2932 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2933 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002934 if (!packagesUnavailable.isEmpty()) {
2935 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2936 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2937 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002938 }
Sunny Goyal34942622014-08-29 17:20:55 -07002939 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002940 }
2941 }
2942 }
2943
Joe Onorato36115782010-06-17 13:28:48 -04002944 private class PackageUpdatedTask implements Runnable {
2945 int mOp;
2946 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002947 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002948
2949 public static final int OP_NONE = 0;
2950 public static final int OP_ADD = 1;
2951 public static final int OP_UPDATE = 2;
2952 public static final int OP_REMOVE = 3; // uninstlled
2953 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2954
2955
Kenny Guyed131872014-04-30 03:02:21 +01002956 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002957 mOp = op;
2958 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002959 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002960 }
2961
2962 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002963 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002964
2965 final String[] packages = mPackages;
2966 final int N = packages.length;
2967 switch (mOp) {
2968 case OP_ADD:
2969 for (int i=0; i<N; i++) {
2970 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002971 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002972 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002973 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002974
2975 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002976 if (ADD_MANAGED_PROFILE_SHORTCUTS
2977 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002978 SharedPreferences prefs = context.getSharedPreferences(
2979 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2980 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2981 + mUserManager.getSerialNumberForUser(mUser);
2982 Set<String> shortcutSet = new HashSet<String>(
2983 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2984
2985 for (int i=0; i<N; i++) {
2986 if (!shortcutSet.contains(packages[i])) {
2987 shortcutSet.add(packages[i]);
2988 List<LauncherActivityInfoCompat> activities =
2989 mLauncherApps.getActivityList(packages[i], mUser);
2990 if (activities != null && !activities.isEmpty()) {
2991 InstallShortcutReceiver.queueInstallShortcut(
2992 activities.get(0), context);
2993 }
2994 }
2995 }
2996
2997 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
2998 }
Joe Onorato36115782010-06-17 13:28:48 -04002999 break;
3000 case OP_UPDATE:
3001 for (int i=0; i<N; i++) {
3002 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003003 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003004 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003005 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003006 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003007 }
3008 break;
3009 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003010 // Remove the packageName for the set of auto-installed shortcuts. This
3011 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003012 if (ADD_MANAGED_PROFILE_SHORTCUTS
3013 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003014 SharedPreferences prefs = context.getSharedPreferences(
3015 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3016 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3017 + mUserManager.getSerialNumberForUser(mUser);
3018 HashSet<String> shortcutSet = new HashSet<String>(
3019 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3020 shortcutSet.removeAll(Arrays.asList(mPackages));
3021 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3022 }
Joe Onorato36115782010-06-17 13:28:48 -04003023 for (int i=0; i<N; i++) {
3024 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003025 mIconCache.removeIconsForPkg(packages[i], mUser);
3026 }
3027 // Fall through
3028 case OP_UNAVAILABLE:
3029 for (int i=0; i<N; i++) {
3030 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3031 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003032 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003033 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003034 }
3035 break;
3036 }
3037
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003038 ArrayList<AppInfo> added = null;
3039 ArrayList<AppInfo> modified = null;
3040 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003041
Adam Cohen487f7dd2012-06-28 18:12:10 -07003042 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003043 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003044 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003045 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003046 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003047 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003048 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003049 }
Winson Chung5d55f332012-07-16 20:45:03 -07003050 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003051 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003052 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003053 }
3054
Sunny Goyale0f58d72014-11-10 18:05:31 -08003055 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003056 if (callbacks == null) {
3057 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3058 return;
3059 }
3060
Sunny Goyal4390ace2014-10-13 11:33:11 -07003061 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3062 new HashMap<ComponentName, AppInfo>();
3063
Joe Onorato36115782010-06-17 13:28:48 -04003064 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003065 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003066 for (AppInfo ai : added) {
3067 addedOrUpdatedApps.put(ai.componentName, ai);
3068 }
Joe Onorato36115782010-06-17 13:28:48 -04003069 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003070
Joe Onorato36115782010-06-17 13:28:48 -04003071 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003072 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003073 for (AppInfo ai : modified) {
3074 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003075 }
3076
Joe Onorato36115782010-06-17 13:28:48 -04003077 mHandler.post(new Runnable() {
3078 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003079 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003080 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003081 callbacks.bindAppsUpdated(modifiedFinal);
3082 }
3083 }
3084 });
3085 }
Winson Chung83892cc2013-05-01 16:53:33 -07003086
Sunny Goyal4390ace2014-10-13 11:33:11 -07003087 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003088 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003089 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3090 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3091 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3092
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003093 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003094 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003095 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003096 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3097 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003098 boolean infoUpdated = false;
3099 boolean shortcutUpdated = false;
3100
3101 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003102 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003103 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003104 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3105 si.iconResource.resourceName, mIconCache, context);
3106 if (icon != null) {
3107 si.setIcon(icon);
3108 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003109 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003110 }
3111 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003112
3113 ComponentName cn = si.getTargetComponent();
3114 if (cn != null && packageSet.contains(cn.getPackageName())) {
3115 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3116
3117 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003118 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3119 // Auto install icon
3120 PackageManager pm = context.getPackageManager();
3121 ResolveInfo matched = pm.resolveActivity(
3122 new Intent(Intent.ACTION_MAIN)
3123 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3124 PackageManager.MATCH_DEFAULT_ONLY);
3125 if (matched == null) {
3126 // Try to find the best match activity.
3127 Intent intent = pm.getLaunchIntentForPackage(
3128 cn.getPackageName());
3129 if (intent != null) {
3130 cn = intent.getComponent();
3131 appInfo = addedOrUpdatedApps.get(cn);
3132 }
3133
3134 if ((intent == null) || (appInfo == null)) {
3135 removedShortcuts.add(si);
3136 continue;
3137 }
3138 si.promisedIntent = intent;
3139 }
3140 }
3141
3142 // Restore the shortcut.
3143 si.intent = si.promisedIntent;
3144 si.promisedIntent = null;
3145 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3146 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3147 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3148
3149 infoUpdated = true;
3150 si.updateIcon(mIconCache);
3151 }
3152
3153 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3154 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3155 si.updateIcon(mIconCache);
3156 si.title = appInfo.title.toString();
3157 si.contentDescription = appInfo.contentDescription;
3158 infoUpdated = true;
3159 }
3160
3161 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3162 // Since package was just updated, the target must be available now.
3163 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3164 shortcutUpdated = true;
3165 }
3166 }
3167
3168 if (infoUpdated || shortcutUpdated) {
3169 updatedShortcuts.add(si);
3170 }
3171 if (infoUpdated) {
3172 updateItemInDatabase(context, si);
3173 }
3174 } else if (info instanceof LauncherAppWidgetInfo) {
3175 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3176 if (mUser.equals(widgetInfo.user)
3177 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3178 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3179 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3180 widgets.add(widgetInfo);
3181 updateItemInDatabase(context, widgetInfo);
3182 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003183 }
3184 }
3185 }
3186
Sunny Goyal4390ace2014-10-13 11:33:11 -07003187 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3188 mHandler.post(new Runnable() {
3189
3190 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003191 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003192 if (callbacks == cb && cb != null) {
3193 callbacks.bindShortcutsChanged(
3194 updatedShortcuts, removedShortcuts, mUser);
3195 }
3196 }
3197 });
3198 if (!removedShortcuts.isEmpty()) {
3199 deleteItemsFromDatabase(context, removedShortcuts);
3200 }
3201 }
3202 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003203 mHandler.post(new Runnable() {
3204 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003205 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003206 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003207 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003208 }
3209 }
3210 });
3211 }
3212 }
3213
Winson Chungdf95eb12013-10-16 14:57:07 -07003214 final ArrayList<String> removedPackageNames =
3215 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003216 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003217 // Mark all packages in the broadcast to be removed
3218 removedPackageNames.addAll(Arrays.asList(packages));
3219 } else if (mOp == OP_UPDATE) {
3220 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003221 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003222 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003223 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003224 }
3225 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003226 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003227
Winson Chungdf95eb12013-10-16 14:57:07 -07003228 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003229 final int removeReason;
3230 if (mOp == OP_UNAVAILABLE) {
3231 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3232 } else {
3233 // Remove all the components associated with this package
3234 for (String pn : removedPackageNames) {
3235 deletePackageFromDatabase(context, pn, mUser);
3236 }
3237 // Remove all the specific components
3238 for (AppInfo a : removedApps) {
3239 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3240 deleteItemsFromDatabase(context, infos);
3241 }
3242 removeReason = 0;
3243 }
3244
Winson Chungdf95eb12013-10-16 14:57:07 -07003245 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003246 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003247 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003248 mHandler.post(new Runnable() {
3249 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003250 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003251 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003252 callbacks.bindComponentsRemoved(
3253 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003254 }
3255 }
3256 });
Joe Onoratobe386092009-11-17 17:32:16 -08003257 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003258
Michael Jurkac402cd92013-05-20 15:49:32 +02003259 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003260 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003261 mHandler.post(new Runnable() {
3262 @Override
3263 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003264 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003265 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003266 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003267 }
3268 }
3269 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003270
3271 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003272 mHandler.post(new Runnable() {
3273 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003274 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003275 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003276 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003277 }
3278 }
3279 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003280 }
3281 }
3282
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003283 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3284 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003285 synchronized (sBgLock) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003286 if (sBgWidgetProviders != null && !refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003287 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3288 }
3289 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3290 List<AppWidgetProviderInfo> widgets =
3291 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3292 LauncherAppWidgetProviderInfo info;
3293 for (AppWidgetProviderInfo pInfo : widgets) {
3294 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3295 sBgWidgetProviders.put(info.provider, info);
3296 }
3297
3298 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3299 for (CustomAppWidget widget : customWidgets) {
3300 info = new LauncherAppWidgetProviderInfo(context, widget);
3301 sBgWidgetProviders.put(info.provider, info);
3302 }
Adam Cohen59400422014-03-05 18:07:04 -08003303 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3304 }
3305 }
3306
3307 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3308 synchronized (sBgLock) {
3309 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003310 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003311 }
3312 return sBgWidgetProviders.get(name);
3313 }
3314 }
3315
Winson Chungb745afb2015-03-02 11:51:23 -08003316 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003317 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003318 PackageManager packageManager = context.getPackageManager();
3319 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003320 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003321 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3322 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003323 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003324 return widgetsAndShortcuts;
3325 }
3326
Kenny Guyed131872014-04-30 03:02:21 +01003327 private static boolean isPackageDisabled(Context context, String packageName,
3328 UserHandleCompat user) {
3329 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3330 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003331 }
Adam Cohen556f6132014-01-15 15:18:08 -08003332
Kenny Guyed131872014-04-30 03:02:21 +01003333 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3334 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003335 if (cn == null) {
3336 return false;
3337 }
Kenny Guyed131872014-04-30 03:02:21 +01003338 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3339 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003340 return false;
3341 }
Kenny Guyed131872014-04-30 03:02:21 +01003342 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003343 }
3344
Adam Cohena28b78e2014-05-20 17:03:04 -07003345 public static boolean isValidPackage(Context context, String packageName,
3346 UserHandleCompat user) {
3347 if (packageName == null) {
3348 return false;
3349 }
3350 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3351 return launcherApps.isPackageEnabledForProfile(packageName, user);
3352 }
3353
Joe Onorato9c1289c2009-08-17 11:03:03 -04003354 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003355 * Make an ShortcutInfo object for a restored application or shortcut item that points
3356 * to a package that is not yet installed on the system.
3357 */
Sunny Goyal34942622014-08-29 17:20:55 -07003358 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003359 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003360 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003361 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003362 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003363
3364 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3365 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3366 if (!TextUtils.isEmpty(title)) {
3367 info.title = title;
3368 }
3369 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3370 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3371 if (TextUtils.isEmpty(info.title)) {
3372 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3373 }
3374 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3375 } else {
3376 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3377 }
3378
Kenny Guyc2bd8102014-06-30 12:30:31 +01003379 info.contentDescription = mUserManager.getBadgedLabelForUser(
3380 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003381 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003382 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003383 return info;
3384 }
3385
3386 /**
3387 * Make an Intent object for a restored application or shortcut item that points
3388 * to the market page for the item.
3389 */
3390 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3391 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003392 return getMarketIntent(componentName.getPackageName());
3393 }
3394
3395 static Intent getMarketIntent(String packageName) {
3396 return new Intent(Intent.ACTION_VIEW)
3397 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003398 .scheme("market")
3399 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003400 .appendQueryParameter("id", packageName)
3401 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003402 }
3403
3404 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003405 * Make an ShortcutInfo object for a shortcut that is an application.
3406 *
3407 * If c is not null, then it will be used to fill in missing data like the title and icon.
3408 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003409 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003410 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003411 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003412 if (user == null) {
3413 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003414 return null;
3415 }
3416
Kenny Guyed131872014-04-30 03:02:21 +01003417 ComponentName componentName = intent.getComponent();
3418 if (componentName == null) {
3419 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3420 return null;
3421 }
3422
3423 Intent newIntent = new Intent(intent.getAction(), null);
3424 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3425 newIntent.setComponent(componentName);
3426 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003427 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003428 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3429 return null;
3430 }
3431
3432 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003433 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003434 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3435 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3436 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003437 }
3438
Joe Onorato56d82912010-03-07 14:32:10 -05003439 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003440 if (TextUtils.isEmpty(info.title) && c != null) {
3441 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003442 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003443
Joe Onorato56d82912010-03-07 14:32:10 -05003444 // fall back to the class name of the activity
3445 if (info.title == null) {
3446 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003447 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003448
Joe Onorato9c1289c2009-08-17 11:03:03 -04003449 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003450 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003451 info.contentDescription = mUserManager.getBadgedLabelForUser(
3452 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003453 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003454 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003455
Winson Chung64359a52013-07-08 17:17:08 -07003456 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3457 ItemInfoFilter f) {
3458 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3459 for (ItemInfo i : infos) {
3460 if (i instanceof ShortcutInfo) {
3461 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003462 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003463 if (cn != null && f.filterItem(null, info, cn)) {
3464 filtered.add(info);
3465 }
3466 } else if (i instanceof FolderInfo) {
3467 FolderInfo info = (FolderInfo) i;
3468 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003469 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003470 if (cn != null && f.filterItem(info, s, cn)) {
3471 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003472 }
3473 }
Winson Chung64359a52013-07-08 17:17:08 -07003474 } else if (i instanceof LauncherAppWidgetInfo) {
3475 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3476 ComponentName cn = info.providerName;
3477 if (cn != null && f.filterItem(null, info, cn)) {
3478 filtered.add(info);
3479 }
Winson Chung8a435102012-08-30 17:16:53 -07003480 }
3481 }
Winson Chung64359a52013-07-08 17:17:08 -07003482 return new ArrayList<ItemInfo>(filtered);
3483 }
3484
Kenny Guyed131872014-04-30 03:02:21 +01003485 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3486 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003487 ItemInfoFilter filter = new ItemInfoFilter() {
3488 @Override
3489 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003490 if (info.user == null) {
3491 return cn.equals(cname);
3492 } else {
3493 return cn.equals(cname) && info.user.equals(user);
3494 }
Winson Chung64359a52013-07-08 17:17:08 -07003495 }
3496 };
3497 return filterItemInfos(sBgItemsIdMap.values(), filter);
3498 }
3499
Sunny Goyal1a745e82014-10-02 15:58:31 -07003500 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003501 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003502 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003503 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003504 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3505 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003506
Joe Onorato56d82912010-03-07 14:32:10 -05003507 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003508 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003509 // Non-app shortcuts are only supported for current user.
3510 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003511 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003512
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003513 // TODO: If there's an explicit component and we can't install that, delete it.
3514
Joe Onorato56d82912010-03-07 14:32:10 -05003515 info.title = c.getString(titleIndex);
3516
Joe Onorato9c1289c2009-08-17 11:03:03 -04003517 int iconType = c.getInt(iconTypeIndex);
3518 switch (iconType) {
3519 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3520 String packageName = c.getString(iconPackageIndex);
3521 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003522 info.customIcon = false;
3523 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003524 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003525 // the db
3526 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003527 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003528 }
3529 // the fallback icon
3530 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003531 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003532 info.usingFallbackIcon = true;
3533 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003534 break;
3535 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003536 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003537 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003538 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003539 info.customIcon = false;
3540 info.usingFallbackIcon = true;
3541 } else {
3542 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003543 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003544 break;
3545 default:
Kenny Guyed131872014-04-30 03:02:21 +01003546 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003547 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003548 info.customIcon = false;
3549 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003550 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003551 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003552 return info;
3553 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003554
Sunny Goyal2350bc92014-10-14 16:42:54 -07003555 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003556 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3557 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3558 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3559
Adam Cohend9198822011-11-22 16:42:47 -08003560 if (intent == null) {
3561 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3562 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3563 return null;
3564 }
3565
Joe Onorato0589f0f2010-02-08 13:44:00 -08003566 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003567 boolean customIcon = false;
3568 ShortcutIconResource iconResource = null;
3569
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003570 if (bitmap instanceof Bitmap) {
3571 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003572 customIcon = true;
3573 } else {
3574 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003575 if (extra instanceof ShortcutIconResource) {
3576 iconResource = (ShortcutIconResource) extra;
3577 icon = Utilities.createIconBitmap(iconResource.packageName,
3578 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003579 }
3580 }
3581
Michael Jurkac9d95c52011-08-29 14:03:34 -07003582 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003583
Kenny Guyed131872014-04-30 03:02:21 +01003584 // Only support intents for current user for now. Intents sent from other
3585 // users wouldn't get here without intent forwarding anyway.
3586 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003587 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003588 icon = mIconCache.getDefaultIcon(info.user);
3589 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003590 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003591 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003592
Joe Onorato0589f0f2010-02-08 13:44:00 -08003593 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003594 info.contentDescription = mUserManager.getBadgedLabelForUser(
3595 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003596 info.intent = intent;
3597 info.customIcon = customIcon;
3598 info.iconResource = iconResource;
3599
3600 return info;
3601 }
3602
Joe Onorato9c1289c2009-08-17 11:03:03 -04003603 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003604 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003605 * or make a new one.
3606 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003607 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003608 // See if a placeholder was created for us already
3609 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003610 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003611 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003612 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003613 folders.put(id, folderInfo);
3614 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003615 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003616 }
3617
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003618 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003619 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003620 return new Comparator<AppInfo>() {
3621 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003622 if (a.user.equals(b.user)) {
3623 int result = collator.compare(a.title.toString().trim(),
3624 b.title.toString().trim());
3625 if (result == 0) {
3626 result = a.componentName.compareTo(b.componentName);
3627 }
3628 return result;
3629 } else {
3630 // TODO Need to figure out rules for sorting
3631 // profiles, this puts work second.
3632 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003633 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003634 }
Winson Chung11904872012-09-17 16:58:46 -07003635 };
3636 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003637 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3638 = new Comparator<AppInfo>() {
3639 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003640 if (a.firstInstallTime < b.firstInstallTime) return 1;
3641 if (a.firstInstallTime > b.firstInstallTime) return -1;
3642 return 0;
3643 }
3644 };
Winson Chung5308f242011-08-18 12:12:41 -07003645 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3646 if (info.activityInfo != null) {
3647 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3648 } else {
3649 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3650 }
3651 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003652
Winson Chung1ed747a2011-05-03 16:18:34 -07003653 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003654 private final AppWidgetManagerCompat mManager;
3655 private final PackageManager mPackageManager;
3656 private final HashMap<Object, String> mLabelCache;
3657 private final Collator mCollator;
3658
3659 WidgetAndShortcutNameComparator(Context context) {
3660 mManager = AppWidgetManagerCompat.getInstance(context);
3661 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003662 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003663 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003664 }
3665 public final int compare(Object a, Object b) {
3666 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003667 if (mLabelCache.containsKey(a)) {
3668 labelA = mLabelCache.get(a);
3669 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003670 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3671 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003672 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003673 mLabelCache.put(a, labelA);
3674 }
3675 if (mLabelCache.containsKey(b)) {
3676 labelB = mLabelCache.get(b);
3677 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003678 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003679 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003680 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003681 mLabelCache.put(b, labelB);
3682 }
Winson Chung11904872012-09-17 16:58:46 -07003683 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003684 }
3685 };
Joe Onoratobe386092009-11-17 17:32:16 -08003686
Sunny Goyal651077b2014-06-30 14:15:31 -07003687 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3688 return (provider != null) && (provider.provider != null)
3689 && (provider.provider.getPackageName() != null);
3690 }
3691
Joe Onoratobe386092009-11-17 17:32:16 -08003692 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003693 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003694 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3695 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3696 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3697 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003698 if (mLoaderTask != null) {
3699 mLoaderTask.dumpState();
3700 } else {
3701 Log.d(TAG, "mLoaderTask=null");
3702 }
Joe Onoratobe386092009-11-17 17:32:16 -08003703 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003704
3705 public Callbacks getCallback() {
3706 return mCallbacks != null ? mCallbacks.get() : null;
3707 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003708}