blob: cb9d12e01496c30669b1ca4e4cce24e1e6afdca0 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Romain Guyedcce092010-03-04 13:03:17 -080061
Michael Jurkac2f801e2011-07-12 14:19:46 -070062import java.lang.ref.WeakReference;
63import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070064import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.text.Collator;
66import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070067import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070068import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070072import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070073import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070074import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070075import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078/**
79 * Maintains in-memory state of the Launcher. It is expected that there should be only one
80 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070081 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 */
Kenny Guyed131872014-04-30 03:02:21 +010083public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010084 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080085 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040086 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070087 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080088 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040089
Joe Onorato9c1289c2009-08-17 11:03:03 -040090 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070091
Dan Sandlerd5024042014-01-09 15:01:33 -050092 public static final int LOADER_FLAG_NONE = 0;
93 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
94 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
95
Joe Onorato36115782010-06-17 13:28:48 -040096 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050097 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080098
Winson Chungee055712013-07-30 14:46:24 -070099 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800100 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400101
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400102 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400103 private final Object mLock = new Object();
104 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400105 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700106 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
Sunny Goyale0f58d72014-11-10 18:05:31 -0800108 /**
109 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
110 */
111 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
112
Winson Chung81b52252012-08-27 15:34:29 -0700113 // Specific runnable types that are run on the main thread deferred handler, this allows us to
114 // clear all queued binding runnables when the Launcher activity is destroyed.
115 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
116 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
117
Jason Monkbbe1e242014-05-16 17:37:34 -0400118 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700119
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700120 private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
121 static {
122 sWorkerThread.start();
123 }
124 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
125
Joe Onoratocc67f472010-06-08 10:54:30 -0700126 // We start off with everything not loaded. After that, we assume that
127 // our monitoring of the package manager provides all updates and we never
128 // need to do a requery. These are only ever touched from the loader thread.
129 private boolean mWorkspaceLoaded;
130 private boolean mAllAppsLoaded;
131
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700132 // When we are loading pages synchronously, we can't just post the binding of items on the side
133 // pages as this delays the rotation process. Instead, we wait for a callback from the first
134 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
135 // a normal load, we also clear this set of Runnables.
136 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
137
Joe Onorato9c1289c2009-08-17 11:03:03 -0400138 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700141 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800142
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700143 // The lock that must be acquired before referencing any static bg data structures. Unlike
144 // other locks, this one can generally be held long-term because we never expect any of these
145 // static data structures to be referenced outside of the worker thread except on the first
146 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700147 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700148
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
154 // created by LauncherModel that are directly on the home screen (however, no widgets or
155 // shortcuts within folders).
156 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157
Adam Cohen487f7dd2012-06-28 18:12:10 -0700158 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
159 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700160 new ArrayList<LauncherAppWidgetInfo>();
161
Adam Cohen487f7dd2012-06-28 18:12:10 -0700162 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
163 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700164
Adam Cohendcd297f2013-06-18 13:13:40 -0700165 // sBgWorkspaceScreens is the ordered set of workspace screens.
166 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
167
Adam Cohen59400422014-03-05 18:07:04 -0800168 // sBgWidgetProviders is the set of widget providers including custom internal widgets
169 public static HashMap<ComponentName, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
170 public static boolean sWidgetProvidersDirty;
171
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700172 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700173 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
174 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700175
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700176 // </ only access in worker thread >
177
178 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179
Reena Lee99a73f32011-10-24 17:27:37 -0700180 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700181
Kenny Guyed131872014-04-30 03:02:21 +0100182 private final LauncherAppsCompat mLauncherApps;
183 private final UserManagerCompat mUserManager;
184
Joe Onorato9c1289c2009-08-17 11:03:03 -0400185 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700186 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400187 public int getCurrentWorkspaceScreen();
188 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700189 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
190 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700191 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700192 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500193 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800194 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400195 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200196 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700197 public void bindAppsAdded(ArrayList<Long> newScreens,
198 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700199 ArrayList<ItemInfo> addAnimated,
200 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200201 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700202 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
203 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
204 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700205 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700206 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700207 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700208 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200209 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100210 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700211 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700212 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700213 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800214 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
215 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400216 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217
Winson Chung64359a52013-07-08 17:17:08 -0700218 public interface ItemInfoFilter {
219 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
220 }
221
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800222 public interface ScreenPosProvider {
223 int getScreenIndex(ArrayList<Long> screenIDs);
224 }
225
Bjorn Bringert1307f632013-10-03 22:31:03 +0100226 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800227 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400228
Winson Chungee055712013-07-30 14:46:24 -0700229 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700230 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400231 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
232 // resource string.
233 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
234 ProviderInfo providerInfo =
235 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
236 ProviderInfo redirectProvider =
237 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700238
239 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400240 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700241
242 if (mOldContentProviderExists) {
243 Log.d(TAG, "Old launcher provider exists.");
244 } else {
245 Log.d(TAG, "Old launcher provider does not exist.");
246 }
247
Daniel Sandlere4f98912013-06-25 15:13:26 -0400248 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100249 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800250 mIconCache = iconCache;
251
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400252 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700253 Configuration config = res.getConfiguration();
254 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100255 mLauncherApps = LauncherAppsCompat.getInstance(context);
256 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800257 }
258
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700259 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
260 * posted on the main thread handler. */
261 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700262 runOnMainThread(r, 0);
263 }
264 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700265 if (sWorkerThread.getThreadId() == Process.myTid()) {
266 // If we are on the worker thread, post onto the main handler
267 mHandler.post(r);
268 } else {
269 r.run();
270 }
271 }
272
273 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
274 * posted on the worker thread handler. */
275 private static void runOnWorkerThread(Runnable r) {
276 if (sWorkerThread.getThreadId() == Process.myTid()) {
277 r.run();
278 } else {
279 // If we are not on the worker thread, then post to the worker handler
280 sWorker.post(r);
281 }
282 }
283
Winson Chunge43a1e72014-01-15 10:33:02 -0800284 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
285 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800286 }
287
Sunny Goyale755d462014-07-22 13:48:29 -0700288 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500289 // Process the updated package state
290 Runnable r = new Runnable() {
291 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800292 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500293 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700294 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500295 }
296 }
297 };
298 mHandler.post(r);
299 }
300
Sunny Goyala22666f2014-09-18 13:25:15 -0700301 public void updatePackageBadge(final String packageName) {
302 // Process the updated package badge
303 Runnable r = new Runnable() {
304 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800305 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700306 if (callbacks != null) {
307 callbacks.updatePackageBadge(packageName);
308 }
309 }
310 };
311 mHandler.post(r);
312 }
313
Adam Cohen76a47a12014-02-05 11:47:43 -0800314 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800315 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800316
317 if (allAppsApps == null) {
318 throw new RuntimeException("allAppsApps must not be null");
319 }
320 if (allAppsApps.isEmpty()) {
321 return;
322 }
323
324 // Process the newly added applications and add them to the database first
325 Runnable r = new Runnable() {
326 public void run() {
327 runOnMainThread(new Runnable() {
328 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800329 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800330 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500331 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800332 }
333 }
334 });
335 }
336 };
337 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700338 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800339
340 public void addAndBindAddedWorkspaceApps(final Context context,
341 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800342 addAndBindAddedWorkspaceApps(context, workspaceApps,
343 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800344
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800345 @Override
346 public int getScreenIndex(ArrayList<Long> screenIDs) {
347 return screenIDs.isEmpty() ? 0 : 1;
348 }
349 }, 1, false);
350 }
351
352 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
353 int[] xy, int spanX, int spanY) {
354 LauncherAppState app = LauncherAppState.getInstance();
355 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
356 final int xCount = (int) grid.numColumns;
357 final int yCount = (int) grid.numRows;
358 boolean[][] occupied = new boolean[xCount][yCount];
359 if (occupiedPos != null) {
360 for (Rect r : occupiedPos) {
361 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
362 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
363 occupied[x][y] = true;
364 }
365 }
366 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800367 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800368 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
369 }
370
371 /**
372 * Find a position on the screen for the given size or adds a new screen.
373 * @return screenId and the coordinates for the item.
374 */
375 private static Pair<Long, int[]> findSpaceForItem(
376 Context context,
377 ScreenPosProvider preferredScreen,
378 int fallbackStartScreen,
379 ArrayList<Long> workspaceScreens,
380 ArrayList<Long> addedWorkspaceScreensFinal,
381 int spanX, int spanY) {
382 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
383 // loadWorkspace() may not have been called.
384 final ContentResolver cr = context.getContentResolver();
385 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
386 new String[] {
387 LauncherSettings.Favorites.SCREEN,
388 LauncherSettings.Favorites.CELLX,
389 LauncherSettings.Favorites.CELLY,
390 LauncherSettings.Favorites.SPANX,
391 LauncherSettings.Favorites.SPANY,
392 LauncherSettings.Favorites.CONTAINER
393 },
394 "container=?",
395 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
396 null);
397
398 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
399 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
400 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
401 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
402 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
403 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
404 try {
405 while (c.moveToNext()) {
406 Rect rect = new Rect();
407 rect.left = c.getInt(cellXIndex);
408 rect.top = c.getInt(cellYIndex);
409 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
410 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
411
412 long screenId = c.getInt(screenIndex);
413 ArrayList<Rect> items = screenItems.get(screenId);
414 if (items == null) {
415 items = new ArrayList<Rect>();
416 screenItems.put(screenId, items);
417 }
418 items.add(rect);
419 }
420 } catch (Exception e) {
421 screenItems.clear();
422 } finally {
423 c.close();
424 }
425
426 // Find appropriate space for the item.
427 long screenId = 0;
428 int[] cordinates = new int[2];
429 boolean found = false;
430
431 int screenCount = workspaceScreens.size();
432 // First check the preferred screen.
433 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
434 if (preferredScreenIndex < screenCount) {
435 screenId = workspaceScreens.get(preferredScreenIndex);
436 found = findNextAvailableIconSpaceInScreen(
437 screenItems.get(screenId), cordinates, spanX, spanY);
438 }
439
440 if (!found) {
441 // Search on any of the screens.
442 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
443 screenId = workspaceScreens.get(screen);
444 if (findNextAvailableIconSpaceInScreen(
445 screenItems.get(screenId), cordinates, spanX, spanY)) {
446 // We found a space for it
447 found = true;
448 break;
449 }
450 }
451 }
452
453 if (!found) {
454 // Still no position found. Add a new screen to the end.
455 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
456
457 // Save the screen id for binding in the workspace
458 workspaceScreens.add(screenId);
459 addedWorkspaceScreensFinal.add(screenId);
460
461 // If we still can't find an empty space, then God help us all!!!
462 if (!findNextAvailableIconSpaceInScreen(
463 screenItems.get(screenId), cordinates, spanX, spanY)) {
464 throw new RuntimeException("Can't find space to add the item");
465 }
466 }
467 return Pair.create(screenId, cordinates);
468 }
469
470 /**
471 * Adds the provided items to the workspace.
472 * @param preferredScreen the screen where we should try to add the app first
473 * @param fallbackStartScreen the screen to start search for empty space if
474 * preferredScreen is not available.
475 */
476 public void addAndBindPendingItem(
477 final Context context,
478 final PendingAddItemInfo addInfo,
479 final ScreenPosProvider preferredScreen,
480 final int fallbackStartScreen) {
481 final Callbacks callbacks = getCallback();
482 // Process the newly added applications and add them to the database first
483 Runnable r = new Runnable() {
484 public void run() {
485 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800486 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800487
488 // Find appropriate space for the item.
489 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
490 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
491 addInfo.spanX,
492 addInfo.spanY);
493 final long screenId = coords.first;
494 final int[] cordinates = coords.second;
495
496 // Update the workspace screens
497 updateWorkspaceScreenOrder(context, workspaceScreens);
498 runOnMainThread(new Runnable() {
499 public void run() {
500 Callbacks cb = getCallback();
501 if (callbacks == cb && cb != null) {
502 cb.bindAddScreens(addedWorkspaceScreensFinal);
503 cb.bindAddPendingItem(addInfo,
504 LauncherSettings.Favorites.CONTAINER_DESKTOP,
505 screenId, cordinates, addInfo.spanX, addInfo.spanY);
506 }
507 }
508 });
509 }
510 };
511 runOnWorkerThread(r);
512 }
513
514 /**
515 * Adds the provided items to the workspace.
516 * @param preferredScreen the screen where we should try to add the app first
517 * @param fallbackStartScreen the screen to start search for empty space if
518 * preferredScreen is not available.
519 */
520 public void addAndBindAddedWorkspaceApps(final Context context,
521 final ArrayList<ItemInfo> workspaceApps,
522 final ScreenPosProvider preferredScreen,
523 final int fallbackStartScreen,
524 final boolean allowDuplicate) {
525 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800526 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700527 return;
Winson Chung997a9232013-07-24 15:33:46 -0700528 }
Winson Chung64359a52013-07-08 17:17:08 -0700529 // Process the newly added applications and add them to the database first
530 Runnable r = new Runnable() {
531 public void run() {
532 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
533 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
534
Winson Chung76828c82013-08-19 15:43:29 -0700535 // Get the list of workspace screens. We need to append to this list and
536 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
537 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800538 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700539 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800540 for (ItemInfo item : workspaceApps) {
541 if (!allowDuplicate) {
542 // Short-circuit this logic if the icon exists somewhere on the workspace
543 if (shortcutExists(context, item.title.toString(),
544 item.getIntent(), item.user)) {
545 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700546 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800547 }
Winson Chung76828c82013-08-19 15:43:29 -0700548
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800549 // Find appropriate space for the item.
550 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
551 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
552 1, 1);
553 long screenId = coords.first;
554 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700555
Winson Chung997a9232013-07-24 15:33:46 -0700556 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800557 if (item instanceof ShortcutInfo) {
558 shortcutInfo = (ShortcutInfo) item;
559 } else if (item instanceof AppInfo) {
560 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700561 } else {
562 throw new RuntimeException("Unexpected info type");
563 }
Winson Chung94d67682013-09-25 16:29:40 -0700564
Winson Chung64359a52013-07-08 17:17:08 -0700565 // Add the shortcut to the db
566 addItemToDatabase(context, shortcutInfo,
567 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800568 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700569 // Save the ShortcutInfo for binding in the workspace
570 addedShortcutsFinal.add(shortcutInfo);
571 }
572 }
573
Winson Chung76828c82013-08-19 15:43:29 -0700574 // Update the workspace screens
575 updateWorkspaceScreenOrder(context, workspaceScreens);
576
Adam Cohen76a47a12014-02-05 11:47:43 -0800577 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700578 runOnMainThread(new Runnable() {
579 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800580 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700581 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700582 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
583 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700584 if (!addedShortcutsFinal.isEmpty()) {
585 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
586 long lastScreenId = info.screenId;
587 for (ItemInfo i : addedShortcutsFinal) {
588 if (i.screenId == lastScreenId) {
589 addAnimated.add(i);
590 } else {
591 addNotAnimated.add(i);
592 }
Winson Chung997a9232013-07-24 15:33:46 -0700593 }
594 }
Winson Chungd64d1762013-08-20 14:37:16 -0700595 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800596 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700597 }
Winson Chung64359a52013-07-08 17:17:08 -0700598 }
Winson Chung997a9232013-07-24 15:33:46 -0700599 });
600 }
Winson Chung64359a52013-07-08 17:17:08 -0700601 }
602 };
603 runOnWorkerThread(r);
604 }
605
Winson Chung81b52252012-08-27 15:34:29 -0700606 public void unbindItemInfosAndClearQueuedBindRunnables() {
607 if (sWorkerThread.getThreadId() == Process.myTid()) {
608 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
609 "main thread");
610 }
611
612 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400613 synchronized (mDeferredBindRunnables) {
614 mDeferredBindRunnables.clear();
615 }
Winson Chung81b52252012-08-27 15:34:29 -0700616 // Remove any queued bind runnables
617 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
618 // Unbind all the workspace items
619 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700620 }
621
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700622 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700623 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700624 // Ensure that we don't use the same workspace items data structure on the main thread
625 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700626 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
627 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700628 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700629 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
630 tmpAppWidgets.addAll(sBgAppWidgets);
631 }
632 Runnable r = new Runnable() {
633 @Override
634 public void run() {
635 for (ItemInfo item : tmpWorkspaceItems) {
636 item.unbind();
637 }
638 for (ItemInfo item : tmpAppWidgets) {
639 item.unbind();
640 }
641 }
642 };
643 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700644 }
645
Joe Onorato9c1289c2009-08-17 11:03:03 -0400646 /**
647 * Adds an item to the DB if it was not created previously, or move it to a new
648 * <container, screen, cellX, cellY>
649 */
650 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400652 if (item.container == ItemInfo.NO_ID) {
653 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700654 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400655 } else {
656 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700657 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 }
659 }
660
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700661 static void checkItemInfoLocked(
662 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
663 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
664 if (modelItem != null && item != modelItem) {
665 // check all the data is consistent
666 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
667 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
668 ShortcutInfo shortcut = (ShortcutInfo) item;
669 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
670 modelShortcut.intent.filterEquals(shortcut.intent) &&
671 modelShortcut.id == shortcut.id &&
672 modelShortcut.itemType == shortcut.itemType &&
673 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700674 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700675 modelShortcut.cellX == shortcut.cellX &&
676 modelShortcut.cellY == shortcut.cellY &&
677 modelShortcut.spanX == shortcut.spanX &&
678 modelShortcut.spanY == shortcut.spanY &&
679 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
680 (modelShortcut.dropPos != null &&
681 shortcut.dropPos != null &&
682 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
683 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
684 // For all intents and purposes, this is the same object
685 return;
686 }
687 }
688
689 // the modelItem needs to match up perfectly with item if our model is
690 // to be consistent with the database-- for now, just require
691 // modelItem == item or the equality check above
692 String msg = "item: " + ((item != null) ? item.toString() : "null") +
693 "modelItem: " +
694 ((modelItem != null) ? modelItem.toString() : "null") +
695 "Error: ItemInfo passed to checkItemInfo doesn't match original";
696 RuntimeException e = new RuntimeException(msg);
697 if (stackTrace != null) {
698 e.setStackTrace(stackTrace);
699 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800700 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700701 }
702 }
703
Michael Jurka816474f2012-06-25 14:49:02 -0700704 static void checkItemInfo(final ItemInfo item) {
705 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
706 final long itemId = item.id;
707 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700708 public void run() {
709 synchronized (sBgLock) {
710 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700711 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700712 }
713 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700714 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700715 }
716
Michael Jurkac9d95c52011-08-29 14:03:34 -0700717 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
718 final ItemInfo item, final String callingFunction) {
719 final long itemId = item.id;
720 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
721 final ContentResolver cr = context.getContentResolver();
722
Adam Cohen487f7dd2012-06-28 18:12:10 -0700723 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700724 Runnable r = new Runnable() {
725 public void run() {
726 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700727 updateItemArrays(item, itemId, stackTrace);
728 }
729 };
730 runOnWorkerThread(r);
731 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700732
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700733 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
734 final ArrayList<ItemInfo> items, final String callingFunction) {
735 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700736
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700737 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
738 Runnable r = new Runnable() {
739 public void run() {
740 ArrayList<ContentProviderOperation> ops =
741 new ArrayList<ContentProviderOperation>();
742 int count = items.size();
743 for (int i = 0; i < count; i++) {
744 ItemInfo item = items.get(i);
745 final long itemId = item.id;
746 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
747 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700748
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700749 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
750 updateItemArrays(item, itemId, stackTrace);
751
752 }
753 try {
754 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
755 } catch (Exception e) {
756 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757 }
758 }
759 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700760 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700761 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700762
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700763 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
764 // Lock on mBgLock *after* the db operation
765 synchronized (sBgLock) {
766 checkItemInfoLocked(itemId, item, stackTrace);
767
768 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
769 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
770 // Item is in a folder, make sure this folder exists
771 if (!sBgFolders.containsKey(item.container)) {
772 // An items container is being set to a that of an item which is not in
773 // the list of Folders.
774 String msg = "item: " + item + " container being set to: " +
775 item.container + ", not in the list of folders";
776 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700777 }
778 }
779
780 // Items are added/removed from the corresponding FolderInfo elsewhere, such
781 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
782 // that are on the desktop, as appropriate
783 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800784 if (modelItem != null &&
785 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
786 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700787 switch (modelItem.itemType) {
788 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
789 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
790 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
791 if (!sBgWorkspaceItems.contains(modelItem)) {
792 sBgWorkspaceItems.add(modelItem);
793 }
794 break;
795 default:
796 break;
797 }
798 } else {
799 sBgWorkspaceItems.remove(modelItem);
800 }
801 }
802 }
803
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800804 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400805 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700806 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700807 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700808 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 item.cellX = cellX;
811 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700812
Winson Chung3d503fb2011-07-13 17:25:49 -0700813 // We store hotseat items in canonical form which is this orientation invariant position
814 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700816 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700817 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700818 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700819 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700820 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400821
822 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400823 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700824 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
825 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800826 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400828
Michael Jurkac9d95c52011-08-29 14:03:34 -0700829 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700830 }
831
832 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700833 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
834 * cellX, cellY have already been updated on the ItemInfos.
835 */
836 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
837 final long container, final int screen) {
838
839 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
840 int count = items.size();
841
842 for (int i = 0; i < count; i++) {
843 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700844 item.container = container;
845
846 // We store hotseat items in canonical form which is this orientation invariant position
847 // in the hotseat
848 if (context instanceof Launcher && screen < 0 &&
849 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700850 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700851 item.cellY);
852 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700853 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700854 }
855
856 final ContentValues values = new ContentValues();
857 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
858 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
859 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800860 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700861 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700862
863 contentValues.add(values);
864 }
865 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
866 }
867
868 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700869 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800870 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700871 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700872 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700873 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800874 item.cellX = cellX;
875 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700876 item.spanX = spanX;
877 item.spanY = spanY;
878
879 // We store hotseat items in canonical form which is this orientation invariant position
880 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700881 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700882 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700883 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700884 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700885 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700886 }
Adam Cohend4844c32011-02-18 19:25:06 -0800887
Adam Cohend4844c32011-02-18 19:25:06 -0800888 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800889 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700890 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
891 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800892 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700893 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
894 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700895 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800896
Michael Jurka816474f2012-06-25 14:49:02 -0700897 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700898 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700899
900 /**
901 * Update an item to the database in a specified container.
902 */
903 static void updateItemInDatabase(Context context, final ItemInfo item) {
904 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100905 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700906 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800907 }
908
909 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400910 * Returns true if the shortcuts already exists in the database.
911 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800912 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800913 static boolean shortcutExists(Context context, String title, Intent intent,
914 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400915 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700916 final Intent intentWithPkg, intentWithoutPkg;
917
918 if (intent.getComponent() != null) {
919 // If component is not null, an intent with null package will produce
920 // the same result and should also be a match.
921 if (intent.getPackage() != null) {
922 intentWithPkg = intent;
923 intentWithoutPkg = new Intent(intent).setPackage(null);
924 } else {
925 intentWithPkg = new Intent(intent).setPackage(
926 intent.getComponent().getPackageName());
927 intentWithoutPkg = intent;
928 }
929 } else {
930 intentWithPkg = intent;
931 intentWithoutPkg = intent;
932 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800933 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
934 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400935 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800936 new String[] { "title", "intent", "profileId" },
937 "title=? and (intent=? or intent=?) and profileId=?",
938 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
939 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400940 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800941 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400942 } finally {
943 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800944 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700945 }
946
Joe Onorato9c1289c2009-08-17 11:03:03 -0400947 /**
948 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
949 */
950 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
951 final ContentResolver cr = context.getContentResolver();
952 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
953 "_id=? and (itemType=? or itemType=?)",
954 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700955 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700956
Joe Onorato9c1289c2009-08-17 11:03:03 -0400957 try {
958 if (c.moveToFirst()) {
959 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
960 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
961 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
962 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
963 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
964 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
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);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400979
980 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700981 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982 } finally {
983 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700984 }
985
986 return null;
987 }
988
Joe Onorato9c1289c2009-08-17 11:03:03 -0400989 /**
990 * Add an item to the database in a specified container. Sets the container, screen, cellX and
991 * cellY fields of the item. Also assigns an ID to the item.
992 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700993 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700994 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400996 item.cellX = cellX;
997 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700998 // We store hotseat items in canonical form which is this orientation invariant position
999 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001000 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001003 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001005 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006
1007 final ContentValues values = new ContentValues();
1008 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001009 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001010
Michael Jurka414300a2013-08-27 15:42:35 +02001011 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001012 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001013
Jason Monk8e19cf22014-03-20 15:06:57 -04001014 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001015 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001016 public void run() {
1017 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1018 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001019
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001020 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001021 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001022 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001023 sBgItemsIdMap.put(item.id, item);
1024 switch (item.itemType) {
1025 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1026 sBgFolders.put(item.id, (FolderInfo) item);
1027 // Fall through
1028 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1029 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1030 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1031 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1032 sBgWorkspaceItems.add(item);
1033 } else {
1034 if (!sBgFolders.containsKey(item.container)) {
1035 // Adding an item to a folder that doesn't exist.
1036 String msg = "adding item: " + item + " to a folder that " +
1037 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001038 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001040 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 break;
1042 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1043 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1044 break;
1045 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001046 }
1047 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001048 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001049 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001050 }
1051
Joe Onorato9c1289c2009-08-17 11:03:03 -04001052 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001053 * Creates a new unique child id, for a given cell span across all layouts.
1054 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001055 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001056 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001057 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001058 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001059 }
1060
Sunny Goyal34942622014-08-29 17:20:55 -07001061 private static ArrayList<ItemInfo> getItemsByPackageName(
1062 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001063 ItemInfoFilter filter = new ItemInfoFilter() {
1064 @Override
1065 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1066 return cn.getPackageName().equals(pn) && info.user.equals(user);
1067 }
1068 };
Sunny Goyal34942622014-08-29 17:20:55 -07001069 return filterItemInfos(sBgItemsIdMap.values(), filter);
1070 }
1071
1072 /**
1073 * Removes all the items from the database corresponding to the specified package.
1074 */
1075 static void deletePackageFromDatabase(Context context, final String pn,
1076 final UserHandleCompat user) {
1077 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001078 }
1079
1080 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001081 * Removes the specified item from the database
1082 * @param context
1083 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001084 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001085 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001086 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1087 items.add(item);
1088 deleteItemsFromDatabase(context, items);
1089 }
1090
1091 /**
1092 * Removes the specified items from the database
1093 * @param context
1094 * @param item
1095 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001096 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001097 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001098
Michael Jurka83df1882011-08-31 20:59:26 -07001099 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001100 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001101 for (ItemInfo item : items) {
1102 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1103 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001104
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001105 // Lock on mBgLock *after* the db operation
1106 synchronized (sBgLock) {
1107 switch (item.itemType) {
1108 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1109 sBgFolders.remove(item.id);
1110 for (ItemInfo info: sBgItemsIdMap.values()) {
1111 if (info.container == item.id) {
1112 // We are deleting a folder which still contains items that
1113 // think they are contained by that folder.
1114 String msg = "deleting a folder (" + item + ") which still " +
1115 "contains items (" + info + ")";
1116 Log.e(TAG, msg);
1117 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001118 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001119 sBgWorkspaceItems.remove(item);
1120 break;
1121 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1122 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1123 sBgWorkspaceItems.remove(item);
1124 break;
1125 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1126 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1127 break;
1128 }
1129 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001130 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001131 }
1132 }
Michael Jurka83df1882011-08-31 20:59:26 -07001133 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001134 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001135 }
1136
1137 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001138 * Update the order of the workspace screens in the database. The array list contains
1139 * a list of screen ids in the order that they should appear.
1140 */
Winson Chungc9168342013-06-26 14:54:55 -07001141 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001142 // Log to disk
1143 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1144 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1145
Winson Chung64359a52013-07-08 17:17:08 -07001146 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001147 final ContentResolver cr = context.getContentResolver();
1148 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1149
1150 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001151 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001152 while (iter.hasNext()) {
1153 long id = iter.next();
1154 if (id < 0) {
1155 iter.remove();
1156 }
1157 }
1158
1159 Runnable r = new Runnable() {
1160 @Override
1161 public void run() {
Yura085c8532014-02-11 15:15:29 +00001162 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001164 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001165 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 for (int i = 0; i < count; i++) {
1167 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001168 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1170 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001171 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 }
Yura085c8532014-02-11 15:15:29 +00001173
1174 try {
1175 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1176 } catch (Exception ex) {
1177 throw new RuntimeException(ex);
1178 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001179
Winson Chungba9c37f2013-08-30 14:11:37 -07001180 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001181 sBgWorkspaceScreens.clear();
1182 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001183 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001184 }
1185 };
1186 runOnWorkerThread(r);
1187 }
1188
1189 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001190 * Remove the contents of the specified folder from the database
1191 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001192 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193 final ContentResolver cr = context.getContentResolver();
1194
Michael Jurkac9d95c52011-08-29 14:03:34 -07001195 Runnable r = new Runnable() {
1196 public void run() {
1197 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001198 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001199 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001200 sBgItemsIdMap.remove(info.id);
1201 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001202 sBgWorkspaceItems.remove(info);
1203 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001204
Michael Jurkac9d95c52011-08-29 14:03:34 -07001205 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1206 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001207 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001208 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001209 for (ItemInfo childInfo : info.contents) {
1210 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001212 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001213 }
1214 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001215 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001216 }
1217
1218 /**
1219 * Set this as the current Launcher activity object for the loader.
1220 */
1221 public void initialize(Callbacks callbacks) {
1222 synchronized (mLock) {
1223 mCallbacks = new WeakReference<Callbacks>(callbacks);
1224 }
1225 }
1226
Kenny Guyed131872014-04-30 03:02:21 +01001227 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001228 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001229 int op = PackageUpdatedTask.OP_UPDATE;
1230 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1231 user));
1232 }
1233
1234 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001235 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001236 int op = PackageUpdatedTask.OP_REMOVE;
1237 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1238 user));
1239 }
1240
1241 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001242 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001243 int op = PackageUpdatedTask.OP_ADD;
1244 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1245 user));
1246 }
1247
1248 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001249 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001250 boolean replacing) {
1251 if (!replacing) {
1252 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1253 user));
1254 if (mAppsCanBeOnRemoveableStorage) {
1255 // Only rebind if we support removable storage. It catches the
1256 // case where
1257 // apps on the external sd card need to be reloaded
1258 startLoaderFromBackground();
1259 }
1260 } else {
1261 // If we are replacing then just update the packages in the list
1262 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1263 packageNames, user));
1264 }
1265 }
1266
1267 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001268 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001269 boolean replacing) {
1270 if (!replacing) {
1271 enqueuePackageUpdated(new PackageUpdatedTask(
1272 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1273 user));
1274 }
Kenny Guyed131872014-04-30 03:02:21 +01001275 }
1276
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001277 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001278 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1279 * ACTION_PACKAGE_CHANGED.
1280 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001281 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001282 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001283 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001284
Joe Onorato36115782010-06-17 13:28:48 -04001285 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001286 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001287 // If we have changed locale we need to clear out the labels in all apps/workspace.
1288 forceReload();
1289 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1290 // Check if configuration change was an mcc/mnc change which would affect app resources
1291 // and we would need to clear out the labels in all apps/workspace. Same handling as
1292 // above for ACTION_LOCALE_CHANGED
1293 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001294 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001295 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001296 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001297 forceReload();
1298 }
1299 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001300 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001301 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1302 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001303 Callbacks callbacks = getCallback();
1304 if (callbacks != null) {
1305 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001306 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001307 }
1308 }
1309
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001310 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001311 resetLoadedState(true, true);
1312
Reena Lee93f824a2011-09-23 17:20:28 -07001313 // Do this here because if the launcher activity is running it will be restarted.
1314 // If it's not running startLoaderFromBackground will merely tell it that it needs
1315 // to reload.
1316 startLoaderFromBackground();
1317 }
1318
Winson Chungf0c6ae02012-03-21 16:10:31 -07001319 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1320 synchronized (mLock) {
1321 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1322 // mWorkspaceLoaded to true later
1323 stopLoaderLocked();
1324 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1325 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1326 }
1327 }
1328
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001329 /**
1330 * When the launcher is in the background, it's possible for it to miss paired
1331 * configuration changes. So whenever we trigger the loader from the background
1332 * tell the launcher that it needs to re-run the loader when it comes back instead
1333 * of doing it now.
1334 */
1335 public void startLoaderFromBackground() {
1336 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001337 Callbacks callbacks = getCallback();
1338 if (callbacks != null) {
1339 // Only actually run the loader if they're not paused.
1340 if (!callbacks.setLoadOnResume()) {
1341 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001342 }
1343 }
1344 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001345 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001346 }
Joe Onorato36115782010-06-17 13:28:48 -04001347 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001348
Reena Lee93f824a2011-09-23 17:20:28 -07001349 // If there is already a loader task running, tell it to stop.
1350 // returns true if isLaunching() was true on the old task
1351 private boolean stopLoaderLocked() {
1352 boolean isLaunching = false;
1353 LoaderTask oldTask = mLoaderTask;
1354 if (oldTask != null) {
1355 if (oldTask.isLaunching()) {
1356 isLaunching = true;
1357 }
1358 oldTask.stopLocked();
1359 }
1360 return isLaunching;
1361 }
1362
Adam Cohen1a85c582014-09-30 09:48:49 -07001363 public boolean isCurrentCallbacks(Callbacks callbacks) {
1364 return (mCallbacks != null && mCallbacks.get() == callbacks);
1365 }
1366
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001367 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001368 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1369 }
1370
1371 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001372 synchronized (mLock) {
1373 if (DEBUG_LOADERS) {
1374 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1375 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001376
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001377 // Clear any deferred bind-runnables from the synchronized load process
1378 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001379 synchronized (mDeferredBindRunnables) {
1380 mDeferredBindRunnables.clear();
1381 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001382
Joe Onorato36115782010-06-17 13:28:48 -04001383 // Don't bother to start the thread if we know it's not going to do anything
1384 if (mCallbacks != null && mCallbacks.get() != null) {
1385 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001386 // also, don't downgrade isLaunching if we're already running
1387 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001388 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001389 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1390 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001391 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1392 } else {
1393 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1394 sWorker.post(mLoaderTask);
1395 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001396 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001397 }
1398 }
1399
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001400 void bindRemainingSynchronousPages() {
1401 // Post the remaining side pages to be loaded
1402 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001403 Runnable[] deferredBindRunnables = null;
1404 synchronized (mDeferredBindRunnables) {
1405 deferredBindRunnables = mDeferredBindRunnables.toArray(
1406 new Runnable[mDeferredBindRunnables.size()]);
1407 mDeferredBindRunnables.clear();
1408 }
1409 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001410 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001412 }
1413 }
1414
Joe Onorato36115782010-06-17 13:28:48 -04001415 public void stopLoader() {
1416 synchronized (mLock) {
1417 if (mLoaderTask != null) {
1418 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001419 }
1420 }
Joe Onorato36115782010-06-17 13:28:48 -04001421 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001422
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001423 /**
1424 * Loads the workspace screen ids in an ordered list.
1425 */
1426 private static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001427 final ContentResolver contentResolver = context.getContentResolver();
1428 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001429
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001430 // Get screens ordered by rank.
1431 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1432 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1433 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001434 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001435 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001436 while (sc.moveToNext()) {
1437 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001438 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001439 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001440 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1441 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001442 }
1443 }
1444 } finally {
1445 sc.close();
1446 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001447 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001448 }
1449
Michael Jurkac57b7a82011-08-09 22:02:20 -07001450 public boolean isAllAppsLoaded() {
1451 return mAllAppsLoaded;
1452 }
1453
Winson Chung36a62fe2012-05-06 18:04:42 -07001454 boolean isLoadingWorkspace() {
1455 synchronized (mLock) {
1456 if (mLoaderTask != null) {
1457 return mLoaderTask.isLoadingWorkspace();
1458 }
1459 }
1460 return false;
1461 }
1462
Joe Onorato36115782010-06-17 13:28:48 -04001463 /**
1464 * Runnable for the thread that loads the contents of the launcher:
1465 * - workspace icons
1466 * - widgets
1467 * - all apps icons
1468 */
1469 private class LoaderTask implements Runnable {
1470 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001471 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001472 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mStopped;
1474 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001475 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001476
Dan Sandlerd5024042014-01-09 15:01:33 -05001477 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001478 mContext = context;
1479 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001480 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001481 }
1482
Joe Onorato36115782010-06-17 13:28:48 -04001483 boolean isLaunching() {
1484 return mIsLaunching;
1485 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001486
Winson Chung36a62fe2012-05-06 18:04:42 -07001487 boolean isLoadingWorkspace() {
1488 return mIsLoadingAndBindingWorkspace;
1489 }
1490
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001491 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001492 mIsLoadingAndBindingWorkspace = true;
1493
Joe Onorato36115782010-06-17 13:28:48 -04001494 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001495 if (DEBUG_LOADERS) {
1496 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001497 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001498
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001499 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001500 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001501 synchronized (LoaderTask.this) {
1502 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001503 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001504 }
1505 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001506 }
1507 }
1508
Joe Onorato36115782010-06-17 13:28:48 -04001509 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001510 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001511 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001512
Joe Onorato36115782010-06-17 13:28:48 -04001513 private void waitForIdle() {
1514 // Wait until the either we're stopped or the other threads are done.
1515 // This way we don't start loading all apps until the workspace has settled
1516 // down.
1517 synchronized (LoaderTask.this) {
1518 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001519
Joe Onorato36115782010-06-17 13:28:48 -04001520 mHandler.postIdle(new Runnable() {
1521 public void run() {
1522 synchronized (LoaderTask.this) {
1523 mLoadAndBindStepFinished = true;
1524 if (DEBUG_LOADERS) {
1525 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001526 }
Joe Onorato36115782010-06-17 13:28:48 -04001527 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001528 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001529 }
Joe Onorato36115782010-06-17 13:28:48 -04001530 });
1531
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001532 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001533 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001534 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1535 // wait no longer than 1sec at a time
1536 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001537 } catch (InterruptedException ex) {
1538 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001539 }
1540 }
Joe Onorato36115782010-06-17 13:28:48 -04001541 if (DEBUG_LOADERS) {
1542 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001543 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001544 + "ms for previous step to finish binding");
1545 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001546 }
Joe Onorato36115782010-06-17 13:28:48 -04001547 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001548
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001549 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001550 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001551 // Ensure that we have a valid page index to load synchronously
1552 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1553 "valid page index");
1554 }
1555 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1556 // Ensure that we don't try and bind a specified page when the pages have not been
1557 // loaded already (we should load everything asynchronously in that case)
1558 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1559 }
1560 synchronized (mLock) {
1561 if (mIsLoaderTaskRunning) {
1562 // Ensure that we are never running the background loading at this point since
1563 // we also touch the background collections
1564 throw new RuntimeException("Error! Background loading is already running");
1565 }
1566 }
1567
1568 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1569 // data structures, we can't allow any other thread to touch that data, but because
1570 // this call is synchronous, we can get away with not locking).
1571
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001572 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001573 // operations from the previous activity. We need to ensure that all queued operations
1574 // are executed before any synchronous binding work is done.
1575 mHandler.flush();
1576
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001577 // Divide the set of loaded items into those that we are binding synchronously, and
1578 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001579 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001580 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1581 // arise from that.
1582 onlyBindAllApps();
1583 }
1584
Joe Onorato36115782010-06-17 13:28:48 -04001585 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 synchronized (mLock) {
1587 mIsLoaderTaskRunning = true;
1588 }
Joe Onorato36115782010-06-17 13:28:48 -04001589 // Optimize for end-user experience: if the Launcher is up and // running with the
1590 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1591 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001592 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001593 // Elevate priority when Home launches for the first time to avoid
1594 // starving at boot time. Staring at a blank home is not cool.
1595 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001596 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1597 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001598 android.os.Process.setThreadPriority(mIsLaunching
1599 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1600 }
Winson Chung64359a52013-07-08 17:17:08 -07001601 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001602 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001603
Joe Onorato36115782010-06-17 13:28:48 -04001604 if (mStopped) {
1605 break keep_running;
1606 }
1607
1608 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1609 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001610 synchronized (mLock) {
1611 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001612 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001613 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614 }
1615 }
Joe Onorato36115782010-06-17 13:28:48 -04001616 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001617
1618 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001619 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1620 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001621
1622 // Restore the default thread priority after we are done loading items
1623 synchronized (mLock) {
1624 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625 }
Joe Onorato36115782010-06-17 13:28:48 -04001626 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001627
Joe Onorato36115782010-06-17 13:28:48 -04001628 // Clear out this reference, otherwise we end up holding it until all of the
1629 // callback runnables are done.
1630 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001631
Joe Onorato36115782010-06-17 13:28:48 -04001632 synchronized (mLock) {
1633 // If we are still the last one to be scheduled, remove ourselves.
1634 if (mLoaderTask == this) {
1635 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001636 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001637 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001638 }
Joe Onorato36115782010-06-17 13:28:48 -04001639 }
1640
1641 public void stopLocked() {
1642 synchronized (LoaderTask.this) {
1643 mStopped = true;
1644 this.notify();
1645 }
1646 }
1647
1648 /**
1649 * Gets the callbacks object. If we've been stopped, or if the launcher object
1650 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1651 * object that was around when the deferred message was scheduled, and if there's
1652 * a new Callbacks object around then also return null. This will save us from
1653 * calling onto it with data that will be ignored.
1654 */
1655 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1656 synchronized (mLock) {
1657 if (mStopped) {
1658 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001659 }
Joe Onorato36115782010-06-17 13:28:48 -04001660
1661 if (mCallbacks == null) {
1662 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001663 }
Joe Onorato36115782010-06-17 13:28:48 -04001664
1665 final Callbacks callbacks = mCallbacks.get();
1666 if (callbacks != oldCallbacks) {
1667 return null;
1668 }
1669 if (callbacks == null) {
1670 Log.w(TAG, "no mCallbacks");
1671 return null;
1672 }
1673
1674 return callbacks;
1675 }
1676 }
1677
1678 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001679 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001680 LauncherAppState app = LauncherAppState.getInstance();
1681 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001682 final int countX = (int) grid.numColumns;
1683 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001684
Adam Cohendcd297f2013-06-18 13:13:40 -07001685 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001686 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001687 // Return early if we detect that an item is under the hotseat button
1688 if (mCallbacks == null ||
1689 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001690 Log.e(TAG, "Error loading shortcut into hotseat " + item
1691 + " into position (" + item.screenId + ":" + item.cellX + ","
1692 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001693 return false;
1694 }
1695
Dan Sandler295ae182013-12-10 16:05:47 -05001696 final ItemInfo[][] hotseatItems =
1697 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1698
Adam Cohenae4409d2013-11-26 10:34:59 -08001699 if (item.screenId >= grid.numHotseatIcons) {
1700 Log.e(TAG, "Error loading shortcut " + item
1701 + " into hotseat position " + item.screenId
1702 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1703 + ")");
1704 return false;
1705 }
1706
Dan Sandler295ae182013-12-10 16:05:47 -05001707 if (hotseatItems != null) {
1708 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001709 Log.e(TAG, "Error loading shortcut into hotseat " + item
1710 + " into position (" + item.screenId + ":" + item.cellX + ","
1711 + item.cellY + ") occupied by "
1712 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1713 [(int) item.screenId][0]);
1714 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001715 } else {
1716 hotseatItems[(int) item.screenId][0] = item;
1717 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001718 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001719 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001720 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001721 items[(int) item.screenId][0] = item;
1722 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001723 return true;
1724 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001725 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1726 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001727 return true;
1728 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001729
Adam Cohendcd297f2013-06-18 13:13:40 -07001730 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001731 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 occupied.put(item.screenId, items);
1733 }
1734
Dan Sandler295ae182013-12-10 16:05:47 -05001735 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001736 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1737 item.cellX < 0 || item.cellY < 0 ||
1738 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1739 Log.e(TAG, "Error loading shortcut " + item
1740 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1741 + item.cellX + "," + item.cellY
1742 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1743 return false;
1744 }
1745
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001746 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001747 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1748 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001749 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001750 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001751 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001752 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001753 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001755 return false;
1756 }
1757 }
1758 }
1759 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1760 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001761 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001762 }
1763 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001764
Joe Onorato36115782010-06-17 13:28:48 -04001765 return true;
1766 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001767
Winson Chungba9c37f2013-08-30 14:11:37 -07001768 /** Clears all the sBg data structures */
1769 private void clearSBgDataStructures() {
1770 synchronized (sBgLock) {
1771 sBgWorkspaceItems.clear();
1772 sBgAppWidgets.clear();
1773 sBgFolders.clear();
1774 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001775 sBgWorkspaceScreens.clear();
1776 }
1777 }
1778
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001779 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001780 // Log to disk
1781 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1782
Joe Onorato36115782010-06-17 13:28:48 -04001783 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001784
Joe Onorato36115782010-06-17 13:28:48 -04001785 final Context context = mContext;
1786 final ContentResolver contentResolver = context.getContentResolver();
1787 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001788 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001789 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1790 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001791 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001792
Winson Chung892c74d2013-08-22 16:15:50 -07001793 LauncherAppState app = LauncherAppState.getInstance();
1794 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1795 int countX = (int) grid.numColumns;
1796 int countY = (int) grid.numRows;
1797
Dan Sandlerd5024042014-01-09 15:01:33 -05001798 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1799 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1800 LauncherAppState.getLauncherProvider().deleteDatabase();
1801 }
1802
1803 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1804 // append the user's Launcher2 shortcuts
1805 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1806 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1807 } else {
1808 // Make sure the default workspace is loaded
1809 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001810 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001811 }
Adam Cohene25af792013-06-06 23:08:25 -07001812
Winson Chung2abf94d2012-07-18 18:16:38 -07001813 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001814 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001815 final HashSet<String> installingPkgs = PackageInstallerCompat
1816 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001817
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001818 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001819 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001820 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001821 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001822 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001823
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001824 // +1 for the hotseat (it can be larger than the workspace)
1825 // Load workspace in reverse order to ensure that latest items are loaded first (and
1826 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001827 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001828
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001829 try {
1830 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1831 final int intentIndex = c.getColumnIndexOrThrow
1832 (LauncherSettings.Favorites.INTENT);
1833 final int titleIndex = c.getColumnIndexOrThrow
1834 (LauncherSettings.Favorites.TITLE);
1835 final int iconTypeIndex = c.getColumnIndexOrThrow(
1836 LauncherSettings.Favorites.ICON_TYPE);
1837 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1838 final int iconPackageIndex = c.getColumnIndexOrThrow(
1839 LauncherSettings.Favorites.ICON_PACKAGE);
1840 final int iconResourceIndex = c.getColumnIndexOrThrow(
1841 LauncherSettings.Favorites.ICON_RESOURCE);
1842 final int containerIndex = c.getColumnIndexOrThrow(
1843 LauncherSettings.Favorites.CONTAINER);
1844 final int itemTypeIndex = c.getColumnIndexOrThrow(
1845 LauncherSettings.Favorites.ITEM_TYPE);
1846 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1847 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001848 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1849 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001850 final int screenIndex = c.getColumnIndexOrThrow(
1851 LauncherSettings.Favorites.SCREEN);
1852 final int cellXIndex = c.getColumnIndexOrThrow
1853 (LauncherSettings.Favorites.CELLX);
1854 final int cellYIndex = c.getColumnIndexOrThrow
1855 (LauncherSettings.Favorites.CELLY);
1856 final int spanXIndex = c.getColumnIndexOrThrow
1857 (LauncherSettings.Favorites.SPANX);
1858 final int spanYIndex = c.getColumnIndexOrThrow(
1859 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001860 final int rankIndex = c.getColumnIndexOrThrow(
1861 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001862 final int restoredIndex = c.getColumnIndexOrThrow(
1863 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001864 final int profileIdIndex = c.getColumnIndexOrThrow(
1865 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001866 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1867 //final int displayModeIndex = c.getColumnIndexOrThrow(
1868 // LauncherSettings.Favorites.DISPLAY_MODE);
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 Goyalbb3b02f2015-01-15 12:00:14 -08002021 if (itemReplaced) {
2022 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002023 info = getAppShortcutInfo(manager, intent, user, context, null,
2024 iconIndex, titleIndex, false);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002025 } else {
2026 // Don't replace items for other profiles.
2027 itemsToRemove.add(id);
2028 continue;
2029 }
2030 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002031 if (user.equals(UserHandleCompat.myUserHandle())) {
2032 Launcher.addDumpLog(TAG,
2033 "constructing info for partially restored package",
2034 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002035 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002036 intent = getRestoredItemIntent(c, context, intent);
2037 } else {
2038 // Don't restore items for other profiles.
2039 itemsToRemove.add(id);
2040 continue;
2041 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002042 } else if (itemType ==
2043 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002044 info = getAppShortcutInfo(manager, intent, user, context, c,
2045 iconIndex, titleIndex, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002046 } else {
2047 info = getShortcutInfo(c, context, iconTypeIndex,
2048 iconPackageIndex, iconResourceIndex, iconIndex,
2049 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002050
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002051 // App shortcuts that used to be automatically added to Launcher
2052 // didn't always have the correct intent flags set, so do that
2053 // here
2054 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002055 intent.getCategories() != null &&
2056 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002057 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002058 intent.addFlags(
2059 Intent.FLAG_ACTIVITY_NEW_TASK |
2060 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2061 }
Michael Jurka96879562012-03-22 05:54:33 -07002062 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002063
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002064 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002065 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002066 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002067 container = c.getInt(containerIndex);
2068 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002069 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002070 info.cellX = c.getInt(cellXIndex);
2071 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002072 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002073 info.spanX = 1;
2074 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002075 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002076 info.isDisabled = disabledState;
2077 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2078 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2079 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002080
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002081 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002082 if (!checkItemPlacement(occupied, info)) {
2083 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 break;
2085 }
2086
2087 switch (container) {
2088 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2089 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2090 sBgWorkspaceItems.add(info);
2091 break;
2092 default:
2093 // Item is in a user folder
2094 FolderInfo folderInfo =
2095 findOrMakeFolder(sBgFolders, container);
2096 folderInfo.add(info);
2097 break;
2098 }
2099 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002100 } else {
2101 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002102 }
2103 break;
2104
2105 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2106 id = c.getLong(idIndex);
2107 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2108
2109 folderInfo.title = c.getString(titleIndex);
2110 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002111 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002113 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002114 folderInfo.cellX = c.getInt(cellXIndex);
2115 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002116 folderInfo.spanX = 1;
2117 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002118
Daniel Sandler8802e962010-05-26 16:28:16 -04002119 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002120 if (!checkItemPlacement(occupied, folderInfo)) {
2121 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002122 break;
2123 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002124
Joe Onorato9c1289c2009-08-17 11:03:03 -04002125 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002126 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2127 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2128 sBgWorkspaceItems.add(folderInfo);
2129 break;
Joe Onorato36115782010-06-17 13:28:48 -04002130 }
Joe Onorato17a89222011-02-08 17:26:11 -08002131
Chris Wrenf4d08112014-01-16 18:13:56 -05002132 if (restored) {
2133 // no special handling required for restored folders
2134 restoredRows.add(id);
2135 }
2136
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2138 sBgFolders.put(folderInfo.id, folderInfo);
2139 break;
2140
2141 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002142 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002143 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002144 boolean customWidget = itemType ==
2145 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2146
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002148 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002149 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002150 final ComponentName component =
2151 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002152
Sunny Goyal651077b2014-06-30 14:15:31 -07002153 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002154 final boolean isIdValid = (restoreStatus &
2155 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002156
Sunny Goyalff572272014-07-23 13:58:07 -07002157 final boolean wasProviderReady = (restoreStatus &
2158 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002159
Adam Cohen59400422014-03-05 18:07:04 -08002160 final LauncherAppWidgetProviderInfo provider =
2161 LauncherModel.getProviderInfo(context,
2162 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002163
2164 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002165 if (!isSafeMode && !customWidget &&
2166 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002167 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002168 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002169
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002170 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002171 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002172 itemsToRemove.add(id);
2173 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002174 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002175 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2176 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002177
2178 if (!customWidget) {
2179 int[] minSpan =
2180 Launcher.getMinSpanForWidget(context, provider);
2181 appWidgetInfo.minSpanX = minSpan[0];
2182 appWidgetInfo.minSpanY = minSpan[1];
2183 }
Sunny Goyalff572272014-07-23 13:58:07 -07002184
2185 int status = restoreStatus;
2186 if (!wasProviderReady) {
2187 // If provider was not previously ready, update the
2188 // status and UI flag.
2189
2190 // Id would be valid only if the widget restore broadcast was received.
2191 if (isIdValid) {
2192 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2193 } else {
2194 status &= ~LauncherAppWidgetInfo
2195 .FLAG_PROVIDER_NOT_READY;
2196 }
2197 }
2198 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002199 } else {
2200 Log.v(TAG, "Widget restore pending id=" + id
2201 + " appWidgetId=" + appWidgetId
2202 + " status =" + restoreStatus);
2203 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002204 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002205 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002206
2207 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2208 // Restore has started once.
2209 } else if (installingPkgs.contains(component.getPackageName())) {
2210 // App restore has started. Update the flag
2211 appWidgetInfo.restoreStatus |=
2212 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002213 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002214 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002215 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002216 itemsToRemove.add(id);
2217 continue;
2218 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002219 }
Sunny Goyalff572272014-07-23 13:58:07 -07002220
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002221 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002222 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002223 appWidgetInfo.cellX = c.getInt(cellXIndex);
2224 appWidgetInfo.cellY = c.getInt(cellYIndex);
2225 appWidgetInfo.spanX = c.getInt(spanXIndex);
2226 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002227
Adam Cohen59400422014-03-05 18:07:04 -08002228 if (!customWidget) {
2229 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2230 appWidgetInfo.minSpanX = minSpan[0];
2231 appWidgetInfo.minSpanY = minSpan[1];
2232 }
2233
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002234 container = c.getInt(containerIndex);
2235 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2236 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2237 Log.e(TAG, "Widget found where container != " +
2238 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2239 continue;
2240 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002241
Adam Cohene25af792013-06-06 23:08:25 -07002242 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002243 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002244 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2245 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002246 break;
2247 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002248
Adam Cohen59400422014-03-05 18:07:04 -08002249 if (!customWidget) {
2250 String providerName =
2251 appWidgetInfo.providerName.flattenToString();
2252 if (!providerName.equals(savedProvider) ||
2253 (appWidgetInfo.restoreStatus != restoreStatus)) {
2254 ContentValues values = new ContentValues();
2255 values.put(
2256 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2257 providerName);
2258 values.put(LauncherSettings.Favorites.RESTORED,
2259 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002260 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002261 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002262 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2264 sBgAppWidgets.add(appWidgetInfo);
2265 }
Joe Onorato36115782010-06-17 13:28:48 -04002266 break;
2267 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002268 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002269 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002270 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002271 }
2272 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002273 if (c != null) {
2274 c.close();
2275 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 }
2277
Winson Chungba9c37f2013-08-30 14:11:37 -07002278 // Break early if we've stopped loading
2279 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002280 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002281 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002282 }
2283
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002284 if (itemsToRemove.size() > 0) {
2285 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002286 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002287 // Remove dead items
2288 for (long id : itemsToRemove) {
2289 if (DEBUG_LOADERS) {
2290 Log.d(TAG, "Removed id = " + id);
2291 }
2292 // Don't notify content observers
2293 try {
2294 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2295 null, null);
2296 } catch (RemoteException e) {
2297 Log.w(TAG, "Could not remove id = " + id);
2298 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002299 }
2300 }
2301
Chris Wrenf4d08112014-01-16 18:13:56 -05002302 if (restoredRows.size() > 0) {
2303 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002304 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002305 // Update restored items that no longer require special handling
2306 try {
2307 StringBuilder selectionBuilder = new StringBuilder();
2308 selectionBuilder.append(LauncherSettings.Favorites._ID);
2309 selectionBuilder.append(" IN (");
2310 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2311 selectionBuilder.append(")");
2312 ContentValues values = new ContentValues();
2313 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002314 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002315 values, selectionBuilder.toString(), null);
2316 } catch (RemoteException e) {
2317 Log.w(TAG, "Could not update restored rows");
2318 }
2319 }
2320
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002321 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2322 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002323 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002324 null, sWorker);
2325 }
2326
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002327 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2328 // Log to disk
2329 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2330 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002331
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002332 // Remove any empty screens
2333 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2334 for (ItemInfo item: sBgItemsIdMap.values()) {
2335 long screenId = item.screenId;
2336 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2337 unusedScreens.contains(screenId)) {
2338 unusedScreens.remove(screenId);
2339 }
2340 }
2341
2342 // If there are any empty screens remove them, and update.
2343 if (unusedScreens.size() != 0) {
2344 // Log to disk
2345 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2346 TextUtils.join(", ", unusedScreens), true);
2347
2348 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002349 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002350 }
2351
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002352 if (DEBUG_LOADERS) {
2353 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2354 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002356 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002358
Daniel Sandler566da102013-06-25 23:43:45 -04002359 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002360 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002361 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002362 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002363 line += " | ";
2364 }
Winson Chung892c74d2013-08-22 16:15:50 -07002365 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002366 ItemInfo[][] screen = occupied.get(screenId);
2367 if (x < screen.length && y < screen[x].length) {
2368 line += (screen[x][y] != null) ? "#" : ".";
2369 } else {
2370 line += "!";
2371 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002372 }
Joe Onorato36115782010-06-17 13:28:48 -04002373 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002374 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002375 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002376 }
Joe Onorato36115782010-06-17 13:28:48 -04002377 }
Adam Cohene25af792013-06-06 23:08:25 -07002378 }
2379
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002380 /**
2381 * Partially updates the item without any notification. Must be called on the worker thread.
2382 */
2383 private void updateItem(long itemId, ContentValues update) {
2384 mContext.getContentResolver().update(
2385 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2386 update,
2387 BaseColumns._ID + "= ?",
2388 new String[]{Long.toString(itemId)});
2389 }
2390
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002391 /** Filters the set of items who are directly or indirectly (via another container) on the
2392 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002393 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002394 ArrayList<ItemInfo> allWorkspaceItems,
2395 ArrayList<ItemInfo> currentScreenItems,
2396 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002397 // Purge any null ItemInfos
2398 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2399 while (iter.hasNext()) {
2400 ItemInfo i = iter.next();
2401 if (i == null) {
2402 iter.remove();
2403 }
2404 }
2405
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002406 // Order the set of items by their containers first, this allows use to walk through the
2407 // list sequentially, build up a list of containers that are in the specified screen,
2408 // as well as all items in those containers.
2409 Set<Long> itemsOnScreen = new HashSet<Long>();
2410 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2411 @Override
2412 public int compare(ItemInfo lhs, ItemInfo rhs) {
2413 return (int) (lhs.container - rhs.container);
2414 }
2415 });
2416 for (ItemInfo info : allWorkspaceItems) {
2417 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002418 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002419 currentScreenItems.add(info);
2420 itemsOnScreen.add(info.id);
2421 } else {
2422 otherScreenItems.add(info);
2423 }
2424 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2425 currentScreenItems.add(info);
2426 itemsOnScreen.add(info.id);
2427 } else {
2428 if (itemsOnScreen.contains(info.container)) {
2429 currentScreenItems.add(info);
2430 itemsOnScreen.add(info.id);
2431 } else {
2432 otherScreenItems.add(info);
2433 }
2434 }
2435 }
2436 }
2437
2438 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002439 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002440 ArrayList<LauncherAppWidgetInfo> appWidgets,
2441 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2442 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002443
2444 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002445 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002446 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002447 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002448 currentScreenWidgets.add(widget);
2449 } else {
2450 otherScreenWidgets.add(widget);
2451 }
2452 }
2453 }
2454
2455 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002456 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 HashMap<Long, ItemInfo> itemsIdMap,
2458 HashMap<Long, FolderInfo> folders,
2459 HashMap<Long, FolderInfo> currentScreenFolders,
2460 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461
2462 for (long id : folders.keySet()) {
2463 ItemInfo info = itemsIdMap.get(id);
2464 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002465 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002467 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 currentScreenFolders.put(id, folder);
2469 } else {
2470 otherScreenFolders.put(id, folder);
2471 }
2472 }
2473 }
2474
2475 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2476 * right) */
2477 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002478 final LauncherAppState app = LauncherAppState.getInstance();
2479 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002480 // XXX: review this
2481 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002482 @Override
2483 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002484 int cellCountX = (int) grid.numColumns;
2485 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002486 int screenOffset = cellCountX * cellCountY;
2487 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002488 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002489 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002490 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002491 rhs.cellY * cellCountX + rhs.cellX);
2492 return (int) (lr - rr);
2493 }
2494 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002495 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002496
Adam Cohendcd297f2013-06-18 13:13:40 -07002497 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2498 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002499 final Runnable r = new Runnable() {
2500 @Override
2501 public void run() {
2502 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2503 if (callbacks != null) {
2504 callbacks.bindScreens(orderedScreens);
2505 }
2506 }
2507 };
2508 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2509 }
2510
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2512 final ArrayList<ItemInfo> workspaceItems,
2513 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2514 final HashMap<Long, FolderInfo> folders,
2515 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002516
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002517 final boolean postOnMainThread = (deferredBindRunnables != null);
2518
2519 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002520 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002521 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002522 final int start = i;
2523 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002524 final Runnable r = new Runnable() {
2525 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002526 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002527 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002528 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002529 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2530 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002531 }
2532 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 };
2534 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002535 synchronized (deferredBindRunnables) {
2536 deferredBindRunnables.add(r);
2537 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002538 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002539 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002540 }
Joe Onorato36115782010-06-17 13:28:48 -04002541 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542
2543 // Bind the folders
2544 if (!folders.isEmpty()) {
2545 final Runnable r = new Runnable() {
2546 public void run() {
2547 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2548 if (callbacks != null) {
2549 callbacks.bindFolders(folders);
2550 }
2551 }
2552 };
2553 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002554 synchronized (deferredBindRunnables) {
2555 deferredBindRunnables.add(r);
2556 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002557 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002558 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002559 }
2560 }
2561
2562 // Bind the widgets, one at a time
2563 N = appWidgets.size();
2564 for (int i = 0; i < N; i++) {
2565 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2566 final Runnable r = new Runnable() {
2567 public void run() {
2568 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2569 if (callbacks != null) {
2570 callbacks.bindAppWidget(widget);
2571 }
2572 }
2573 };
2574 if (postOnMainThread) {
2575 deferredBindRunnables.add(r);
2576 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002577 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002578 }
2579 }
2580 }
2581
2582 /**
2583 * Binds all loaded data to actual views on the main thread.
2584 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002585 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002586 final long t = SystemClock.uptimeMillis();
2587 Runnable r;
2588
2589 // Don't use these two variables in any of the callback runnables.
2590 // Otherwise we hold a reference to them.
2591 final Callbacks oldCallbacks = mCallbacks.get();
2592 if (oldCallbacks == null) {
2593 // This launcher has exited and nobody bothered to tell us. Just bail.
2594 Log.w(TAG, "LoaderTask running with no launcher");
2595 return;
2596 }
2597
Winson Chung9b9fb962013-11-15 15:39:34 -08002598 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002599 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2600 ArrayList<LauncherAppWidgetInfo> appWidgets =
2601 new ArrayList<LauncherAppWidgetInfo>();
2602 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2603 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002604 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002605 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002606 workspaceItems.addAll(sBgWorkspaceItems);
2607 appWidgets.addAll(sBgAppWidgets);
2608 folders.putAll(sBgFolders);
2609 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002610 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 }
2612
Derek Prothro7aff3992013-12-10 14:00:37 -05002613 final boolean isLoadingSynchronously =
2614 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002615 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002616 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002617 if (currScreen >= orderedScreenIds.size()) {
2618 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002619 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002620 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002621 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002622 final long currentScreenId = currentScreen < 0
2623 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002624
2625 // Load all the items that are on the current page first (and in the process, unbind
2626 // all the existing workspace items before we call startBinding() below.
2627 unbindWorkspaceItemsOnMainThread();
2628
2629 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002630 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2631 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2632 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2633 new ArrayList<LauncherAppWidgetInfo>();
2634 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2635 new ArrayList<LauncherAppWidgetInfo>();
2636 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2637 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2638
Winson Chung9b9fb962013-11-15 15:39:34 -08002639 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002640 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002641 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002642 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002643 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002644 otherFolders);
2645 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2646 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2647
2648 // Tell the workspace that we're about to start binding items
2649 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002650 public void run() {
2651 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2652 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002654 }
2655 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002656 };
Winson Chung81b52252012-08-27 15:34:29 -07002657 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658
Adam Cohendcd297f2013-06-18 13:13:40 -07002659 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2660
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002661 // Load items on the current page
2662 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2663 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002664 if (isLoadingSynchronously) {
2665 r = new Runnable() {
2666 public void run() {
2667 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002668 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002669 callbacks.onPageBoundSynchronously(currentScreen);
2670 }
2671 }
2672 };
Winson Chung81b52252012-08-27 15:34:29 -07002673 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002674 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002675
Winson Chung4a2afa32012-07-19 14:53:05 -07002676 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2677 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002678 synchronized (mDeferredBindRunnables) {
2679 mDeferredBindRunnables.clear();
2680 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002682 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002683
2684 // Tell the workspace that we're done binding items
2685 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002686 public void run() {
2687 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2688 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002689 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002690 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002691
Winson Chung98e030b2012-05-07 16:01:11 -07002692 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002693 if (DEBUG_LOADERS) {
2694 Log.d(TAG, "bound workspace in "
2695 + (SystemClock.uptimeMillis()-t) + "ms");
2696 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002697
2698 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002699 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002700 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002701 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002702 synchronized (mDeferredBindRunnables) {
2703 mDeferredBindRunnables.add(r);
2704 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002705 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002706 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002707 }
Joe Onorato36115782010-06-17 13:28:48 -04002708 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002709
Joe Onorato36115782010-06-17 13:28:48 -04002710 private void loadAndBindAllApps() {
2711 if (DEBUG_LOADERS) {
2712 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2713 }
2714 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002715 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002716 synchronized (LoaderTask.this) {
2717 if (mStopped) {
2718 return;
2719 }
2720 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002721 }
Joe Onorato36115782010-06-17 13:28:48 -04002722 } else {
2723 onlyBindAllApps();
2724 }
2725 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002726
Joe Onorato36115782010-06-17 13:28:48 -04002727 private void onlyBindAllApps() {
2728 final Callbacks oldCallbacks = mCallbacks.get();
2729 if (oldCallbacks == null) {
2730 // This launcher has exited and nobody bothered to tell us. Just bail.
2731 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2732 return;
2733 }
2734
2735 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002736 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002737 final ArrayList<AppInfo> list
2738 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002739 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002740 public void run() {
2741 final long t = SystemClock.uptimeMillis();
2742 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2743 if (callbacks != null) {
2744 callbacks.bindAllApplications(list);
2745 }
2746 if (DEBUG_LOADERS) {
2747 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2748 + (SystemClock.uptimeMillis()-t) + "ms");
2749 }
2750 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002751 };
2752 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002753 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002754 r.run();
2755 } else {
2756 mHandler.post(r);
2757 }
Joe Onorato36115782010-06-17 13:28:48 -04002758 }
2759
Winson Chung64359a52013-07-08 17:17:08 -07002760 private void loadAllApps() {
2761 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002762
Joe Onorato36115782010-06-17 13:28:48 -04002763 final Callbacks oldCallbacks = mCallbacks.get();
2764 if (oldCallbacks == null) {
2765 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002766 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002767 return;
2768 }
2769
2770 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2771 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2772
Kenny Guyed131872014-04-30 03:02:21 +01002773 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2774
Winson Chung64359a52013-07-08 17:17:08 -07002775 // Clear the list of apps
2776 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002777 SharedPreferences prefs = mContext.getSharedPreferences(
2778 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002779 for (UserHandleCompat user : profiles) {
2780 // Query for the set of apps
2781 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2782 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2783 if (DEBUG_LOADERS) {
2784 Log.d(TAG, "getActivityList took "
2785 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2786 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2787 }
2788 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002789 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002790 if (apps == null || apps.isEmpty()) {
2791 return;
2792 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002793
2794 // Update icon cache
2795 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2796
2797 // If any package icon has changed (app was updated while launcher was dead),
2798 // update the corresponding shortcuts.
2799 if (!updatedPackages.isEmpty()) {
2800 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2801 synchronized (sBgLock) {
2802 for (ItemInfo info : sBgItemsIdMap.values()) {
2803 if (info instanceof ShortcutInfo && user.equals(info.user)
2804 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2805 ShortcutInfo si = (ShortcutInfo) info;
2806 ComponentName cn = si.getTargetComponent();
2807 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2808 si.updateIcon(mIconCache);
2809 updates.add(si);
2810 }
2811 }
2812 }
2813 }
2814
2815 if (!updates.isEmpty()) {
2816 final UserHandleCompat userFinal = user;
2817 mHandler.post(new Runnable() {
2818
2819 public void run() {
2820 Callbacks cb = getCallback();
2821 if (cb != null) {
2822 cb.bindShortcutsChanged(
2823 updates, new ArrayList<ShortcutInfo>(), userFinal);
2824 }
2825 }
2826 });
2827 }
Kenny Guyed131872014-04-30 03:02:21 +01002828 }
Joe Onorato36115782010-06-17 13:28:48 -04002829
Kenny Guyed131872014-04-30 03:02:21 +01002830 // Create the ApplicationInfos
2831 for (int i = 0; i < apps.size(); i++) {
2832 LauncherActivityInfoCompat app = apps.get(i);
2833 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002834 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002835 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002836
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002837 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002838 // Add shortcuts for packages which were installed while launcher was dead.
2839 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2840 + mUserManager.getSerialNumberForUser(user);
2841 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2842 HashSet<String> newPackageSet = new HashSet<String>();
2843
2844 for (LauncherActivityInfoCompat info : apps) {
2845 String packageName = info.getComponentName().getPackageName();
2846 if (!packagesAdded.contains(packageName)
2847 && !newPackageSet.contains(packageName)) {
2848 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2849 }
2850 newPackageSet.add(packageName);
2851 }
2852
2853 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2854 }
Winson Chung64359a52013-07-08 17:17:08 -07002855 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002856 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002857 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2858 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002859
2860 // Post callback on main thread
2861 mHandler.post(new Runnable() {
2862 public void run() {
2863 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002864 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002865 if (callbacks != null) {
2866 callbacks.bindAllApplications(added);
2867 if (DEBUG_LOADERS) {
2868 Log.d(TAG, "bound " + added.size() + " apps in "
2869 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2870 }
2871 } else {
2872 Log.i(TAG, "not binding apps: no Launcher activity");
2873 }
2874 }
2875 });
2876
Joe Onorato36115782010-06-17 13:28:48 -04002877 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002878 Log.d(TAG, "Icons processed in "
2879 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002880 }
2881 }
2882
2883 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002884 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002885 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2886 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2887 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2888 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2889 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2890 }
Joe Onorato36115782010-06-17 13:28:48 -04002891 }
2892 }
2893
2894 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002895 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002896 }
2897
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002898 private class AppsAvailabilityCheck extends BroadcastReceiver {
2899
2900 @Override
2901 public void onReceive(Context context, Intent intent) {
2902 synchronized (sBgLock) {
2903 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2904 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002905 final PackageManager manager = context.getPackageManager();
2906 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2907 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002908 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2909 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002910 packagesRemoved.clear();
2911 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002912 for (String pkg : entry.getValue()) {
2913 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002914 boolean packageOnSdcard = launcherApps.isAppEnabled(
2915 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2916 if (packageOnSdcard) {
2917 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2918 packagesUnavailable.add(pkg);
2919 } else {
2920 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2921 packagesRemoved.add(pkg);
2922 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002923 }
2924 }
2925 if (!packagesRemoved.isEmpty()) {
2926 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2927 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2928 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002929 if (!packagesUnavailable.isEmpty()) {
2930 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2931 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2932 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002933 }
Sunny Goyal34942622014-08-29 17:20:55 -07002934 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002935 }
2936 }
2937 }
2938
Joe Onorato36115782010-06-17 13:28:48 -04002939 private class PackageUpdatedTask implements Runnable {
2940 int mOp;
2941 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002942 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002943
2944 public static final int OP_NONE = 0;
2945 public static final int OP_ADD = 1;
2946 public static final int OP_UPDATE = 2;
2947 public static final int OP_REMOVE = 3; // uninstlled
2948 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2949
2950
Kenny Guyed131872014-04-30 03:02:21 +01002951 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002952 mOp = op;
2953 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002954 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002955 }
2956
2957 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002958 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002959
2960 final String[] packages = mPackages;
2961 final int N = packages.length;
2962 switch (mOp) {
2963 case OP_ADD:
2964 for (int i=0; i<N; i++) {
2965 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002966 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002967 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002968 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002969
2970 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002971 if (ADD_MANAGED_PROFILE_SHORTCUTS
2972 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002973 SharedPreferences prefs = context.getSharedPreferences(
2974 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2975 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2976 + mUserManager.getSerialNumberForUser(mUser);
2977 Set<String> shortcutSet = new HashSet<String>(
2978 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2979
2980 for (int i=0; i<N; i++) {
2981 if (!shortcutSet.contains(packages[i])) {
2982 shortcutSet.add(packages[i]);
2983 List<LauncherActivityInfoCompat> activities =
2984 mLauncherApps.getActivityList(packages[i], mUser);
2985 if (activities != null && !activities.isEmpty()) {
2986 InstallShortcutReceiver.queueInstallShortcut(
2987 activities.get(0), context);
2988 }
2989 }
2990 }
2991
2992 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
2993 }
Joe Onorato36115782010-06-17 13:28:48 -04002994 break;
2995 case OP_UPDATE:
2996 for (int i=0; i<N; i++) {
2997 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002998 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002999 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003000 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003001 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003002 }
3003 break;
3004 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003005 // Remove the packageName for the set of auto-installed shortcuts. This
3006 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003007 if (ADD_MANAGED_PROFILE_SHORTCUTS
3008 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003009 SharedPreferences prefs = context.getSharedPreferences(
3010 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3011 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3012 + mUserManager.getSerialNumberForUser(mUser);
3013 HashSet<String> shortcutSet = new HashSet<String>(
3014 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3015 shortcutSet.removeAll(Arrays.asList(mPackages));
3016 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3017 }
Joe Onorato36115782010-06-17 13:28:48 -04003018 for (int i=0; i<N; i++) {
3019 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003020 mIconCache.removeIconsForPkg(packages[i], mUser);
3021 }
3022 // Fall through
3023 case OP_UNAVAILABLE:
3024 for (int i=0; i<N; i++) {
3025 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3026 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003027 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003028 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003029 }
3030 break;
3031 }
3032
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003033 ArrayList<AppInfo> added = null;
3034 ArrayList<AppInfo> modified = null;
3035 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003036
Adam Cohen487f7dd2012-06-28 18:12:10 -07003037 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003038 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003039 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003040 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003041 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003042 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003043 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003044 }
Winson Chung5d55f332012-07-16 20:45:03 -07003045 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003046 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003047 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003048 }
3049
Sunny Goyale0f58d72014-11-10 18:05:31 -08003050 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003051 if (callbacks == null) {
3052 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3053 return;
3054 }
3055
Sunny Goyal4390ace2014-10-13 11:33:11 -07003056 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3057 new HashMap<ComponentName, AppInfo>();
3058
Joe Onorato36115782010-06-17 13:28:48 -04003059 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003060 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003061 for (AppInfo ai : added) {
3062 addedOrUpdatedApps.put(ai.componentName, ai);
3063 }
Joe Onorato36115782010-06-17 13:28:48 -04003064 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003065
Joe Onorato36115782010-06-17 13:28:48 -04003066 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003067 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003068 for (AppInfo ai : modified) {
3069 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003070 }
3071
Joe Onorato36115782010-06-17 13:28:48 -04003072 mHandler.post(new Runnable() {
3073 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003074 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003075 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003076 callbacks.bindAppsUpdated(modifiedFinal);
3077 }
3078 }
3079 });
3080 }
Winson Chung83892cc2013-05-01 16:53:33 -07003081
Sunny Goyal4390ace2014-10-13 11:33:11 -07003082 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003083 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003084 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3085 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3086 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3087
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003088 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003089 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003090 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003091 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3092 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003093 boolean infoUpdated = false;
3094 boolean shortcutUpdated = false;
3095
3096 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003097 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003098 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003099 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3100 si.iconResource.resourceName, mIconCache, context);
3101 if (icon != null) {
3102 si.setIcon(icon);
3103 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003104 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003105 }
3106 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003107
3108 ComponentName cn = si.getTargetComponent();
3109 if (cn != null && packageSet.contains(cn.getPackageName())) {
3110 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3111
3112 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003113 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3114 // Auto install icon
3115 PackageManager pm = context.getPackageManager();
3116 ResolveInfo matched = pm.resolveActivity(
3117 new Intent(Intent.ACTION_MAIN)
3118 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3119 PackageManager.MATCH_DEFAULT_ONLY);
3120 if (matched == null) {
3121 // Try to find the best match activity.
3122 Intent intent = pm.getLaunchIntentForPackage(
3123 cn.getPackageName());
3124 if (intent != null) {
3125 cn = intent.getComponent();
3126 appInfo = addedOrUpdatedApps.get(cn);
3127 }
3128
3129 if ((intent == null) || (appInfo == null)) {
3130 removedShortcuts.add(si);
3131 continue;
3132 }
3133 si.promisedIntent = intent;
3134 }
3135 }
3136
3137 // Restore the shortcut.
3138 si.intent = si.promisedIntent;
3139 si.promisedIntent = null;
3140 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3141 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3142 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3143
3144 infoUpdated = true;
3145 si.updateIcon(mIconCache);
3146 }
3147
3148 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3149 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3150 si.updateIcon(mIconCache);
3151 si.title = appInfo.title.toString();
3152 si.contentDescription = appInfo.contentDescription;
3153 infoUpdated = true;
3154 }
3155
3156 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3157 // Since package was just updated, the target must be available now.
3158 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3159 shortcutUpdated = true;
3160 }
3161 }
3162
3163 if (infoUpdated || shortcutUpdated) {
3164 updatedShortcuts.add(si);
3165 }
3166 if (infoUpdated) {
3167 updateItemInDatabase(context, si);
3168 }
3169 } else if (info instanceof LauncherAppWidgetInfo) {
3170 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3171 if (mUser.equals(widgetInfo.user)
3172 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3173 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3174 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3175 widgets.add(widgetInfo);
3176 updateItemInDatabase(context, widgetInfo);
3177 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003178 }
3179 }
3180 }
3181
Sunny Goyal4390ace2014-10-13 11:33:11 -07003182 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3183 mHandler.post(new Runnable() {
3184
3185 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003186 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003187 if (callbacks == cb && cb != null) {
3188 callbacks.bindShortcutsChanged(
3189 updatedShortcuts, removedShortcuts, mUser);
3190 }
3191 }
3192 });
3193 if (!removedShortcuts.isEmpty()) {
3194 deleteItemsFromDatabase(context, removedShortcuts);
3195 }
3196 }
3197 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003198 mHandler.post(new Runnable() {
3199 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003200 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003201 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003202 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003203 }
3204 }
3205 });
3206 }
3207 }
3208
Winson Chungdf95eb12013-10-16 14:57:07 -07003209 final ArrayList<String> removedPackageNames =
3210 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003211 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003212 // Mark all packages in the broadcast to be removed
3213 removedPackageNames.addAll(Arrays.asList(packages));
3214 } else if (mOp == OP_UPDATE) {
3215 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003216 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003217 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003218 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003219 }
3220 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003221 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003222
Winson Chungdf95eb12013-10-16 14:57:07 -07003223 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003224 final int removeReason;
3225 if (mOp == OP_UNAVAILABLE) {
3226 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3227 } else {
3228 // Remove all the components associated with this package
3229 for (String pn : removedPackageNames) {
3230 deletePackageFromDatabase(context, pn, mUser);
3231 }
3232 // Remove all the specific components
3233 for (AppInfo a : removedApps) {
3234 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3235 deleteItemsFromDatabase(context, infos);
3236 }
3237 removeReason = 0;
3238 }
3239
Winson Chungdf95eb12013-10-16 14:57:07 -07003240 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003241 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003242 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003243 mHandler.post(new Runnable() {
3244 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003245 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003246 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003247 callbacks.bindComponentsRemoved(
3248 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003249 }
3250 }
3251 });
Joe Onoratobe386092009-11-17 17:32:16 -08003252 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003253
Michael Jurkac402cd92013-05-20 15:49:32 +02003254 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003255 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003256 mHandler.post(new Runnable() {
3257 @Override
3258 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003259 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003260 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003261 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003262 }
3263 }
3264 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003265
3266 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003267 mHandler.post(new Runnable() {
3268 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003269 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003270 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003271 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003272 }
3273 }
3274 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003275 }
3276 }
3277
Adam Cohen59400422014-03-05 18:07:04 -08003278 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3279 synchronized (sBgLock) {
3280 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3281 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3282 }
3283 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3284 List<AppWidgetProviderInfo> widgets =
3285 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3286 LauncherAppWidgetProviderInfo info;
3287 for (AppWidgetProviderInfo pInfo : widgets) {
3288 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3289 sBgWidgetProviders.put(info.provider, info);
3290 }
3291
3292 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3293 for (CustomAppWidget widget : customWidgets) {
3294 info = new LauncherAppWidgetProviderInfo(context, widget);
3295 sBgWidgetProviders.put(info.provider, info);
3296 }
3297 sWidgetProvidersDirty = false;
3298 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3299 }
3300 }
3301
3302 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3303 synchronized (sBgLock) {
3304 if (sBgWidgetProviders == null) {
3305 getWidgetProviders(ctx);
3306 }
3307 return sBgWidgetProviders.get(name);
3308 }
3309 }
3310
Michael Jurkac402cd92013-05-20 15:49:32 +02003311 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3312 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3313 PackageManager packageManager = context.getPackageManager();
3314 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003315 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003316 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3317 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003318 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003319 return widgetsAndShortcuts;
3320 }
3321
Kenny Guyed131872014-04-30 03:02:21 +01003322 private static boolean isPackageDisabled(Context context, String packageName,
3323 UserHandleCompat user) {
3324 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3325 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003326 }
Adam Cohen556f6132014-01-15 15:18:08 -08003327
Kenny Guyed131872014-04-30 03:02:21 +01003328 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3329 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003330 if (cn == null) {
3331 return false;
3332 }
Kenny Guyed131872014-04-30 03:02:21 +01003333 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3334 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003335 return false;
3336 }
Kenny Guyed131872014-04-30 03:02:21 +01003337 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003338 }
3339
Adam Cohena28b78e2014-05-20 17:03:04 -07003340 public static boolean isValidPackage(Context context, String packageName,
3341 UserHandleCompat user) {
3342 if (packageName == null) {
3343 return false;
3344 }
3345 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3346 return launcherApps.isPackageEnabledForProfile(packageName, user);
3347 }
3348
Joe Onorato9c1289c2009-08-17 11:03:03 -04003349 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003350 * Make an ShortcutInfo object for a restored application or shortcut item that points
3351 * to a package that is not yet installed on the system.
3352 */
Sunny Goyal34942622014-08-29 17:20:55 -07003353 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3354 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003355 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003356 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003357 mIconCache.getTitleAndIcon(info, intent, info.user);
Sunny Goyal34942622014-08-29 17:20:55 -07003358
3359 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3360 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3361 if (!TextUtils.isEmpty(title)) {
3362 info.title = title;
3363 }
3364 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3365 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3366 if (TextUtils.isEmpty(info.title)) {
3367 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3368 }
3369 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3370 } else {
3371 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3372 }
3373
Kenny Guyc2bd8102014-06-30 12:30:31 +01003374 info.contentDescription = mUserManager.getBadgedLabelForUser(
3375 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003376 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003377 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003378 return info;
3379 }
3380
3381 /**
3382 * Make an Intent object for a restored application or shortcut item that points
3383 * to the market page for the item.
3384 */
3385 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3386 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003387 return getMarketIntent(componentName.getPackageName());
3388 }
3389
3390 static Intent getMarketIntent(String packageName) {
3391 return new Intent(Intent.ACTION_VIEW)
3392 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003393 .scheme("market")
3394 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003395 .appendQueryParameter("id", packageName)
3396 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003397 }
3398
3399 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003400 * Make an ShortcutInfo object for a shortcut that is an application.
3401 *
3402 * If c is not null, then it will be used to fill in missing data like the title and icon.
3403 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003404 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003405 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003406 boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003407 if (user == null) {
3408 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003409 return null;
3410 }
3411
Kenny Guyed131872014-04-30 03:02:21 +01003412 ComponentName componentName = intent.getComponent();
3413 if (componentName == null) {
3414 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3415 return null;
3416 }
3417
3418 Intent newIntent = new Intent(intent.getAction(), null);
3419 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3420 newIntent.setComponent(componentName);
3421 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003422 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003423 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3424 return null;
3425 }
3426
3427 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003428 mIconCache.getTitleAndIcon(info, componentName, lai, user, false);
3429 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3430 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3431 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003432 }
3433
Joe Onorato56d82912010-03-07 14:32:10 -05003434 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003435 if (TextUtils.isEmpty(info.title) && c != null) {
3436 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003437 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003438
Joe Onorato56d82912010-03-07 14:32:10 -05003439 // fall back to the class name of the activity
3440 if (info.title == null) {
3441 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003442 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003443
Joe Onorato9c1289c2009-08-17 11:03:03 -04003444 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003445 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003446 info.contentDescription = mUserManager.getBadgedLabelForUser(
3447 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003448 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003449 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003450
Winson Chung64359a52013-07-08 17:17:08 -07003451 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3452 ItemInfoFilter f) {
3453 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3454 for (ItemInfo i : infos) {
3455 if (i instanceof ShortcutInfo) {
3456 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003457 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003458 if (cn != null && f.filterItem(null, info, cn)) {
3459 filtered.add(info);
3460 }
3461 } else if (i instanceof FolderInfo) {
3462 FolderInfo info = (FolderInfo) i;
3463 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003464 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003465 if (cn != null && f.filterItem(info, s, cn)) {
3466 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003467 }
3468 }
Winson Chung64359a52013-07-08 17:17:08 -07003469 } else if (i instanceof LauncherAppWidgetInfo) {
3470 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3471 ComponentName cn = info.providerName;
3472 if (cn != null && f.filterItem(null, info, cn)) {
3473 filtered.add(info);
3474 }
Winson Chung8a435102012-08-30 17:16:53 -07003475 }
3476 }
Winson Chung64359a52013-07-08 17:17:08 -07003477 return new ArrayList<ItemInfo>(filtered);
3478 }
3479
Kenny Guyed131872014-04-30 03:02:21 +01003480 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3481 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003482 ItemInfoFilter filter = new ItemInfoFilter() {
3483 @Override
3484 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003485 if (info.user == null) {
3486 return cn.equals(cname);
3487 } else {
3488 return cn.equals(cname) && info.user.equals(user);
3489 }
Winson Chung64359a52013-07-08 17:17:08 -07003490 }
3491 };
3492 return filterItemInfos(sBgItemsIdMap.values(), filter);
3493 }
3494
Sunny Goyal1a745e82014-10-02 15:58:31 -07003495 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003496 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003497 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003498 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003499 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3500 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003501
Joe Onorato56d82912010-03-07 14:32:10 -05003502 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003503 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003504 // Non-app shortcuts are only supported for current user.
3505 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003506 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003507
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003508 // TODO: If there's an explicit component and we can't install that, delete it.
3509
Joe Onorato56d82912010-03-07 14:32:10 -05003510 info.title = c.getString(titleIndex);
3511
Joe Onorato9c1289c2009-08-17 11:03:03 -04003512 int iconType = c.getInt(iconTypeIndex);
3513 switch (iconType) {
3514 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3515 String packageName = c.getString(iconPackageIndex);
3516 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003517 info.customIcon = false;
3518 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003519 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003520 // the db
3521 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003522 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003523 }
3524 // the fallback icon
3525 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003526 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003527 info.usingFallbackIcon = true;
3528 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003529 break;
3530 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003531 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003532 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003533 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003534 info.customIcon = false;
3535 info.usingFallbackIcon = true;
3536 } else {
3537 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003538 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003539 break;
3540 default:
Kenny Guyed131872014-04-30 03:02:21 +01003541 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003542 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003543 info.customIcon = false;
3544 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003545 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003546 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003547 return info;
3548 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003549
Sunny Goyal2350bc92014-10-14 16:42:54 -07003550 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003551 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3552 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3553 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3554
Adam Cohend9198822011-11-22 16:42:47 -08003555 if (intent == null) {
3556 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3557 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3558 return null;
3559 }
3560
Joe Onorato0589f0f2010-02-08 13:44:00 -08003561 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003562 boolean customIcon = false;
3563 ShortcutIconResource iconResource = null;
3564
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003565 if (bitmap instanceof Bitmap) {
3566 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003567 customIcon = true;
3568 } else {
3569 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003570 if (extra instanceof ShortcutIconResource) {
3571 iconResource = (ShortcutIconResource) extra;
3572 icon = Utilities.createIconBitmap(iconResource.packageName,
3573 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003574 }
3575 }
3576
Michael Jurkac9d95c52011-08-29 14:03:34 -07003577 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003578
Kenny Guyed131872014-04-30 03:02:21 +01003579 // Only support intents for current user for now. Intents sent from other
3580 // users wouldn't get here without intent forwarding anyway.
3581 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003582 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003583 icon = mIconCache.getDefaultIcon(info.user);
3584 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003585 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003586 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003587
Joe Onorato0589f0f2010-02-08 13:44:00 -08003588 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003589 info.contentDescription = mUserManager.getBadgedLabelForUser(
3590 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003591 info.intent = intent;
3592 info.customIcon = customIcon;
3593 info.iconResource = iconResource;
3594
3595 return info;
3596 }
3597
Joe Onorato9c1289c2009-08-17 11:03:03 -04003598 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003599 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003600 * or make a new one.
3601 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003602 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003603 // See if a placeholder was created for us already
3604 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003605 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003606 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003607 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003608 folders.put(id, folderInfo);
3609 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003610 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003611 }
3612
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003613 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003614 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003615 return new Comparator<AppInfo>() {
3616 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003617 if (a.user.equals(b.user)) {
3618 int result = collator.compare(a.title.toString().trim(),
3619 b.title.toString().trim());
3620 if (result == 0) {
3621 result = a.componentName.compareTo(b.componentName);
3622 }
3623 return result;
3624 } else {
3625 // TODO Need to figure out rules for sorting
3626 // profiles, this puts work second.
3627 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003628 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003629 }
Winson Chung11904872012-09-17 16:58:46 -07003630 };
3631 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003632 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3633 = new Comparator<AppInfo>() {
3634 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003635 if (a.firstInstallTime < b.firstInstallTime) return 1;
3636 if (a.firstInstallTime > b.firstInstallTime) return -1;
3637 return 0;
3638 }
3639 };
Winson Chung5308f242011-08-18 12:12:41 -07003640 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3641 if (info.activityInfo != null) {
3642 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3643 } else {
3644 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3645 }
3646 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003647
Winson Chung1ed747a2011-05-03 16:18:34 -07003648 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003649 private final AppWidgetManagerCompat mManager;
3650 private final PackageManager mPackageManager;
3651 private final HashMap<Object, String> mLabelCache;
3652 private final Collator mCollator;
3653
3654 WidgetAndShortcutNameComparator(Context context) {
3655 mManager = AppWidgetManagerCompat.getInstance(context);
3656 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003657 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003658 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003659 }
3660 public final int compare(Object a, Object b) {
3661 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003662 if (mLabelCache.containsKey(a)) {
3663 labelA = mLabelCache.get(a);
3664 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003665 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3666 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003667 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003668 mLabelCache.put(a, labelA);
3669 }
3670 if (mLabelCache.containsKey(b)) {
3671 labelB = mLabelCache.get(b);
3672 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003673 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003674 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003675 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003676 mLabelCache.put(b, labelB);
3677 }
Winson Chung11904872012-09-17 16:58:46 -07003678 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003679 }
3680 };
Joe Onoratobe386092009-11-17 17:32:16 -08003681
Sunny Goyal651077b2014-06-30 14:15:31 -07003682 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3683 return (provider != null) && (provider.provider != null)
3684 && (provider.provider.getPackageName() != null);
3685 }
3686
Joe Onoratobe386092009-11-17 17:32:16 -08003687 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003688 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003689 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3690 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3691 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3692 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003693 if (mLoaderTask != null) {
3694 mLoaderTask.dumpState();
3695 } else {
3696 Log.d(TAG, "mLoaderTask=null");
3697 }
Joe Onoratobe386092009-11-17 17:32:16 -08003698 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003699
3700 public Callbacks getCallback() {
3701 return mCallbacks != null ? mCallbacks.get() : null;
3702 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003703}