blob: 489e3299d8c6592b584b6b96fa2fe1a74c225f63 [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
Nilesh Agrawal16f3ea82014-01-09 17:14:01 -08001628 if (LauncherAppState.isDisableAllApps()) {
Winson Chungc58497e2013-09-03 17:48:37 -07001629 // Ensure that all the applications that are in the system are
1630 // represented on the home screen.
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001631 verifyApplications();
Winson Chungc763c4e2013-07-19 13:49:06 -07001632 }
1633
Joe Onorato36115782010-06-17 13:28:48 -04001634 // Clear out this reference, otherwise we end up holding it until all of the
1635 // callback runnables are done.
1636 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001637
Joe Onorato36115782010-06-17 13:28:48 -04001638 synchronized (mLock) {
1639 // If we are still the last one to be scheduled, remove ourselves.
1640 if (mLoaderTask == this) {
1641 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001642 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001643 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001644 }
Joe Onorato36115782010-06-17 13:28:48 -04001645 }
1646
1647 public void stopLocked() {
1648 synchronized (LoaderTask.this) {
1649 mStopped = true;
1650 this.notify();
1651 }
1652 }
1653
1654 /**
1655 * Gets the callbacks object. If we've been stopped, or if the launcher object
1656 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1657 * object that was around when the deferred message was scheduled, and if there's
1658 * a new Callbacks object around then also return null. This will save us from
1659 * calling onto it with data that will be ignored.
1660 */
1661 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1662 synchronized (mLock) {
1663 if (mStopped) {
1664 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001665 }
Joe Onorato36115782010-06-17 13:28:48 -04001666
1667 if (mCallbacks == null) {
1668 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001669 }
Joe Onorato36115782010-06-17 13:28:48 -04001670
1671 final Callbacks callbacks = mCallbacks.get();
1672 if (callbacks != oldCallbacks) {
1673 return null;
1674 }
1675 if (callbacks == null) {
1676 Log.w(TAG, "no mCallbacks");
1677 return null;
1678 }
1679
1680 return callbacks;
1681 }
1682 }
1683
Winson Chungc763c4e2013-07-19 13:49:06 -07001684 private void verifyApplications() {
1685 final Context context = mApp.getContext();
1686
1687 // Cross reference all the applications in our apps list with items in the workspace
1688 ArrayList<ItemInfo> tmpInfos;
Michael Jurka695ff6b2013-08-05 12:06:48 +02001689 ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
Winson Chungc763c4e2013-07-19 13:49:06 -07001690 synchronized (sBgLock) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001691 for (AppInfo app : mBgAllAppsList.data) {
Kenny Guyed131872014-04-30 03:02:21 +01001692 tmpInfos = getItemInfoForComponentName(app.componentName, app.user);
Winson Chungc763c4e2013-07-19 13:49:06 -07001693 if (tmpInfos.isEmpty()) {
1694 // We are missing an application icon, so add this to the workspace
1695 added.add(app);
1696 // This is a rare event, so lets log it
1697 Log.e(TAG, "Missing Application on load: " + app);
1698 }
1699 }
1700 }
1701 if (!added.isEmpty()) {
Adam Cohen76a47a12014-02-05 11:47:43 -08001702 addAndBindAddedWorkspaceApps(context, added);
Winson Chungc763c4e2013-07-19 13:49:06 -07001703 }
1704 }
1705
Joe Onorato36115782010-06-17 13:28:48 -04001706 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001707 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001708 LauncherAppState app = LauncherAppState.getInstance();
1709 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001710 final int countX = (int) grid.numColumns;
1711 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001712
Adam Cohendcd297f2013-06-18 13:13:40 -07001713 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001714 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001715 // Return early if we detect that an item is under the hotseat button
1716 if (mCallbacks == null ||
1717 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001718 Log.e(TAG, "Error loading shortcut into hotseat " + item
1719 + " into position (" + item.screenId + ":" + item.cellX + ","
1720 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001721 return false;
1722 }
1723
Dan Sandler295ae182013-12-10 16:05:47 -05001724 final ItemInfo[][] hotseatItems =
1725 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1726
Adam Cohenae4409d2013-11-26 10:34:59 -08001727 if (item.screenId >= grid.numHotseatIcons) {
1728 Log.e(TAG, "Error loading shortcut " + item
1729 + " into hotseat position " + item.screenId
1730 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1731 + ")");
1732 return false;
1733 }
1734
Dan Sandler295ae182013-12-10 16:05:47 -05001735 if (hotseatItems != null) {
1736 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001737 Log.e(TAG, "Error loading shortcut into hotseat " + item
1738 + " into position (" + item.screenId + ":" + item.cellX + ","
1739 + item.cellY + ") occupied by "
1740 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1741 [(int) item.screenId][0]);
1742 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001743 } else {
1744 hotseatItems[(int) item.screenId][0] = item;
1745 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001746 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001747 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001748 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001749 items[(int) item.screenId][0] = item;
1750 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001751 return true;
1752 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001753 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1754 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001755 return true;
1756 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001757
Adam Cohendcd297f2013-06-18 13:13:40 -07001758 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001759 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001760 occupied.put(item.screenId, items);
1761 }
1762
Dan Sandler295ae182013-12-10 16:05:47 -05001763 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001764 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1765 item.cellX < 0 || item.cellY < 0 ||
1766 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1767 Log.e(TAG, "Error loading shortcut " + item
1768 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1769 + item.cellX + "," + item.cellY
1770 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1771 return false;
1772 }
1773
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001774 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001775 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1776 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001777 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001778 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001779 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001780 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001781 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001782 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001783 return false;
1784 }
1785 }
1786 }
1787 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1788 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001789 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001790 }
1791 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001792
Joe Onorato36115782010-06-17 13:28:48 -04001793 return true;
1794 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001795
Winson Chungba9c37f2013-08-30 14:11:37 -07001796 /** Clears all the sBg data structures */
1797 private void clearSBgDataStructures() {
1798 synchronized (sBgLock) {
1799 sBgWorkspaceItems.clear();
1800 sBgAppWidgets.clear();
1801 sBgFolders.clear();
1802 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001803 sBgWorkspaceScreens.clear();
1804 }
1805 }
1806
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001807 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001808 // Log to disk
1809 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1810
Joe Onorato36115782010-06-17 13:28:48 -04001811 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001812
Joe Onorato36115782010-06-17 13:28:48 -04001813 final Context context = mContext;
1814 final ContentResolver contentResolver = context.getContentResolver();
1815 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001816 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001817 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1818 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001819 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001820
Winson Chung892c74d2013-08-22 16:15:50 -07001821 LauncherAppState app = LauncherAppState.getInstance();
1822 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1823 int countX = (int) grid.numColumns;
1824 int countY = (int) grid.numRows;
1825
Dan Sandlerd5024042014-01-09 15:01:33 -05001826 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1827 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1828 LauncherAppState.getLauncherProvider().deleteDatabase();
1829 }
1830
1831 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1832 // append the user's Launcher2 shortcuts
1833 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1834 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1835 } else {
1836 // Make sure the default workspace is loaded
1837 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001838 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001839 }
Adam Cohene25af792013-06-06 23:08:25 -07001840
Winson Chung2abf94d2012-07-18 18:16:38 -07001841 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001842 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001843 final HashSet<String> installingPkgs = PackageInstallerCompat
1844 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001845
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001846 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001847 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001848 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001849 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001850 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001851
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001852 // +1 for the hotseat (it can be larger than the workspace)
1853 // Load workspace in reverse order to ensure that latest items are loaded first (and
1854 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001855 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001856
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001857 try {
1858 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1859 final int intentIndex = c.getColumnIndexOrThrow
1860 (LauncherSettings.Favorites.INTENT);
1861 final int titleIndex = c.getColumnIndexOrThrow
1862 (LauncherSettings.Favorites.TITLE);
1863 final int iconTypeIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.ICON_TYPE);
1865 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1866 final int iconPackageIndex = c.getColumnIndexOrThrow(
1867 LauncherSettings.Favorites.ICON_PACKAGE);
1868 final int iconResourceIndex = c.getColumnIndexOrThrow(
1869 LauncherSettings.Favorites.ICON_RESOURCE);
1870 final int containerIndex = c.getColumnIndexOrThrow(
1871 LauncherSettings.Favorites.CONTAINER);
1872 final int itemTypeIndex = c.getColumnIndexOrThrow(
1873 LauncherSettings.Favorites.ITEM_TYPE);
1874 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1875 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001876 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1877 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001878 final int screenIndex = c.getColumnIndexOrThrow(
1879 LauncherSettings.Favorites.SCREEN);
1880 final int cellXIndex = c.getColumnIndexOrThrow
1881 (LauncherSettings.Favorites.CELLX);
1882 final int cellYIndex = c.getColumnIndexOrThrow
1883 (LauncherSettings.Favorites.CELLY);
1884 final int spanXIndex = c.getColumnIndexOrThrow
1885 (LauncherSettings.Favorites.SPANX);
1886 final int spanYIndex = c.getColumnIndexOrThrow(
1887 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001888 final int rankIndex = c.getColumnIndexOrThrow(
1889 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001890 final int restoredIndex = c.getColumnIndexOrThrow(
1891 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001892 final int profileIdIndex = c.getColumnIndexOrThrow(
1893 LauncherSettings.Favorites.PROFILE_ID);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001894 //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
1895 //final int displayModeIndex = c.getColumnIndexOrThrow(
1896 // LauncherSettings.Favorites.DISPLAY_MODE);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001897
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001898 ShortcutInfo info;
1899 String intentDescription;
1900 LauncherAppWidgetInfo appWidgetInfo;
1901 int container;
1902 long id;
1903 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001904 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001905
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001906 while (!mStopped && c.moveToNext()) {
1907 try {
1908 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001909 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001910 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001911
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001912 switch (itemType) {
1913 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1914 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001915 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001916 intentDescription = c.getString(intentIndex);
Kenny Guy1317e2d2014-05-08 18:52:50 +01001917 long serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001918 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001919 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001920 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001921 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001922 if (user == null) {
1923 // User has been deleted remove the item.
1924 itemsToRemove.add(id);
1925 continue;
1926 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001927 try {
1928 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001929 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001930 if (cn != null && cn.getPackageName() != null) {
1931 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1932 cn.getPackageName(), user);
1933 boolean validComponent = validPkg &&
1934 launcherApps.isActivityEnabledForProfile(cn, user);
1935
1936 if (validComponent) {
1937 if (restored) {
1938 // no special handling necessary for this item
1939 restoredRows.add(id);
1940 restored = false;
1941 }
1942 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001943 intent = null;
1944 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1945 // We allow auto install apps to have their intent
1946 // updated after an install.
1947 intent = manager.getLaunchIntentForPackage(
1948 cn.getPackageName());
1949 if (intent != null) {
1950 ContentValues values = new ContentValues();
1951 values.put(LauncherSettings.Favorites.INTENT,
1952 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001953 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001954 }
1955 }
1956
1957 if (intent == null) {
1958 // The app is installed but the component is no
1959 // longer available.
1960 Launcher.addDumpLog(TAG,
1961 "Invalid component removed: " + cn, true);
1962 itemsToRemove.add(id);
1963 continue;
1964 } else {
1965 // no special handling necessary for this item
1966 restoredRows.add(id);
1967 restored = false;
1968 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001969 } else if (restored) {
1970 // Package is not yet available but might be
1971 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001972 Launcher.addDumpLog(TAG,
1973 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001974
1975 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1976 // Restore has started once.
1977 } else if (installingPkgs.contains(cn.getPackageName())) {
1978 // App restore has started. Update the flag
1979 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1980 ContentValues values = new ContentValues();
1981 values.put(LauncherSettings.Favorites.RESTORED,
1982 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001983 updateItem(id, values);
1984 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1985 // This is a common app. Try to replace this.
1986 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1987 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1988 if (parser.findDefaultApp()) {
1989 // Default app found. Replace it.
1990 intent = parser.parsedIntent;
1991 cn = intent.getComponent();
1992 ContentValues values = parser.parsedValues;
1993 values.put(LauncherSettings.Favorites.RESTORED, 0);
1994 updateItem(id, values);
1995 restored = false;
1996 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001997
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001998 } else if (REMOVE_UNRESTORED_ICONS) {
1999 Launcher.addDumpLog(TAG,
2000 "Unrestored package removed: " + cn, true);
2001 itemsToRemove.add(id);
2002 continue;
2003 }
Sunny Goyal94485362014-09-18 16:13:58 -07002004 } else if (REMOVE_UNRESTORED_ICONS) {
2005 Launcher.addDumpLog(TAG,
2006 "Unrestored package removed: " + cn, true);
2007 itemsToRemove.add(id);
2008 continue;
2009 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002010 } else if (launcherApps.isAppEnabled(
2011 manager, cn.getPackageName(),
2012 PackageManager.GET_UNINSTALLED_PACKAGES)) {
2013 // Package is present but not available.
2014 allowMissingTarget = true;
2015 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
2016 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002017 // SdCard is not ready yet. Package might get available,
2018 // once it is ready.
2019 Launcher.addDumpLog(TAG, "Invalid package: " + cn
2020 + " (check again later)", true);
2021 HashSet<String> pkgs = sPendingPackages.get(user);
2022 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002023 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002024 sPendingPackages.put(user, pkgs);
2025 }
2026 pkgs.add(cn.getPackageName());
2027 allowMissingTarget = true;
2028 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002029
2030 } else {
2031 // Do not wait for external media load anymore.
2032 // Log the invalid package, and remove it
2033 Launcher.addDumpLog(TAG,
2034 "Invalid package removed: " + cn, true);
2035 itemsToRemove.add(id);
2036 continue;
Winson Chungee055712013-07-30 14:46:24 -07002037 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002038 } else if (cn == null) {
2039 // For shortcuts with no component, keep them as they are
2040 restoredRows.add(id);
2041 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002042 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002043 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002044 Launcher.addDumpLog(TAG,
2045 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002046 continue;
2047 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002048
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002049 if (itemReplaced) {
2050 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002051 info = getAppShortcutInfo(manager, intent, user, context, null,
2052 iconIndex, titleIndex, false);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002053 } else {
2054 // Don't replace items for other profiles.
2055 itemsToRemove.add(id);
2056 continue;
2057 }
2058 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002059 if (user.equals(UserHandleCompat.myUserHandle())) {
2060 Launcher.addDumpLog(TAG,
2061 "constructing info for partially restored package",
2062 true);
Sunny Goyal34942622014-08-29 17:20:55 -07002063 info = getRestoredItemInfo(c, titleIndex, intent, promiseType);
Kenny Guyed131872014-04-30 03:02:21 +01002064 intent = getRestoredItemIntent(c, context, intent);
2065 } else {
2066 // Don't restore items for other profiles.
2067 itemsToRemove.add(id);
2068 continue;
2069 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002070 } else if (itemType ==
2071 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002072 info = getAppShortcutInfo(manager, intent, user, context, c,
2073 iconIndex, titleIndex, allowMissingTarget);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 } else {
2075 info = getShortcutInfo(c, context, iconTypeIndex,
2076 iconPackageIndex, iconResourceIndex, iconIndex,
2077 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002078
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 // App shortcuts that used to be automatically added to Launcher
2080 // didn't always have the correct intent flags set, so do that
2081 // here
2082 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002083 intent.getCategories() != null &&
2084 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002085 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002086 intent.addFlags(
2087 Intent.FLAG_ACTIVITY_NEW_TASK |
2088 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2089 }
Michael Jurka96879562012-03-22 05:54:33 -07002090 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002091
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002092 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002093 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002094 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002095 container = c.getInt(containerIndex);
2096 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002097 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002098 info.cellX = c.getInt(cellXIndex);
2099 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002100 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002101 info.spanX = 1;
2102 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002103 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002104 info.isDisabled = disabledState;
2105 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2106 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2107 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002108
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002109 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002110 if (!checkItemPlacement(occupied, info)) {
2111 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 break;
2113 }
2114
2115 switch (container) {
2116 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2117 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2118 sBgWorkspaceItems.add(info);
2119 break;
2120 default:
2121 // Item is in a user folder
2122 FolderInfo folderInfo =
2123 findOrMakeFolder(sBgFolders, container);
2124 folderInfo.add(info);
2125 break;
2126 }
2127 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002128 } else {
2129 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002130 }
2131 break;
2132
2133 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2134 id = c.getLong(idIndex);
2135 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2136
2137 folderInfo.title = c.getString(titleIndex);
2138 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002139 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002140 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002141 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 folderInfo.cellX = c.getInt(cellXIndex);
2143 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002144 folderInfo.spanX = 1;
2145 folderInfo.spanY = 1;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002146
Daniel Sandler8802e962010-05-26 16:28:16 -04002147 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002148 if (!checkItemPlacement(occupied, folderInfo)) {
2149 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002150 break;
2151 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002152
Joe Onorato9c1289c2009-08-17 11:03:03 -04002153 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2155 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2156 sBgWorkspaceItems.add(folderInfo);
2157 break;
Joe Onorato36115782010-06-17 13:28:48 -04002158 }
Joe Onorato17a89222011-02-08 17:26:11 -08002159
Chris Wrenf4d08112014-01-16 18:13:56 -05002160 if (restored) {
2161 // no special handling required for restored folders
2162 restoredRows.add(id);
2163 }
2164
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002165 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2166 sBgFolders.put(folderInfo.id, folderInfo);
2167 break;
2168
2169 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002170 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002171 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002172 boolean customWidget = itemType ==
2173 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2174
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002175 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002176 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002177 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002178 final ComponentName component =
2179 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002180
Sunny Goyal651077b2014-06-30 14:15:31 -07002181 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002182 final boolean isIdValid = (restoreStatus &
2183 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002184
Sunny Goyalff572272014-07-23 13:58:07 -07002185 final boolean wasProviderReady = (restoreStatus &
2186 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002187
Adam Cohen59400422014-03-05 18:07:04 -08002188 final LauncherAppWidgetProviderInfo provider =
2189 LauncherModel.getProviderInfo(context,
2190 ComponentName.unflattenFromString(savedProvider));
Sunny Goyalff572272014-07-23 13:58:07 -07002191
2192 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002193 if (!isSafeMode && !customWidget &&
2194 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002195 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002196 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002197
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002198 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002199 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002200 itemsToRemove.add(id);
2201 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002202 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002203 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2204 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002205
2206 if (!customWidget) {
2207 int[] minSpan =
2208 Launcher.getMinSpanForWidget(context, provider);
2209 appWidgetInfo.minSpanX = minSpan[0];
2210 appWidgetInfo.minSpanY = minSpan[1];
2211 }
Sunny Goyalff572272014-07-23 13:58:07 -07002212
2213 int status = restoreStatus;
2214 if (!wasProviderReady) {
2215 // If provider was not previously ready, update the
2216 // status and UI flag.
2217
2218 // Id would be valid only if the widget restore broadcast was received.
2219 if (isIdValid) {
2220 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2221 } else {
2222 status &= ~LauncherAppWidgetInfo
2223 .FLAG_PROVIDER_NOT_READY;
2224 }
2225 }
2226 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002227 } else {
2228 Log.v(TAG, "Widget restore pending id=" + id
2229 + " appWidgetId=" + appWidgetId
2230 + " status =" + restoreStatus);
2231 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002232 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002233 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002234
2235 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2236 // Restore has started once.
2237 } else if (installingPkgs.contains(component.getPackageName())) {
2238 // App restore has started. Update the flag
2239 appWidgetInfo.restoreStatus |=
2240 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002241 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002242 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002243 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002244 itemsToRemove.add(id);
2245 continue;
2246 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002247 }
Sunny Goyalff572272014-07-23 13:58:07 -07002248
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002249 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002250 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251 appWidgetInfo.cellX = c.getInt(cellXIndex);
2252 appWidgetInfo.cellY = c.getInt(cellYIndex);
2253 appWidgetInfo.spanX = c.getInt(spanXIndex);
2254 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002255
Adam Cohen59400422014-03-05 18:07:04 -08002256 if (!customWidget) {
2257 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2258 appWidgetInfo.minSpanX = minSpan[0];
2259 appWidgetInfo.minSpanY = minSpan[1];
2260 }
2261
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002262 container = c.getInt(containerIndex);
2263 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2264 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2265 Log.e(TAG, "Widget found where container != " +
2266 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2267 continue;
2268 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002269
Adam Cohene25af792013-06-06 23:08:25 -07002270 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002271 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002272 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2273 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002274 break;
2275 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002276
Adam Cohen59400422014-03-05 18:07:04 -08002277 if (!customWidget) {
2278 String providerName =
2279 appWidgetInfo.providerName.flattenToString();
2280 if (!providerName.equals(savedProvider) ||
2281 (appWidgetInfo.restoreStatus != restoreStatus)) {
2282 ContentValues values = new ContentValues();
2283 values.put(
2284 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2285 providerName);
2286 values.put(LauncherSettings.Favorites.RESTORED,
2287 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002288 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002289 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002290 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002291 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2292 sBgAppWidgets.add(appWidgetInfo);
2293 }
Joe Onorato36115782010-06-17 13:28:48 -04002294 break;
2295 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002296 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002297 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002298 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002299 }
2300 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002301 if (c != null) {
2302 c.close();
2303 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002304 }
2305
Winson Chungba9c37f2013-08-30 14:11:37 -07002306 // Break early if we've stopped loading
2307 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002308 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002309 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002310 }
2311
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 if (itemsToRemove.size() > 0) {
2313 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002314 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002315 // Remove dead items
2316 for (long id : itemsToRemove) {
2317 if (DEBUG_LOADERS) {
2318 Log.d(TAG, "Removed id = " + id);
2319 }
2320 // Don't notify content observers
2321 try {
2322 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2323 null, null);
2324 } catch (RemoteException e) {
2325 Log.w(TAG, "Could not remove id = " + id);
2326 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002327 }
2328 }
2329
Chris Wrenf4d08112014-01-16 18:13:56 -05002330 if (restoredRows.size() > 0) {
2331 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002332 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002333 // Update restored items that no longer require special handling
2334 try {
2335 StringBuilder selectionBuilder = new StringBuilder();
2336 selectionBuilder.append(LauncherSettings.Favorites._ID);
2337 selectionBuilder.append(" IN (");
2338 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2339 selectionBuilder.append(")");
2340 ContentValues values = new ContentValues();
2341 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002342 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002343 values, selectionBuilder.toString(), null);
2344 } catch (RemoteException e) {
2345 Log.w(TAG, "Could not update restored rows");
2346 }
2347 }
2348
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002349 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2350 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002351 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002352 null, sWorker);
2353 }
2354
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002355 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2356 // Log to disk
2357 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2358 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002359
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002360 // Remove any empty screens
2361 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2362 for (ItemInfo item: sBgItemsIdMap.values()) {
2363 long screenId = item.screenId;
2364 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2365 unusedScreens.contains(screenId)) {
2366 unusedScreens.remove(screenId);
2367 }
2368 }
2369
2370 // If there are any empty screens remove them, and update.
2371 if (unusedScreens.size() != 0) {
2372 // Log to disk
2373 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2374 TextUtils.join(", ", unusedScreens), true);
2375
2376 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002378 }
2379
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002380 if (DEBUG_LOADERS) {
2381 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2382 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002383 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002384 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002385 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002386
Daniel Sandler566da102013-06-25 23:43:45 -04002387 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002388 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002389 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002390 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002391 line += " | ";
2392 }
Winson Chung892c74d2013-08-22 16:15:50 -07002393 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002394 ItemInfo[][] screen = occupied.get(screenId);
2395 if (x < screen.length && y < screen[x].length) {
2396 line += (screen[x][y] != null) ? "#" : ".";
2397 } else {
2398 line += "!";
2399 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002400 }
Joe Onorato36115782010-06-17 13:28:48 -04002401 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002402 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002403 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002404 }
Joe Onorato36115782010-06-17 13:28:48 -04002405 }
Adam Cohene25af792013-06-06 23:08:25 -07002406 }
2407
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002408 /**
2409 * Partially updates the item without any notification. Must be called on the worker thread.
2410 */
2411 private void updateItem(long itemId, ContentValues update) {
2412 mContext.getContentResolver().update(
2413 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2414 update,
2415 BaseColumns._ID + "= ?",
2416 new String[]{Long.toString(itemId)});
2417 }
2418
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002419 /** Filters the set of items who are directly or indirectly (via another container) on the
2420 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002421 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002422 ArrayList<ItemInfo> allWorkspaceItems,
2423 ArrayList<ItemInfo> currentScreenItems,
2424 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002425 // Purge any null ItemInfos
2426 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2427 while (iter.hasNext()) {
2428 ItemInfo i = iter.next();
2429 if (i == null) {
2430 iter.remove();
2431 }
2432 }
2433
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002434 // Order the set of items by their containers first, this allows use to walk through the
2435 // list sequentially, build up a list of containers that are in the specified screen,
2436 // as well as all items in those containers.
2437 Set<Long> itemsOnScreen = new HashSet<Long>();
2438 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2439 @Override
2440 public int compare(ItemInfo lhs, ItemInfo rhs) {
2441 return (int) (lhs.container - rhs.container);
2442 }
2443 });
2444 for (ItemInfo info : allWorkspaceItems) {
2445 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002446 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002447 currentScreenItems.add(info);
2448 itemsOnScreen.add(info.id);
2449 } else {
2450 otherScreenItems.add(info);
2451 }
2452 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2453 currentScreenItems.add(info);
2454 itemsOnScreen.add(info.id);
2455 } else {
2456 if (itemsOnScreen.contains(info.container)) {
2457 currentScreenItems.add(info);
2458 itemsOnScreen.add(info.id);
2459 } else {
2460 otherScreenItems.add(info);
2461 }
2462 }
2463 }
2464 }
2465
2466 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002467 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 ArrayList<LauncherAppWidgetInfo> appWidgets,
2469 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2470 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471
2472 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002473 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002475 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002476 currentScreenWidgets.add(widget);
2477 } else {
2478 otherScreenWidgets.add(widget);
2479 }
2480 }
2481 }
2482
2483 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002484 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002485 HashMap<Long, ItemInfo> itemsIdMap,
2486 HashMap<Long, FolderInfo> folders,
2487 HashMap<Long, FolderInfo> currentScreenFolders,
2488 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489
2490 for (long id : folders.keySet()) {
2491 ItemInfo info = itemsIdMap.get(id);
2492 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002493 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002494 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002495 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002496 currentScreenFolders.put(id, folder);
2497 } else {
2498 otherScreenFolders.put(id, folder);
2499 }
2500 }
2501 }
2502
2503 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2504 * right) */
2505 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002506 final LauncherAppState app = LauncherAppState.getInstance();
2507 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 // XXX: review this
2509 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002510 @Override
2511 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002512 int cellCountX = (int) grid.numColumns;
2513 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002514 int screenOffset = cellCountX * cellCountY;
2515 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002516 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002517 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002518 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002519 rhs.cellY * cellCountX + rhs.cellX);
2520 return (int) (lr - rr);
2521 }
2522 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002524
Adam Cohendcd297f2013-06-18 13:13:40 -07002525 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2526 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002527 final Runnable r = new Runnable() {
2528 @Override
2529 public void run() {
2530 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2531 if (callbacks != null) {
2532 callbacks.bindScreens(orderedScreens);
2533 }
2534 }
2535 };
2536 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2537 }
2538
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2540 final ArrayList<ItemInfo> workspaceItems,
2541 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2542 final HashMap<Long, FolderInfo> folders,
2543 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002544
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 final boolean postOnMainThread = (deferredBindRunnables != null);
2546
2547 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002548 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002550 final int start = i;
2551 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002552 final Runnable r = new Runnable() {
2553 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002554 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002555 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002556 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002557 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2558 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002559 }
2560 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002561 };
2562 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002563 synchronized (deferredBindRunnables) {
2564 deferredBindRunnables.add(r);
2565 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002566 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002567 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002568 }
Joe Onorato36115782010-06-17 13:28:48 -04002569 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570
2571 // Bind the folders
2572 if (!folders.isEmpty()) {
2573 final Runnable r = new Runnable() {
2574 public void run() {
2575 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2576 if (callbacks != null) {
2577 callbacks.bindFolders(folders);
2578 }
2579 }
2580 };
2581 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002582 synchronized (deferredBindRunnables) {
2583 deferredBindRunnables.add(r);
2584 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002585 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002586 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002587 }
2588 }
2589
2590 // Bind the widgets, one at a time
2591 N = appWidgets.size();
2592 for (int i = 0; i < N; i++) {
2593 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2594 final Runnable r = new Runnable() {
2595 public void run() {
2596 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2597 if (callbacks != null) {
2598 callbacks.bindAppWidget(widget);
2599 }
2600 }
2601 };
2602 if (postOnMainThread) {
2603 deferredBindRunnables.add(r);
2604 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002605 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002606 }
2607 }
2608 }
2609
2610 /**
2611 * Binds all loaded data to actual views on the main thread.
2612 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002613 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002614 final long t = SystemClock.uptimeMillis();
2615 Runnable r;
2616
2617 // Don't use these two variables in any of the callback runnables.
2618 // Otherwise we hold a reference to them.
2619 final Callbacks oldCallbacks = mCallbacks.get();
2620 if (oldCallbacks == null) {
2621 // This launcher has exited and nobody bothered to tell us. Just bail.
2622 Log.w(TAG, "LoaderTask running with no launcher");
2623 return;
2624 }
2625
Winson Chung9b9fb962013-11-15 15:39:34 -08002626 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2628 ArrayList<LauncherAppWidgetInfo> appWidgets =
2629 new ArrayList<LauncherAppWidgetInfo>();
2630 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2631 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002632 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002633 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002634 workspaceItems.addAll(sBgWorkspaceItems);
2635 appWidgets.addAll(sBgAppWidgets);
2636 folders.putAll(sBgFolders);
2637 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002638 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002639 }
2640
Derek Prothro7aff3992013-12-10 14:00:37 -05002641 final boolean isLoadingSynchronously =
2642 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002643 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002644 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002645 if (currScreen >= orderedScreenIds.size()) {
2646 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002647 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002648 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002649 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002650 final long currentScreenId = currentScreen < 0
2651 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002652
2653 // Load all the items that are on the current page first (and in the process, unbind
2654 // all the existing workspace items before we call startBinding() below.
2655 unbindWorkspaceItemsOnMainThread();
2656
2657 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2659 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2660 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2661 new ArrayList<LauncherAppWidgetInfo>();
2662 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2663 new ArrayList<LauncherAppWidgetInfo>();
2664 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2665 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2666
Winson Chung9b9fb962013-11-15 15:39:34 -08002667 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002668 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002669 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002670 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002671 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 otherFolders);
2673 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2674 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2675
2676 // Tell the workspace that we're about to start binding items
2677 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002678 public void run() {
2679 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2680 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002682 }
2683 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684 };
Winson Chung81b52252012-08-27 15:34:29 -07002685 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002686
Adam Cohendcd297f2013-06-18 13:13:40 -07002687 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2688
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002689 // Load items on the current page
2690 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2691 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002692 if (isLoadingSynchronously) {
2693 r = new Runnable() {
2694 public void run() {
2695 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002696 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002697 callbacks.onPageBoundSynchronously(currentScreen);
2698 }
2699 }
2700 };
Winson Chung81b52252012-08-27 15:34:29 -07002701 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002702 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002703
Winson Chung4a2afa32012-07-19 14:53:05 -07002704 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2705 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002706 synchronized (mDeferredBindRunnables) {
2707 mDeferredBindRunnables.clear();
2708 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002709 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002710 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002711
2712 // Tell the workspace that we're done binding items
2713 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002714 public void run() {
2715 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2716 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002717 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002718 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002719
Winson Chung98e030b2012-05-07 16:01:11 -07002720 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002721 if (DEBUG_LOADERS) {
2722 Log.d(TAG, "bound workspace in "
2723 + (SystemClock.uptimeMillis()-t) + "ms");
2724 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002725
2726 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002727 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002728 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002729 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002730 synchronized (mDeferredBindRunnables) {
2731 mDeferredBindRunnables.add(r);
2732 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002733 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002734 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002735 }
Joe Onorato36115782010-06-17 13:28:48 -04002736 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002737
Joe Onorato36115782010-06-17 13:28:48 -04002738 private void loadAndBindAllApps() {
2739 if (DEBUG_LOADERS) {
2740 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2741 }
2742 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002743 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002744 synchronized (LoaderTask.this) {
2745 if (mStopped) {
2746 return;
2747 }
2748 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002749 }
Joe Onorato36115782010-06-17 13:28:48 -04002750 } else {
2751 onlyBindAllApps();
2752 }
2753 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002754
Joe Onorato36115782010-06-17 13:28:48 -04002755 private void onlyBindAllApps() {
2756 final Callbacks oldCallbacks = mCallbacks.get();
2757 if (oldCallbacks == null) {
2758 // This launcher has exited and nobody bothered to tell us. Just bail.
2759 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2760 return;
2761 }
2762
2763 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002764 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002765 final ArrayList<AppInfo> list
2766 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002767 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002768 public void run() {
2769 final long t = SystemClock.uptimeMillis();
2770 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2771 if (callbacks != null) {
2772 callbacks.bindAllApplications(list);
2773 }
2774 if (DEBUG_LOADERS) {
2775 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2776 + (SystemClock.uptimeMillis()-t) + "ms");
2777 }
2778 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002779 };
2780 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002781 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002782 r.run();
2783 } else {
2784 mHandler.post(r);
2785 }
Joe Onorato36115782010-06-17 13:28:48 -04002786 }
2787
Winson Chung64359a52013-07-08 17:17:08 -07002788 private void loadAllApps() {
2789 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002790
Joe Onorato36115782010-06-17 13:28:48 -04002791 final Callbacks oldCallbacks = mCallbacks.get();
2792 if (oldCallbacks == null) {
2793 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002794 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002795 return;
2796 }
2797
2798 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2799 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2800
Kenny Guyed131872014-04-30 03:02:21 +01002801 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2802
Winson Chung64359a52013-07-08 17:17:08 -07002803 // Clear the list of apps
2804 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002805 SharedPreferences prefs = mContext.getSharedPreferences(
2806 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002807 for (UserHandleCompat user : profiles) {
2808 // Query for the set of apps
2809 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2810 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2811 if (DEBUG_LOADERS) {
2812 Log.d(TAG, "getActivityList took "
2813 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2814 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2815 }
2816 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002817 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002818 if (apps == null || apps.isEmpty()) {
2819 return;
2820 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002821
2822 // Update icon cache
2823 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2824
2825 // If any package icon has changed (app was updated while launcher was dead),
2826 // update the corresponding shortcuts.
2827 if (!updatedPackages.isEmpty()) {
2828 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2829 synchronized (sBgLock) {
2830 for (ItemInfo info : sBgItemsIdMap.values()) {
2831 if (info instanceof ShortcutInfo && user.equals(info.user)
2832 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2833 ShortcutInfo si = (ShortcutInfo) info;
2834 ComponentName cn = si.getTargetComponent();
2835 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2836 si.updateIcon(mIconCache);
2837 updates.add(si);
2838 }
2839 }
2840 }
2841 }
2842
2843 if (!updates.isEmpty()) {
2844 final UserHandleCompat userFinal = user;
2845 mHandler.post(new Runnable() {
2846
2847 public void run() {
2848 Callbacks cb = getCallback();
2849 if (cb != null) {
2850 cb.bindShortcutsChanged(
2851 updates, new ArrayList<ShortcutInfo>(), userFinal);
2852 }
2853 }
2854 });
2855 }
Kenny Guyed131872014-04-30 03:02:21 +01002856 }
Joe Onorato36115782010-06-17 13:28:48 -04002857
Kenny Guyed131872014-04-30 03:02:21 +01002858 // Create the ApplicationInfos
2859 for (int i = 0; i < apps.size(); i++) {
2860 LauncherActivityInfoCompat app = apps.get(i);
2861 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002862 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002863 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002864
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002865 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002866 // Add shortcuts for packages which were installed while launcher was dead.
2867 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2868 + mUserManager.getSerialNumberForUser(user);
2869 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2870 HashSet<String> newPackageSet = new HashSet<String>();
2871
2872 for (LauncherActivityInfoCompat info : apps) {
2873 String packageName = info.getComponentName().getPackageName();
2874 if (!packagesAdded.contains(packageName)
2875 && !newPackageSet.contains(packageName)) {
2876 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2877 }
2878 newPackageSet.add(packageName);
2879 }
2880
2881 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2882 }
Winson Chung64359a52013-07-08 17:17:08 -07002883 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002884 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002885 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2886 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002887
2888 // Post callback on main thread
2889 mHandler.post(new Runnable() {
2890 public void run() {
2891 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002892 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002893 if (callbacks != null) {
2894 callbacks.bindAllApplications(added);
2895 if (DEBUG_LOADERS) {
2896 Log.d(TAG, "bound " + added.size() + " apps in "
2897 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2898 }
2899 } else {
2900 Log.i(TAG, "not binding apps: no Launcher activity");
2901 }
2902 }
2903 });
2904
Joe Onorato36115782010-06-17 13:28:48 -04002905 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002906 Log.d(TAG, "Icons processed in "
2907 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002908 }
2909 }
2910
2911 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002912 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002913 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2914 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2915 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2916 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2917 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2918 }
Joe Onorato36115782010-06-17 13:28:48 -04002919 }
2920 }
2921
2922 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002923 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002924 }
2925
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002926 private class AppsAvailabilityCheck extends BroadcastReceiver {
2927
2928 @Override
2929 public void onReceive(Context context, Intent intent) {
2930 synchronized (sBgLock) {
2931 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2932 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002933 final PackageManager manager = context.getPackageManager();
2934 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2935 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2937 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002938 packagesRemoved.clear();
2939 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002940 for (String pkg : entry.getValue()) {
2941 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002942 boolean packageOnSdcard = launcherApps.isAppEnabled(
2943 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2944 if (packageOnSdcard) {
2945 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2946 packagesUnavailable.add(pkg);
2947 } else {
2948 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2949 packagesRemoved.add(pkg);
2950 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002951 }
2952 }
2953 if (!packagesRemoved.isEmpty()) {
2954 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2955 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2956 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002957 if (!packagesUnavailable.isEmpty()) {
2958 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2959 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2960 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002961 }
Sunny Goyal34942622014-08-29 17:20:55 -07002962 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002963 }
2964 }
2965 }
2966
Joe Onorato36115782010-06-17 13:28:48 -04002967 private class PackageUpdatedTask implements Runnable {
2968 int mOp;
2969 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002970 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002971
2972 public static final int OP_NONE = 0;
2973 public static final int OP_ADD = 1;
2974 public static final int OP_UPDATE = 2;
2975 public static final int OP_REMOVE = 3; // uninstlled
2976 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2977
2978
Kenny Guyed131872014-04-30 03:02:21 +01002979 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002980 mOp = op;
2981 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002982 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002983 }
2984
2985 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002986 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002987
2988 final String[] packages = mPackages;
2989 final int N = packages.length;
2990 switch (mOp) {
2991 case OP_ADD:
2992 for (int i=0; i<N; i++) {
2993 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002994 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002995 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002996 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002997
2998 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002999 if (ADD_MANAGED_PROFILE_SHORTCUTS
3000 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003001 SharedPreferences prefs = context.getSharedPreferences(
3002 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3003 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3004 + mUserManager.getSerialNumberForUser(mUser);
3005 Set<String> shortcutSet = new HashSet<String>(
3006 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
3007
3008 for (int i=0; i<N; i++) {
3009 if (!shortcutSet.contains(packages[i])) {
3010 shortcutSet.add(packages[i]);
3011 List<LauncherActivityInfoCompat> activities =
3012 mLauncherApps.getActivityList(packages[i], mUser);
3013 if (activities != null && !activities.isEmpty()) {
3014 InstallShortcutReceiver.queueInstallShortcut(
3015 activities.get(0), context);
3016 }
3017 }
3018 }
3019
3020 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3021 }
Joe Onorato36115782010-06-17 13:28:48 -04003022 break;
3023 case OP_UPDATE:
3024 for (int i=0; i<N; i++) {
3025 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003026 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003027 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003028 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003029 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003030 }
3031 break;
3032 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003033 // Remove the packageName for the set of auto-installed shortcuts. This
3034 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003035 if (ADD_MANAGED_PROFILE_SHORTCUTS
3036 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003037 SharedPreferences prefs = context.getSharedPreferences(
3038 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3039 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3040 + mUserManager.getSerialNumberForUser(mUser);
3041 HashSet<String> shortcutSet = new HashSet<String>(
3042 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3043 shortcutSet.removeAll(Arrays.asList(mPackages));
3044 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3045 }
Joe Onorato36115782010-06-17 13:28:48 -04003046 for (int i=0; i<N; i++) {
3047 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003048 mIconCache.removeIconsForPkg(packages[i], mUser);
3049 }
3050 // Fall through
3051 case OP_UNAVAILABLE:
3052 for (int i=0; i<N; i++) {
3053 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3054 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003055 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003056 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003057 }
3058 break;
3059 }
3060
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003061 ArrayList<AppInfo> added = null;
3062 ArrayList<AppInfo> modified = null;
3063 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003064
Adam Cohen487f7dd2012-06-28 18:12:10 -07003065 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003066 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003067 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003068 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003069 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003070 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003071 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003072 }
Winson Chung5d55f332012-07-16 20:45:03 -07003073 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003074 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003075 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003076 }
3077
Sunny Goyale0f58d72014-11-10 18:05:31 -08003078 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003079 if (callbacks == null) {
3080 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3081 return;
3082 }
3083
Sunny Goyal4390ace2014-10-13 11:33:11 -07003084 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3085 new HashMap<ComponentName, AppInfo>();
3086
Joe Onorato36115782010-06-17 13:28:48 -04003087 if (added != null) {
Winson Chung64359a52013-07-08 17:17:08 -07003088 // Ensure that we add all the workspace applications to the db
Adam Cohen76a47a12014-02-05 11:47:43 -08003089 if (LauncherAppState.isDisableAllApps()) {
Winson Chung94d67682013-09-25 16:29:40 -07003090 final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Adam Cohen76a47a12014-02-05 11:47:43 -08003091 addAndBindAddedWorkspaceApps(context, addedInfos);
3092 } else {
3093 addAppsToAllApps(context, added);
Winson Chung94d67682013-09-25 16:29:40 -07003094 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003095 for (AppInfo ai : added) {
3096 addedOrUpdatedApps.put(ai.componentName, ai);
3097 }
Joe Onorato36115782010-06-17 13:28:48 -04003098 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003099
Joe Onorato36115782010-06-17 13:28:48 -04003100 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003101 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003102 for (AppInfo ai : modified) {
3103 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003104 }
3105
Joe Onorato36115782010-06-17 13:28:48 -04003106 mHandler.post(new Runnable() {
3107 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003108 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003109 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003110 callbacks.bindAppsUpdated(modifiedFinal);
3111 }
3112 }
3113 });
3114 }
Winson Chung83892cc2013-05-01 16:53:33 -07003115
Sunny Goyal4390ace2014-10-13 11:33:11 -07003116 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003117 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003118 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3119 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3120 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3121
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003122 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003123 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003124 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003125 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3126 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003127 boolean infoUpdated = false;
3128 boolean shortcutUpdated = false;
3129
3130 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003131 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003132 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003133 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3134 si.iconResource.resourceName, mIconCache, context);
3135 if (icon != null) {
3136 si.setIcon(icon);
3137 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003138 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003139 }
3140 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003141
3142 ComponentName cn = si.getTargetComponent();
3143 if (cn != null && packageSet.contains(cn.getPackageName())) {
3144 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3145
3146 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003147 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3148 // Auto install icon
3149 PackageManager pm = context.getPackageManager();
3150 ResolveInfo matched = pm.resolveActivity(
3151 new Intent(Intent.ACTION_MAIN)
3152 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3153 PackageManager.MATCH_DEFAULT_ONLY);
3154 if (matched == null) {
3155 // Try to find the best match activity.
3156 Intent intent = pm.getLaunchIntentForPackage(
3157 cn.getPackageName());
3158 if (intent != null) {
3159 cn = intent.getComponent();
3160 appInfo = addedOrUpdatedApps.get(cn);
3161 }
3162
3163 if ((intent == null) || (appInfo == null)) {
3164 removedShortcuts.add(si);
3165 continue;
3166 }
3167 si.promisedIntent = intent;
3168 }
3169 }
3170
3171 // Restore the shortcut.
3172 si.intent = si.promisedIntent;
3173 si.promisedIntent = null;
3174 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3175 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3176 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3177
3178 infoUpdated = true;
3179 si.updateIcon(mIconCache);
3180 }
3181
3182 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3183 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3184 si.updateIcon(mIconCache);
3185 si.title = appInfo.title.toString();
3186 si.contentDescription = appInfo.contentDescription;
3187 infoUpdated = true;
3188 }
3189
3190 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3191 // Since package was just updated, the target must be available now.
3192 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3193 shortcutUpdated = true;
3194 }
3195 }
3196
3197 if (infoUpdated || shortcutUpdated) {
3198 updatedShortcuts.add(si);
3199 }
3200 if (infoUpdated) {
3201 updateItemInDatabase(context, si);
3202 }
3203 } else if (info instanceof LauncherAppWidgetInfo) {
3204 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3205 if (mUser.equals(widgetInfo.user)
3206 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3207 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3208 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3209 widgets.add(widgetInfo);
3210 updateItemInDatabase(context, widgetInfo);
3211 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003212 }
3213 }
3214 }
3215
Sunny Goyal4390ace2014-10-13 11:33:11 -07003216 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3217 mHandler.post(new Runnable() {
3218
3219 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003220 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003221 if (callbacks == cb && cb != null) {
3222 callbacks.bindShortcutsChanged(
3223 updatedShortcuts, removedShortcuts, mUser);
3224 }
3225 }
3226 });
3227 if (!removedShortcuts.isEmpty()) {
3228 deleteItemsFromDatabase(context, removedShortcuts);
3229 }
3230 }
3231 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003232 mHandler.post(new Runnable() {
3233 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003234 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003235 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003236 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003237 }
3238 }
3239 });
3240 }
3241 }
3242
Winson Chungdf95eb12013-10-16 14:57:07 -07003243 final ArrayList<String> removedPackageNames =
3244 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003245 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003246 // Mark all packages in the broadcast to be removed
3247 removedPackageNames.addAll(Arrays.asList(packages));
3248 } else if (mOp == OP_UPDATE) {
3249 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003250 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003251 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003252 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003253 }
3254 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003255 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003256
Winson Chungdf95eb12013-10-16 14:57:07 -07003257 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003258 final int removeReason;
3259 if (mOp == OP_UNAVAILABLE) {
3260 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3261 } else {
3262 // Remove all the components associated with this package
3263 for (String pn : removedPackageNames) {
3264 deletePackageFromDatabase(context, pn, mUser);
3265 }
3266 // Remove all the specific components
3267 for (AppInfo a : removedApps) {
3268 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3269 deleteItemsFromDatabase(context, infos);
3270 }
3271 removeReason = 0;
3272 }
3273
Winson Chungdf95eb12013-10-16 14:57:07 -07003274 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003275 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003276 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003277 mHandler.post(new Runnable() {
3278 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003279 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003280 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003281 callbacks.bindComponentsRemoved(
3282 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003283 }
3284 }
3285 });
Joe Onoratobe386092009-11-17 17:32:16 -08003286 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003287
Michael Jurkac402cd92013-05-20 15:49:32 +02003288 final ArrayList<Object> widgetsAndShortcuts =
Kenny Guyed131872014-04-30 03:02:21 +01003289 getSortedWidgetsAndShortcuts(context);
Winson Chung80baf5a2010-08-09 16:03:15 -07003290 mHandler.post(new Runnable() {
3291 @Override
3292 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003293 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003294 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003295 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003296 }
3297 }
3298 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003299
3300 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003301 mHandler.post(new Runnable() {
3302 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003303 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003304 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003305 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003306 }
3307 }
3308 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003309 }
3310 }
3311
Adam Cohen59400422014-03-05 18:07:04 -08003312 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context) {
3313 synchronized (sBgLock) {
3314 if (sBgWidgetProviders != null && !sWidgetProvidersDirty) {
3315 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3316 }
3317 sBgWidgetProviders = new HashMap<ComponentName, LauncherAppWidgetProviderInfo>();
3318 List<AppWidgetProviderInfo> widgets =
3319 AppWidgetManagerCompat.getInstance(context).getAllProviders();
3320 LauncherAppWidgetProviderInfo info;
3321 for (AppWidgetProviderInfo pInfo : widgets) {
3322 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3323 sBgWidgetProviders.put(info.provider, info);
3324 }
3325
3326 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3327 for (CustomAppWidget widget : customWidgets) {
3328 info = new LauncherAppWidgetProviderInfo(context, widget);
3329 sBgWidgetProviders.put(info.provider, info);
3330 }
3331 sWidgetProvidersDirty = false;
3332 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3333 }
3334 }
3335
3336 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name) {
3337 synchronized (sBgLock) {
3338 if (sBgWidgetProviders == null) {
3339 getWidgetProviders(ctx);
3340 }
3341 return sBgWidgetProviders.get(name);
3342 }
3343 }
3344
Michael Jurkac402cd92013-05-20 15:49:32 +02003345 // Returns a list of ResolveInfos/AppWindowInfos in sorted order
3346 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
3347 PackageManager packageManager = context.getPackageManager();
3348 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Adam Cohen59400422014-03-05 18:07:04 -08003349 widgetsAndShortcuts.addAll(getWidgetProviders(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003350 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3351 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003352 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003353 return widgetsAndShortcuts;
3354 }
3355
Kenny Guyed131872014-04-30 03:02:21 +01003356 private static boolean isPackageDisabled(Context context, String packageName,
3357 UserHandleCompat user) {
3358 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3359 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003360 }
Adam Cohen556f6132014-01-15 15:18:08 -08003361
Kenny Guyed131872014-04-30 03:02:21 +01003362 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3363 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003364 if (cn == null) {
3365 return false;
3366 }
Kenny Guyed131872014-04-30 03:02:21 +01003367 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3368 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003369 return false;
3370 }
Kenny Guyed131872014-04-30 03:02:21 +01003371 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003372 }
3373
Adam Cohena28b78e2014-05-20 17:03:04 -07003374 public static boolean isValidPackage(Context context, String packageName,
3375 UserHandleCompat user) {
3376 if (packageName == null) {
3377 return false;
3378 }
3379 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3380 return launcherApps.isPackageEnabledForProfile(packageName, user);
3381 }
3382
Joe Onorato9c1289c2009-08-17 11:03:03 -04003383 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003384 * Make an ShortcutInfo object for a restored application or shortcut item that points
3385 * to a package that is not yet installed on the system.
3386 */
Sunny Goyal34942622014-08-29 17:20:55 -07003387 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
3388 int promiseType) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003389 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003390 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003391 mIconCache.getTitleAndIcon(info, intent, info.user);
Sunny Goyal34942622014-08-29 17:20:55 -07003392
3393 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3394 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3395 if (!TextUtils.isEmpty(title)) {
3396 info.title = title;
3397 }
3398 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3399 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3400 if (TextUtils.isEmpty(info.title)) {
3401 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3402 }
3403 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3404 } else {
3405 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3406 }
3407
Kenny Guyc2bd8102014-06-30 12:30:31 +01003408 info.contentDescription = mUserManager.getBadgedLabelForUser(
3409 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003410 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003411 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003412 return info;
3413 }
3414
3415 /**
3416 * Make an Intent object for a restored application or shortcut item that points
3417 * to the market page for the item.
3418 */
3419 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3420 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003421 return getMarketIntent(componentName.getPackageName());
3422 }
3423
3424 static Intent getMarketIntent(String packageName) {
3425 return new Intent(Intent.ACTION_VIEW)
3426 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003427 .scheme("market")
3428 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003429 .appendQueryParameter("id", packageName)
3430 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003431 }
3432
3433 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003434 * Make an ShortcutInfo object for a shortcut that is an application.
3435 *
3436 * If c is not null, then it will be used to fill in missing data like the title and icon.
3437 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003438 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003439 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003440 boolean allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003441 if (user == null) {
3442 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003443 return null;
3444 }
3445
Kenny Guyed131872014-04-30 03:02:21 +01003446 ComponentName componentName = intent.getComponent();
3447 if (componentName == null) {
3448 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3449 return null;
3450 }
3451
3452 Intent newIntent = new Intent(intent.getAction(), null);
3453 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3454 newIntent.setComponent(componentName);
3455 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003456 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003457 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3458 return null;
3459 }
3460
3461 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003462 mIconCache.getTitleAndIcon(info, componentName, lai, user, false);
3463 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3464 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3465 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003466 }
3467
Joe Onorato56d82912010-03-07 14:32:10 -05003468 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003469 if (TextUtils.isEmpty(info.title) && c != null) {
3470 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003471 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003472
Joe Onorato56d82912010-03-07 14:32:10 -05003473 // fall back to the class name of the activity
3474 if (info.title == null) {
3475 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003476 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003477
Joe Onorato9c1289c2009-08-17 11:03:03 -04003478 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003479 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003480 info.contentDescription = mUserManager.getBadgedLabelForUser(
3481 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003482 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003483 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003484
Winson Chung64359a52013-07-08 17:17:08 -07003485 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3486 ItemInfoFilter f) {
3487 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3488 for (ItemInfo i : infos) {
3489 if (i instanceof ShortcutInfo) {
3490 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003491 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003492 if (cn != null && f.filterItem(null, info, cn)) {
3493 filtered.add(info);
3494 }
3495 } else if (i instanceof FolderInfo) {
3496 FolderInfo info = (FolderInfo) i;
3497 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003498 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003499 if (cn != null && f.filterItem(info, s, cn)) {
3500 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003501 }
3502 }
Winson Chung64359a52013-07-08 17:17:08 -07003503 } else if (i instanceof LauncherAppWidgetInfo) {
3504 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3505 ComponentName cn = info.providerName;
3506 if (cn != null && f.filterItem(null, info, cn)) {
3507 filtered.add(info);
3508 }
Winson Chung8a435102012-08-30 17:16:53 -07003509 }
3510 }
Winson Chung64359a52013-07-08 17:17:08 -07003511 return new ArrayList<ItemInfo>(filtered);
3512 }
3513
Kenny Guyed131872014-04-30 03:02:21 +01003514 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3515 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003516 ItemInfoFilter filter = new ItemInfoFilter() {
3517 @Override
3518 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003519 if (info.user == null) {
3520 return cn.equals(cname);
3521 } else {
3522 return cn.equals(cname) && info.user.equals(user);
3523 }
Winson Chung64359a52013-07-08 17:17:08 -07003524 }
3525 };
3526 return filterItemInfos(sBgItemsIdMap.values(), filter);
3527 }
3528
Sunny Goyal1a745e82014-10-02 15:58:31 -07003529 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003530 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003531 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003532 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003533 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3534 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003535
Joe Onorato56d82912010-03-07 14:32:10 -05003536 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003537 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003538 // Non-app shortcuts are only supported for current user.
3539 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003540 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003541
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003542 // TODO: If there's an explicit component and we can't install that, delete it.
3543
Joe Onorato56d82912010-03-07 14:32:10 -05003544 info.title = c.getString(titleIndex);
3545
Joe Onorato9c1289c2009-08-17 11:03:03 -04003546 int iconType = c.getInt(iconTypeIndex);
3547 switch (iconType) {
3548 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3549 String packageName = c.getString(iconPackageIndex);
3550 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003551 info.customIcon = false;
3552 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003553 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003554 // the db
3555 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003556 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003557 }
3558 // the fallback icon
3559 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003560 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003561 info.usingFallbackIcon = true;
3562 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003563 break;
3564 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003565 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003566 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003567 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003568 info.customIcon = false;
3569 info.usingFallbackIcon = true;
3570 } else {
3571 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003572 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003573 break;
3574 default:
Kenny Guyed131872014-04-30 03:02:21 +01003575 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003576 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003577 info.customIcon = false;
3578 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003579 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003580 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003581 return info;
3582 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003583
Sunny Goyal2350bc92014-10-14 16:42:54 -07003584 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003585 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3586 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3587 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3588
Adam Cohend9198822011-11-22 16:42:47 -08003589 if (intent == null) {
3590 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3591 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3592 return null;
3593 }
3594
Joe Onorato0589f0f2010-02-08 13:44:00 -08003595 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003596 boolean customIcon = false;
3597 ShortcutIconResource iconResource = null;
3598
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003599 if (bitmap instanceof Bitmap) {
3600 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003601 customIcon = true;
3602 } else {
3603 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003604 if (extra instanceof ShortcutIconResource) {
3605 iconResource = (ShortcutIconResource) extra;
3606 icon = Utilities.createIconBitmap(iconResource.packageName,
3607 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003608 }
3609 }
3610
Michael Jurkac9d95c52011-08-29 14:03:34 -07003611 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003612
Kenny Guyed131872014-04-30 03:02:21 +01003613 // Only support intents for current user for now. Intents sent from other
3614 // users wouldn't get here without intent forwarding anyway.
3615 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003616 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003617 icon = mIconCache.getDefaultIcon(info.user);
3618 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003619 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003620 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003621
Joe Onorato0589f0f2010-02-08 13:44:00 -08003622 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003623 info.contentDescription = mUserManager.getBadgedLabelForUser(
3624 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003625 info.intent = intent;
3626 info.customIcon = customIcon;
3627 info.iconResource = iconResource;
3628
3629 return info;
3630 }
3631
Joe Onorato9c1289c2009-08-17 11:03:03 -04003632 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003633 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003634 * or make a new one.
3635 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003636 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003637 // See if a placeholder was created for us already
3638 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003639 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003640 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003641 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003642 folders.put(id, folderInfo);
3643 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003644 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003645 }
3646
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003647 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003648 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003649 return new Comparator<AppInfo>() {
3650 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003651 if (a.user.equals(b.user)) {
3652 int result = collator.compare(a.title.toString().trim(),
3653 b.title.toString().trim());
3654 if (result == 0) {
3655 result = a.componentName.compareTo(b.componentName);
3656 }
3657 return result;
3658 } else {
3659 // TODO Need to figure out rules for sorting
3660 // profiles, this puts work second.
3661 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003662 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003663 }
Winson Chung11904872012-09-17 16:58:46 -07003664 };
3665 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003666 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3667 = new Comparator<AppInfo>() {
3668 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003669 if (a.firstInstallTime < b.firstInstallTime) return 1;
3670 if (a.firstInstallTime > b.firstInstallTime) return -1;
3671 return 0;
3672 }
3673 };
Winson Chung5308f242011-08-18 12:12:41 -07003674 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3675 if (info.activityInfo != null) {
3676 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3677 } else {
3678 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3679 }
3680 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003681
Winson Chung1ed747a2011-05-03 16:18:34 -07003682 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003683 private final AppWidgetManagerCompat mManager;
3684 private final PackageManager mPackageManager;
3685 private final HashMap<Object, String> mLabelCache;
3686 private final Collator mCollator;
3687
3688 WidgetAndShortcutNameComparator(Context context) {
3689 mManager = AppWidgetManagerCompat.getInstance(context);
3690 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003691 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003692 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003693 }
3694 public final int compare(Object a, Object b) {
3695 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003696 if (mLabelCache.containsKey(a)) {
3697 labelA = mLabelCache.get(a);
3698 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003699 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3700 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003701 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003702 mLabelCache.put(a, labelA);
3703 }
3704 if (mLabelCache.containsKey(b)) {
3705 labelB = mLabelCache.get(b);
3706 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003707 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003708 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003709 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003710 mLabelCache.put(b, labelB);
3711 }
Winson Chung11904872012-09-17 16:58:46 -07003712 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003713 }
3714 };
Joe Onoratobe386092009-11-17 17:32:16 -08003715
Sunny Goyal651077b2014-06-30 14:15:31 -07003716 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3717 return (provider != null) && (provider.provider != null)
3718 && (provider.provider.getPackageName() != null);
3719 }
3720
Joe Onoratobe386092009-11-17 17:32:16 -08003721 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003722 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003723 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3724 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3725 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3726 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003727 if (mLoaderTask != null) {
3728 mLoaderTask.dumpState();
3729 } else {
3730 Log.d(TAG, "mLoaderTask=null");
3731 }
Joe Onoratobe386092009-11-17 17:32:16 -08003732 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003733
3734 public Callbacks getCallback() {
3735 return mCallbacks != null ? mCallbacks.get() : null;
3736 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003737}