blob: dcb375928532b04bd6b431116367f6cb4c157081 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Robin Lee26ace122015-03-16 19:41:43 +000061import com.android.launcher3.util.ComponentKey;
Adam Cohen091440a2015-03-18 14:16:05 -070062import com.android.launcher3.util.Thunk;
Romain Guyedcce092010-03-04 13:03:17 -080063
Michael Jurkac2f801e2011-07-12 14:19:46 -070064import java.lang.ref.WeakReference;
65import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070066import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070067import java.text.Collator;
68import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070069import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070070import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070071import java.util.Collections;
72import java.util.Comparator;
73import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070074import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070075import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070076import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070077import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070078import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080/**
81 * Maintains in-memory state of the Launcher. It is expected that there should be only one
82 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070083 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 */
Kenny Guyed131872014-04-30 03:02:21 +010085public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010086 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040088 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070089 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080090 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040091
Joe Onorato9c1289c2009-08-17 11:03:03 -040092 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070093
Dan Sandlerd5024042014-01-09 15:01:33 -050094 public static final int LOADER_FLAG_NONE = 0;
95 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
96 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
97
Joe Onorato36115782010-06-17 13:28:48 -040098 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050099 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800100
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800102 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400103
Adam Cohen091440a2015-03-18 14:16:05 -0700104 @Thunk final LauncherAppState mApp;
105 @Thunk final Object mLock = new Object();
106 @Thunk DeferredHandler mHandler = new DeferredHandler();
107 @Thunk LoaderTask mLoaderTask;
108 @Thunk boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Sunny Goyale0f58d72014-11-10 18:05:31 -0800110 /**
111 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
112 */
113 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
114
Winson Chung81b52252012-08-27 15:34:29 -0700115 // Specific runnable types that are run on the main thread deferred handler, this allows us to
116 // clear all queued binding runnables when the Launcher activity is destroyed.
117 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
118 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
119
Jason Monkbbe1e242014-05-16 17:37:34 -0400120 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700121
Adam Cohen091440a2015-03-18 14:16:05 -0700122 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700123 static {
124 sWorkerThread.start();
125 }
Adam Cohen091440a2015-03-18 14:16:05 -0700126 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700127
Joe Onoratocc67f472010-06-08 10:54:30 -0700128 // We start off with everything not loaded. After that, we assume that
129 // our monitoring of the package manager provides all updates and we never
130 // need to do a requery. These are only ever touched from the loader thread.
Adam Cohen091440a2015-03-18 14:16:05 -0700131 @Thunk boolean mWorkspaceLoaded;
132 @Thunk boolean mAllAppsLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700133
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700134 // When we are loading pages synchronously, we can't just post the binding of items on the side
135 // pages as this delays the rotation process. Instead, we wait for a callback from the first
136 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
137 // a normal load, we also clear this set of Runnables.
138 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
139
Adam Cohen091440a2015-03-18 14:16:05 -0700140 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700142 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700143 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800144
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145 // The lock that must be acquired before referencing any static bg data structures. Unlike
146 // other locks, this one can generally be held long-term because we never expect any of these
147 // static data structures to be referenced outside of the worker thread except on the first
148 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700149 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700152 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700153 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
156 // created by LauncherModel that are directly on the home screen (however, no widgets or
157 // shortcuts within folders).
158 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700159
Adam Cohen487f7dd2012-06-28 18:12:10 -0700160 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
161 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700162 new ArrayList<LauncherAppWidgetInfo>();
163
Adam Cohen487f7dd2012-06-28 18:12:10 -0700164 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
165 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700166
Adam Cohendcd297f2013-06-18 13:13:40 -0700167 // sBgWorkspaceScreens is the ordered set of workspace screens.
168 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
169
Adam Cohen59400422014-03-05 18:07:04 -0800170 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000171 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800172
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700173 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700174 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
175 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700176
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 // </ only access in worker thread >
178
Adam Cohen091440a2015-03-18 14:16:05 -0700179 @Thunk IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180
Reena Lee99a73f32011-10-24 17:27:37 -0700181 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700182
Adam Cohen091440a2015-03-18 14:16:05 -0700183 @Thunk final LauncherAppsCompat mLauncherApps;
184 @Thunk final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100185
Joe Onorato9c1289c2009-08-17 11:03:03 -0400186 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700187 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400188 public int getCurrentWorkspaceScreen();
189 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700190 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
191 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700192 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700193 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500194 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800195 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400196 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200197 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700198 public void bindAppsAdded(ArrayList<Long> newScreens,
199 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700200 ArrayList<ItemInfo> addAnimated,
201 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200202 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700203 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
204 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
205 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700206 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700207 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700208 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700209 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200210 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100211 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700212 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700213 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700214 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800215 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
216 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400217 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218
Winson Chung64359a52013-07-08 17:17:08 -0700219 public interface ItemInfoFilter {
220 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
221 }
222
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800223 public interface ScreenPosProvider {
224 int getScreenIndex(ArrayList<Long> screenIDs);
225 }
226
Bjorn Bringert1307f632013-10-03 22:31:03 +0100227 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800228 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400229
Winson Chungee055712013-07-30 14:46:24 -0700230 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700231 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400232 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
233 // resource string.
234 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
235 ProviderInfo providerInfo =
236 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
237 ProviderInfo redirectProvider =
238 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700239
240 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400241 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700242
243 if (mOldContentProviderExists) {
244 Log.d(TAG, "Old launcher provider exists.");
245 } else {
246 Log.d(TAG, "Old launcher provider does not exist.");
247 }
248
Daniel Sandlere4f98912013-06-25 15:13:26 -0400249 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100250 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800251 mIconCache = iconCache;
252
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400253 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700254 Configuration config = res.getConfiguration();
255 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100256 mLauncherApps = LauncherAppsCompat.getInstance(context);
257 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800258 }
259
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700260 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
261 * posted on the main thread handler. */
Adam Cohen091440a2015-03-18 14:16:05 -0700262 @Thunk void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700263 runOnMainThread(r, 0);
264 }
Adam Cohen091440a2015-03-18 14:16:05 -0700265 @Thunk void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700266 if (sWorkerThread.getThreadId() == Process.myTid()) {
267 // If we are on the worker thread, post onto the main handler
268 mHandler.post(r);
269 } else {
270 r.run();
271 }
272 }
273
274 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
275 * posted on the worker thread handler. */
276 private static void runOnWorkerThread(Runnable r) {
277 if (sWorkerThread.getThreadId() == Process.myTid()) {
278 r.run();
279 } else {
280 // If we are not on the worker thread, then post to the worker handler
281 sWorker.post(r);
282 }
283 }
284
Winson Chunge43a1e72014-01-15 10:33:02 -0800285 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
286 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800287 }
288
Sunny Goyale755d462014-07-22 13:48:29 -0700289 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500290 // Process the updated package state
291 Runnable r = new Runnable() {
292 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800293 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500294 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700295 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500296 }
297 }
298 };
299 mHandler.post(r);
300 }
301
Sunny Goyala22666f2014-09-18 13:25:15 -0700302 public void updatePackageBadge(final String packageName) {
303 // Process the updated package badge
304 Runnable r = new Runnable() {
305 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800306 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700307 if (callbacks != null) {
308 callbacks.updatePackageBadge(packageName);
309 }
310 }
311 };
312 mHandler.post(r);
313 }
314
Adam Cohen76a47a12014-02-05 11:47:43 -0800315 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800316 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800317
318 if (allAppsApps == null) {
319 throw new RuntimeException("allAppsApps must not be null");
320 }
321 if (allAppsApps.isEmpty()) {
322 return;
323 }
324
325 // Process the newly added applications and add them to the database first
326 Runnable r = new Runnable() {
327 public void run() {
328 runOnMainThread(new Runnable() {
329 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800330 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800331 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500332 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800333 }
334 }
335 });
336 }
337 };
338 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700339 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800340
341 public void addAndBindAddedWorkspaceApps(final Context context,
342 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800343 addAndBindAddedWorkspaceApps(context, workspaceApps,
344 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800345
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800346 @Override
347 public int getScreenIndex(ArrayList<Long> screenIDs) {
348 return screenIDs.isEmpty() ? 0 : 1;
349 }
350 }, 1, false);
351 }
352
353 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
354 int[] xy, int spanX, int spanY) {
355 LauncherAppState app = LauncherAppState.getInstance();
356 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
357 final int xCount = (int) grid.numColumns;
358 final int yCount = (int) grid.numRows;
359 boolean[][] occupied = new boolean[xCount][yCount];
360 if (occupiedPos != null) {
361 for (Rect r : occupiedPos) {
362 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
363 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
364 occupied[x][y] = true;
365 }
366 }
367 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800368 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800369 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
370 }
371
372 /**
373 * Find a position on the screen for the given size or adds a new screen.
374 * @return screenId and the coordinates for the item.
375 */
Adam Cohen091440a2015-03-18 14:16:05 -0700376 @Thunk static Pair<Long, int[]> findSpaceForItem(
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800377 Context context,
378 ScreenPosProvider preferredScreen,
379 int fallbackStartScreen,
380 ArrayList<Long> workspaceScreens,
381 ArrayList<Long> addedWorkspaceScreensFinal,
382 int spanX, int spanY) {
383 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
384 // loadWorkspace() may not have been called.
385 final ContentResolver cr = context.getContentResolver();
386 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
387 new String[] {
388 LauncherSettings.Favorites.SCREEN,
389 LauncherSettings.Favorites.CELLX,
390 LauncherSettings.Favorites.CELLY,
391 LauncherSettings.Favorites.SPANX,
392 LauncherSettings.Favorites.SPANY,
393 LauncherSettings.Favorites.CONTAINER
394 },
395 "container=?",
396 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
397 null);
398
399 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
400 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
401 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
402 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
403 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
404 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
405 try {
406 while (c.moveToNext()) {
407 Rect rect = new Rect();
408 rect.left = c.getInt(cellXIndex);
409 rect.top = c.getInt(cellYIndex);
410 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
411 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
412
413 long screenId = c.getInt(screenIndex);
414 ArrayList<Rect> items = screenItems.get(screenId);
415 if (items == null) {
416 items = new ArrayList<Rect>();
417 screenItems.put(screenId, items);
418 }
419 items.add(rect);
420 }
421 } catch (Exception e) {
422 screenItems.clear();
423 } finally {
424 c.close();
425 }
426
427 // Find appropriate space for the item.
428 long screenId = 0;
429 int[] cordinates = new int[2];
430 boolean found = false;
431
432 int screenCount = workspaceScreens.size();
433 // First check the preferred screen.
434 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
435 if (preferredScreenIndex < screenCount) {
436 screenId = workspaceScreens.get(preferredScreenIndex);
437 found = findNextAvailableIconSpaceInScreen(
438 screenItems.get(screenId), cordinates, spanX, spanY);
439 }
440
441 if (!found) {
442 // Search on any of the screens.
443 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
444 screenId = workspaceScreens.get(screen);
445 if (findNextAvailableIconSpaceInScreen(
446 screenItems.get(screenId), cordinates, spanX, spanY)) {
447 // We found a space for it
448 found = true;
449 break;
450 }
451 }
452 }
453
454 if (!found) {
455 // Still no position found. Add a new screen to the end.
456 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
457
458 // Save the screen id for binding in the workspace
459 workspaceScreens.add(screenId);
460 addedWorkspaceScreensFinal.add(screenId);
461
462 // If we still can't find an empty space, then God help us all!!!
463 if (!findNextAvailableIconSpaceInScreen(
464 screenItems.get(screenId), cordinates, spanX, spanY)) {
465 throw new RuntimeException("Can't find space to add the item");
466 }
467 }
468 return Pair.create(screenId, cordinates);
469 }
470
471 /**
472 * Adds the provided items to the workspace.
473 * @param preferredScreen the screen where we should try to add the app first
474 * @param fallbackStartScreen the screen to start search for empty space if
475 * preferredScreen is not available.
476 */
477 public void addAndBindPendingItem(
478 final Context context,
479 final PendingAddItemInfo addInfo,
480 final ScreenPosProvider preferredScreen,
481 final int fallbackStartScreen) {
482 final Callbacks callbacks = getCallback();
483 // Process the newly added applications and add them to the database first
484 Runnable r = new Runnable() {
485 public void run() {
486 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800487 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800488
489 // Find appropriate space for the item.
490 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
491 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
492 addInfo.spanX,
493 addInfo.spanY);
494 final long screenId = coords.first;
495 final int[] cordinates = coords.second;
496
497 // Update the workspace screens
498 updateWorkspaceScreenOrder(context, workspaceScreens);
499 runOnMainThread(new Runnable() {
500 public void run() {
501 Callbacks cb = getCallback();
502 if (callbacks == cb && cb != null) {
503 cb.bindAddScreens(addedWorkspaceScreensFinal);
504 cb.bindAddPendingItem(addInfo,
505 LauncherSettings.Favorites.CONTAINER_DESKTOP,
506 screenId, cordinates, addInfo.spanX, addInfo.spanY);
507 }
508 }
509 });
510 }
511 };
512 runOnWorkerThread(r);
513 }
514
515 /**
516 * Adds the provided items to the workspace.
517 * @param preferredScreen the screen where we should try to add the app first
518 * @param fallbackStartScreen the screen to start search for empty space if
519 * preferredScreen is not available.
520 */
521 public void addAndBindAddedWorkspaceApps(final Context context,
522 final ArrayList<ItemInfo> workspaceApps,
523 final ScreenPosProvider preferredScreen,
524 final int fallbackStartScreen,
525 final boolean allowDuplicate) {
526 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800527 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700528 return;
Winson Chung997a9232013-07-24 15:33:46 -0700529 }
Winson Chung64359a52013-07-08 17:17:08 -0700530 // Process the newly added applications and add them to the database first
531 Runnable r = new Runnable() {
532 public void run() {
533 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
534 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
535
Winson Chung76828c82013-08-19 15:43:29 -0700536 // Get the list of workspace screens. We need to append to this list and
537 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
538 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800539 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700540 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800541 for (ItemInfo item : workspaceApps) {
542 if (!allowDuplicate) {
543 // Short-circuit this logic if the icon exists somewhere on the workspace
544 if (shortcutExists(context, item.title.toString(),
545 item.getIntent(), item.user)) {
546 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700547 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800548 }
Winson Chung76828c82013-08-19 15:43:29 -0700549
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800550 // Find appropriate space for the item.
551 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
552 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
553 1, 1);
554 long screenId = coords.first;
555 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700556
Winson Chung997a9232013-07-24 15:33:46 -0700557 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800558 if (item instanceof ShortcutInfo) {
559 shortcutInfo = (ShortcutInfo) item;
560 } else if (item instanceof AppInfo) {
561 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700562 } else {
563 throw new RuntimeException("Unexpected info type");
564 }
Winson Chung94d67682013-09-25 16:29:40 -0700565
Winson Chung64359a52013-07-08 17:17:08 -0700566 // Add the shortcut to the db
567 addItemToDatabase(context, shortcutInfo,
568 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800569 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700570 // Save the ShortcutInfo for binding in the workspace
571 addedShortcutsFinal.add(shortcutInfo);
572 }
573 }
574
Winson Chung76828c82013-08-19 15:43:29 -0700575 // Update the workspace screens
576 updateWorkspaceScreenOrder(context, workspaceScreens);
577
Adam Cohen76a47a12014-02-05 11:47:43 -0800578 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700579 runOnMainThread(new Runnable() {
580 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800581 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700582 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700583 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
584 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700585 if (!addedShortcutsFinal.isEmpty()) {
586 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
587 long lastScreenId = info.screenId;
588 for (ItemInfo i : addedShortcutsFinal) {
589 if (i.screenId == lastScreenId) {
590 addAnimated.add(i);
591 } else {
592 addNotAnimated.add(i);
593 }
Winson Chung997a9232013-07-24 15:33:46 -0700594 }
595 }
Winson Chungd64d1762013-08-20 14:37:16 -0700596 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800597 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700598 }
Winson Chung64359a52013-07-08 17:17:08 -0700599 }
Winson Chung997a9232013-07-24 15:33:46 -0700600 });
601 }
Winson Chung64359a52013-07-08 17:17:08 -0700602 }
603 };
604 runOnWorkerThread(r);
605 }
606
Winson Chung81b52252012-08-27 15:34:29 -0700607 public void unbindItemInfosAndClearQueuedBindRunnables() {
608 if (sWorkerThread.getThreadId() == Process.myTid()) {
609 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
610 "main thread");
611 }
612
613 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400614 synchronized (mDeferredBindRunnables) {
615 mDeferredBindRunnables.clear();
616 }
Winson Chung81b52252012-08-27 15:34:29 -0700617 // Remove any queued bind runnables
618 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
619 // Unbind all the workspace items
620 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700621 }
622
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700623 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700624 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700625 // Ensure that we don't use the same workspace items data structure on the main thread
626 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700627 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
628 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700629 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700630 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
631 tmpAppWidgets.addAll(sBgAppWidgets);
632 }
633 Runnable r = new Runnable() {
634 @Override
635 public void run() {
636 for (ItemInfo item : tmpWorkspaceItems) {
637 item.unbind();
638 }
639 for (ItemInfo item : tmpAppWidgets) {
640 item.unbind();
641 }
642 }
643 };
644 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700645 }
646
Joe Onorato9c1289c2009-08-17 11:03:03 -0400647 /**
648 * Adds an item to the DB if it was not created previously, or move it to a new
649 * <container, screen, cellX, cellY>
650 */
651 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700652 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400653 if (item.container == ItemInfo.NO_ID) {
654 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700655 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400656 } else {
657 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700658 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800659 }
660 }
661
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700662 static void checkItemInfoLocked(
663 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
664 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
665 if (modelItem != null && item != modelItem) {
666 // check all the data is consistent
667 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
668 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
669 ShortcutInfo shortcut = (ShortcutInfo) item;
670 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
671 modelShortcut.intent.filterEquals(shortcut.intent) &&
672 modelShortcut.id == shortcut.id &&
673 modelShortcut.itemType == shortcut.itemType &&
674 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700675 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700676 modelShortcut.cellX == shortcut.cellX &&
677 modelShortcut.cellY == shortcut.cellY &&
678 modelShortcut.spanX == shortcut.spanX &&
679 modelShortcut.spanY == shortcut.spanY &&
680 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
681 (modelShortcut.dropPos != null &&
682 shortcut.dropPos != null &&
683 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
684 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
685 // For all intents and purposes, this is the same object
686 return;
687 }
688 }
689
690 // the modelItem needs to match up perfectly with item if our model is
691 // to be consistent with the database-- for now, just require
692 // modelItem == item or the equality check above
693 String msg = "item: " + ((item != null) ? item.toString() : "null") +
694 "modelItem: " +
695 ((modelItem != null) ? modelItem.toString() : "null") +
696 "Error: ItemInfo passed to checkItemInfo doesn't match original";
697 RuntimeException e = new RuntimeException(msg);
698 if (stackTrace != null) {
699 e.setStackTrace(stackTrace);
700 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800701 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700702 }
703 }
704
Michael Jurka816474f2012-06-25 14:49:02 -0700705 static void checkItemInfo(final ItemInfo item) {
706 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
707 final long itemId = item.id;
708 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700709 public void run() {
710 synchronized (sBgLock) {
711 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700712 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700713 }
714 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700715 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700716 }
717
Michael Jurkac9d95c52011-08-29 14:03:34 -0700718 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
719 final ItemInfo item, final String callingFunction) {
720 final long itemId = item.id;
721 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
722 final ContentResolver cr = context.getContentResolver();
723
Adam Cohen487f7dd2012-06-28 18:12:10 -0700724 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700725 Runnable r = new Runnable() {
726 public void run() {
727 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700728 updateItemArrays(item, itemId, stackTrace);
729 }
730 };
731 runOnWorkerThread(r);
732 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700733
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700734 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
735 final ArrayList<ItemInfo> items, final String callingFunction) {
736 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700737
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700738 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
739 Runnable r = new Runnable() {
740 public void run() {
741 ArrayList<ContentProviderOperation> ops =
742 new ArrayList<ContentProviderOperation>();
743 int count = items.size();
744 for (int i = 0; i < count; i++) {
745 ItemInfo item = items.get(i);
746 final long itemId = item.id;
747 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
748 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700749
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700750 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
751 updateItemArrays(item, itemId, stackTrace);
752
753 }
754 try {
755 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
756 } catch (Exception e) {
757 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700758 }
759 }
760 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700761 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700762 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700763
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700764 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
765 // Lock on mBgLock *after* the db operation
766 synchronized (sBgLock) {
767 checkItemInfoLocked(itemId, item, stackTrace);
768
769 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
770 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
771 // Item is in a folder, make sure this folder exists
772 if (!sBgFolders.containsKey(item.container)) {
773 // An items container is being set to a that of an item which is not in
774 // the list of Folders.
775 String msg = "item: " + item + " container being set to: " +
776 item.container + ", not in the list of folders";
777 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700778 }
779 }
780
781 // Items are added/removed from the corresponding FolderInfo elsewhere, such
782 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
783 // that are on the desktop, as appropriate
784 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800785 if (modelItem != null &&
786 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
787 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700788 switch (modelItem.itemType) {
789 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
790 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
791 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
792 if (!sBgWorkspaceItems.contains(modelItem)) {
793 sBgWorkspaceItems.add(modelItem);
794 }
795 break;
796 default:
797 break;
798 }
799 } else {
800 sBgWorkspaceItems.remove(modelItem);
801 }
802 }
803 }
804
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800805 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700807 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700808 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700809 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400811 item.cellX = cellX;
812 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700813
Winson Chung3d503fb2011-07-13 17:25:49 -0700814 // We store hotseat items in canonical form which is this orientation invariant position
815 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700817 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700818 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700819 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700820 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700821 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400822
823 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400824 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700825 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
826 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800827 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700828 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400829
Michael Jurkac9d95c52011-08-29 14:03:34 -0700830 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700831 }
832
833 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700834 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
835 * cellX, cellY have already been updated on the ItemInfos.
836 */
837 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
838 final long container, final int screen) {
839
840 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
841 int count = items.size();
842
843 for (int i = 0; i < count; i++) {
844 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700845 item.container = container;
846
847 // We store hotseat items in canonical form which is this orientation invariant position
848 // in the hotseat
849 if (context instanceof Launcher && screen < 0 &&
850 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700851 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700852 item.cellY);
853 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700854 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700855 }
856
857 final ContentValues values = new ContentValues();
858 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
859 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
860 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800861 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700862 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700863
864 contentValues.add(values);
865 }
866 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
867 }
868
869 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700870 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800871 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700872 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700873 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700874 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800875 item.cellX = cellX;
876 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700877 item.spanX = spanX;
878 item.spanY = spanY;
879
880 // We store hotseat items in canonical form which is this orientation invariant position
881 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700882 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700884 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700885 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700886 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700887 }
Adam Cohend4844c32011-02-18 19:25:06 -0800888
Adam Cohend4844c32011-02-18 19:25:06 -0800889 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800890 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700891 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
892 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800893 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700894 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
895 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700896 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800897
Michael Jurka816474f2012-06-25 14:49:02 -0700898 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700899 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700900
901 /**
902 * Update an item to the database in a specified container.
903 */
904 static void updateItemInDatabase(Context context, final ItemInfo item) {
905 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100906 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700907 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800908 }
909
910 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400911 * Returns true if the shortcuts already exists in the database.
912 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800913 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800914 static boolean shortcutExists(Context context, String title, Intent intent,
915 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400916 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700917 final Intent intentWithPkg, intentWithoutPkg;
918
919 if (intent.getComponent() != null) {
920 // If component is not null, an intent with null package will produce
921 // the same result and should also be a match.
922 if (intent.getPackage() != null) {
923 intentWithPkg = intent;
924 intentWithoutPkg = new Intent(intent).setPackage(null);
925 } else {
926 intentWithPkg = new Intent(intent).setPackage(
927 intent.getComponent().getPackageName());
928 intentWithoutPkg = intent;
929 }
930 } else {
931 intentWithPkg = intent;
932 intentWithoutPkg = intent;
933 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800934 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
935 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400936 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800937 new String[] { "title", "intent", "profileId" },
938 "title=? and (intent=? or intent=?) and profileId=?",
939 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
940 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400941 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800942 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400943 } finally {
944 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700946 }
947
Joe Onorato9c1289c2009-08-17 11:03:03 -0400948 /**
949 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
950 */
951 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
952 final ContentResolver cr = context.getContentResolver();
953 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
954 "_id=? and (itemType=? or itemType=?)",
955 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700956 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700957
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 try {
959 if (c.moveToFirst()) {
960 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
961 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
962 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
963 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
964 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
965 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700966 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800967
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968 FolderInfo folderInfo = null;
969 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700970 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
971 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400972 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700973 }
974
Joe Onorato9c1289c2009-08-17 11:03:03 -0400975 folderInfo.title = c.getString(titleIndex);
976 folderInfo.id = id;
977 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700978 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700979 folderInfo.cellX = c.getInt(cellXIndex);
980 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700981 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400982
983 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700984 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400985 } finally {
986 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700987 }
988
989 return null;
990 }
991
Joe Onorato9c1289c2009-08-17 11:03:03 -0400992 /**
993 * Add an item to the database in a specified container. Sets the container, screen, cellX and
994 * cellY fields of the item. Also assigns an ID to the item.
995 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700996 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700997 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400999 item.cellX = cellX;
1000 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 // We store hotseat items in canonical form which is this orientation invariant position
1002 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001006 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001007 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001008 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
1010 final ContentValues values = new ContentValues();
1011 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001012 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013
Michael Jurka414300a2013-08-27 15:42:35 +02001014 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001016
Jason Monk8e19cf22014-03-20 15:06:57 -04001017 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001018 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001019 public void run() {
1020 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1021 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001022
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001023 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001024 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001025 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001026 sBgItemsIdMap.put(item.id, item);
1027 switch (item.itemType) {
1028 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1029 sBgFolders.put(item.id, (FolderInfo) item);
1030 // Fall through
1031 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1032 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1033 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1034 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1035 sBgWorkspaceItems.add(item);
1036 } else {
1037 if (!sBgFolders.containsKey(item.container)) {
1038 // Adding an item to a folder that doesn't exist.
1039 String msg = "adding item: " + item + " to a folder that " +
1040 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001041 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001042 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001043 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001044 break;
1045 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1046 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1047 break;
1048 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001049 }
1050 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001051 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001052 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001053 }
1054
Joe Onorato9c1289c2009-08-17 11:03:03 -04001055 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001056 * Creates a new unique child id, for a given cell span across all layouts.
1057 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001058 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001059 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001060 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001061 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001062 }
1063
Sunny Goyal34942622014-08-29 17:20:55 -07001064 private static ArrayList<ItemInfo> getItemsByPackageName(
1065 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001066 ItemInfoFilter filter = new ItemInfoFilter() {
1067 @Override
1068 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1069 return cn.getPackageName().equals(pn) && info.user.equals(user);
1070 }
1071 };
Sunny Goyal34942622014-08-29 17:20:55 -07001072 return filterItemInfos(sBgItemsIdMap.values(), filter);
1073 }
1074
1075 /**
1076 * Removes all the items from the database corresponding to the specified package.
1077 */
1078 static void deletePackageFromDatabase(Context context, final String pn,
1079 final UserHandleCompat user) {
1080 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001081 }
1082
1083 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001084 * Removes the specified item from the database
1085 * @param context
1086 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001087 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001088 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001089 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1090 items.add(item);
1091 deleteItemsFromDatabase(context, items);
1092 }
1093
1094 /**
1095 * Removes the specified items from the database
1096 * @param context
1097 * @param item
1098 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001099 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001100 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001101
Michael Jurka83df1882011-08-31 20:59:26 -07001102 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001103 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001104 for (ItemInfo item : items) {
1105 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1106 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001107
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001108 // Lock on mBgLock *after* the db operation
1109 synchronized (sBgLock) {
1110 switch (item.itemType) {
1111 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1112 sBgFolders.remove(item.id);
1113 for (ItemInfo info: sBgItemsIdMap.values()) {
1114 if (info.container == item.id) {
1115 // We are deleting a folder which still contains items that
1116 // think they are contained by that folder.
1117 String msg = "deleting a folder (" + item + ") which still " +
1118 "contains items (" + info + ")";
1119 Log.e(TAG, msg);
1120 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001121 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001122 sBgWorkspaceItems.remove(item);
1123 break;
1124 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1125 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1126 sBgWorkspaceItems.remove(item);
1127 break;
1128 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1129 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1130 break;
1131 }
1132 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001133 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001134 }
1135 }
Michael Jurka83df1882011-08-31 20:59:26 -07001136 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001137 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001138 }
1139
1140 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001141 * Update the order of the workspace screens in the database. The array list contains
1142 * a list of screen ids in the order that they should appear.
1143 */
Winson Chungc9168342013-06-26 14:54:55 -07001144 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001145 // Log to disk
1146 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1147 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1148
Winson Chung64359a52013-07-08 17:17:08 -07001149 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001150 final ContentResolver cr = context.getContentResolver();
1151 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1152
1153 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001154 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001155 while (iter.hasNext()) {
1156 long id = iter.next();
1157 if (id < 0) {
1158 iter.remove();
1159 }
1160 }
1161
1162 Runnable r = new Runnable() {
1163 @Override
1164 public void run() {
Yura085c8532014-02-11 15:15:29 +00001165 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001167 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001168 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 for (int i = 0; i < count; i++) {
1170 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001171 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001172 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1173 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001174 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001175 }
Yura085c8532014-02-11 15:15:29 +00001176
1177 try {
1178 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1179 } catch (Exception ex) {
1180 throw new RuntimeException(ex);
1181 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001182
Winson Chungba9c37f2013-08-30 14:11:37 -07001183 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001184 sBgWorkspaceScreens.clear();
1185 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001186 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001187 }
1188 };
1189 runOnWorkerThread(r);
1190 }
1191
1192 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001193 * Remove the contents of the specified folder from the database
1194 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001195 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001196 final ContentResolver cr = context.getContentResolver();
1197
Michael Jurkac9d95c52011-08-29 14:03:34 -07001198 Runnable r = new Runnable() {
1199 public void run() {
1200 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001201 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001202 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 sBgItemsIdMap.remove(info.id);
1204 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 sBgWorkspaceItems.remove(info);
1206 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001207
Michael Jurkac9d95c52011-08-29 14:03:34 -07001208 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1209 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001210 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001211 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001212 for (ItemInfo childInfo : info.contents) {
1213 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001214 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001215 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001216 }
1217 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001218 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001219 }
1220
1221 /**
1222 * Set this as the current Launcher activity object for the loader.
1223 */
1224 public void initialize(Callbacks callbacks) {
1225 synchronized (mLock) {
1226 mCallbacks = new WeakReference<Callbacks>(callbacks);
1227 }
1228 }
1229
Kenny Guyed131872014-04-30 03:02:21 +01001230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_UPDATE;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001239 int op = PackageUpdatedTask.OP_REMOVE;
1240 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1241 user));
1242 }
1243
1244 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001245 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001246 int op = PackageUpdatedTask.OP_ADD;
1247 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1248 user));
1249 }
1250
1251 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001252 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001253 boolean replacing) {
1254 if (!replacing) {
1255 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1256 user));
1257 if (mAppsCanBeOnRemoveableStorage) {
1258 // Only rebind if we support removable storage. It catches the
1259 // case where
1260 // apps on the external sd card need to be reloaded
1261 startLoaderFromBackground();
1262 }
1263 } else {
1264 // If we are replacing then just update the packages in the list
1265 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1266 packageNames, user));
1267 }
1268 }
1269
1270 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001271 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001272 boolean replacing) {
1273 if (!replacing) {
1274 enqueuePackageUpdated(new PackageUpdatedTask(
1275 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1276 user));
1277 }
Kenny Guyed131872014-04-30 03:02:21 +01001278 }
1279
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001280 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001281 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1282 * ACTION_PACKAGE_CHANGED.
1283 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001284 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001285 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001286 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001287
Joe Onorato36115782010-06-17 13:28:48 -04001288 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001289 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001290 // If we have changed locale we need to clear out the labels in all apps/workspace.
1291 forceReload();
1292 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1293 // Check if configuration change was an mcc/mnc change which would affect app resources
1294 // and we would need to clear out the labels in all apps/workspace. Same handling as
1295 // above for ACTION_LOCALE_CHANGED
1296 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001297 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001298 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001299 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001300 forceReload();
1301 }
1302 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001303 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001304 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1305 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001306 Callbacks callbacks = getCallback();
1307 if (callbacks != null) {
1308 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001309 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001310 }
1311 }
1312
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001313 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001314 resetLoadedState(true, true);
1315
Reena Lee93f824a2011-09-23 17:20:28 -07001316 // Do this here because if the launcher activity is running it will be restarted.
1317 // If it's not running startLoaderFromBackground will merely tell it that it needs
1318 // to reload.
1319 startLoaderFromBackground();
1320 }
1321
Winson Chungf0c6ae02012-03-21 16:10:31 -07001322 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1323 synchronized (mLock) {
1324 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1325 // mWorkspaceLoaded to true later
1326 stopLoaderLocked();
1327 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1328 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1329 }
1330 }
1331
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001332 /**
1333 * When the launcher is in the background, it's possible for it to miss paired
1334 * configuration changes. So whenever we trigger the loader from the background
1335 * tell the launcher that it needs to re-run the loader when it comes back instead
1336 * of doing it now.
1337 */
1338 public void startLoaderFromBackground() {
1339 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001340 Callbacks callbacks = getCallback();
1341 if (callbacks != null) {
1342 // Only actually run the loader if they're not paused.
1343 if (!callbacks.setLoadOnResume()) {
1344 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001345 }
1346 }
1347 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001348 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001349 }
Joe Onorato36115782010-06-17 13:28:48 -04001350 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001351
Reena Lee93f824a2011-09-23 17:20:28 -07001352 // If there is already a loader task running, tell it to stop.
1353 // returns true if isLaunching() was true on the old task
1354 private boolean stopLoaderLocked() {
1355 boolean isLaunching = false;
1356 LoaderTask oldTask = mLoaderTask;
1357 if (oldTask != null) {
1358 if (oldTask.isLaunching()) {
1359 isLaunching = true;
1360 }
1361 oldTask.stopLocked();
1362 }
1363 return isLaunching;
1364 }
1365
Adam Cohen1a85c582014-09-30 09:48:49 -07001366 public boolean isCurrentCallbacks(Callbacks callbacks) {
1367 return (mCallbacks != null && mCallbacks.get() == callbacks);
1368 }
1369
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001370 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001371 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1372 }
1373
1374 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001375 synchronized (mLock) {
1376 if (DEBUG_LOADERS) {
1377 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1378 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001379
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001380 // Clear any deferred bind-runnables from the synchronized load process
1381 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001382 synchronized (mDeferredBindRunnables) {
1383 mDeferredBindRunnables.clear();
1384 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001385
Joe Onorato36115782010-06-17 13:28:48 -04001386 // Don't bother to start the thread if we know it's not going to do anything
1387 if (mCallbacks != null && mCallbacks.get() != null) {
1388 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001389 // also, don't downgrade isLaunching if we're already running
1390 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001391 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001392 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1393 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001394 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1395 } else {
1396 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1397 sWorker.post(mLoaderTask);
1398 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001399 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001400 }
1401 }
1402
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001403 void bindRemainingSynchronousPages() {
1404 // Post the remaining side pages to be loaded
1405 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001406 Runnable[] deferredBindRunnables = null;
1407 synchronized (mDeferredBindRunnables) {
1408 deferredBindRunnables = mDeferredBindRunnables.toArray(
1409 new Runnable[mDeferredBindRunnables.size()]);
1410 mDeferredBindRunnables.clear();
1411 }
1412 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001413 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001414 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001415 }
1416 }
1417
Joe Onorato36115782010-06-17 13:28:48 -04001418 public void stopLoader() {
1419 synchronized (mLock) {
1420 if (mLoaderTask != null) {
1421 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001422 }
1423 }
Joe Onorato36115782010-06-17 13:28:48 -04001424 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001425
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001426 /**
1427 * Loads the workspace screen ids in an ordered list.
1428 */
Adam Cohen091440a2015-03-18 14:16:05 -07001429 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001430 final ContentResolver contentResolver = context.getContentResolver();
1431 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001432
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001433 // Get screens ordered by rank.
1434 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1435 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1436 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001437 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001438 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001439 while (sc.moveToNext()) {
1440 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001441 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001442 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001443 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1444 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001445 }
1446 }
1447 } finally {
1448 sc.close();
1449 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001450 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001451 }
1452
Michael Jurkac57b7a82011-08-09 22:02:20 -07001453 public boolean isAllAppsLoaded() {
1454 return mAllAppsLoaded;
1455 }
1456
Winson Chung36a62fe2012-05-06 18:04:42 -07001457 boolean isLoadingWorkspace() {
1458 synchronized (mLock) {
1459 if (mLoaderTask != null) {
1460 return mLoaderTask.isLoadingWorkspace();
1461 }
1462 }
1463 return false;
1464 }
1465
Joe Onorato36115782010-06-17 13:28:48 -04001466 /**
1467 * Runnable for the thread that loads the contents of the launcher:
1468 * - workspace icons
1469 * - widgets
1470 * - all apps icons
1471 */
1472 private class LoaderTask implements Runnable {
1473 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001474 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001475 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001476 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001477 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001478 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001479
Dan Sandlerd5024042014-01-09 15:01:33 -05001480 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001481 mContext = context;
1482 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001483 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001484 }
1485
Joe Onorato36115782010-06-17 13:28:48 -04001486 boolean isLaunching() {
1487 return mIsLaunching;
1488 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001489
Winson Chung36a62fe2012-05-06 18:04:42 -07001490 boolean isLoadingWorkspace() {
1491 return mIsLoadingAndBindingWorkspace;
1492 }
1493
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001494 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001495 mIsLoadingAndBindingWorkspace = true;
1496
Joe Onorato36115782010-06-17 13:28:48 -04001497 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001498 if (DEBUG_LOADERS) {
1499 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001500 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001501
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001502 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001503 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001504 synchronized (LoaderTask.this) {
1505 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001506 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001507 }
1508 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001509 }
1510 }
1511
Joe Onorato36115782010-06-17 13:28:48 -04001512 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001513 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001514 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001515
Joe Onorato36115782010-06-17 13:28:48 -04001516 private void waitForIdle() {
1517 // Wait until the either we're stopped or the other threads are done.
1518 // This way we don't start loading all apps until the workspace has settled
1519 // down.
1520 synchronized (LoaderTask.this) {
1521 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001522
Joe Onorato36115782010-06-17 13:28:48 -04001523 mHandler.postIdle(new Runnable() {
1524 public void run() {
1525 synchronized (LoaderTask.this) {
1526 mLoadAndBindStepFinished = true;
1527 if (DEBUG_LOADERS) {
1528 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001529 }
Joe Onorato36115782010-06-17 13:28:48 -04001530 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001532 }
Joe Onorato36115782010-06-17 13:28:48 -04001533 });
1534
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001535 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001536 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001537 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1538 // wait no longer than 1sec at a time
1539 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001540 } catch (InterruptedException ex) {
1541 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001542 }
1543 }
Joe Onorato36115782010-06-17 13:28:48 -04001544 if (DEBUG_LOADERS) {
1545 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001546 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001547 + "ms for previous step to finish binding");
1548 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001549 }
Joe Onorato36115782010-06-17 13:28:48 -04001550 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001551
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001552 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001553 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001554 // Ensure that we have a valid page index to load synchronously
1555 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1556 "valid page index");
1557 }
1558 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1559 // Ensure that we don't try and bind a specified page when the pages have not been
1560 // loaded already (we should load everything asynchronously in that case)
1561 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1562 }
1563 synchronized (mLock) {
1564 if (mIsLoaderTaskRunning) {
1565 // Ensure that we are never running the background loading at this point since
1566 // we also touch the background collections
1567 throw new RuntimeException("Error! Background loading is already running");
1568 }
1569 }
1570
1571 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1572 // data structures, we can't allow any other thread to touch that data, but because
1573 // this call is synchronous, we can get away with not locking).
1574
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001575 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001576 // operations from the previous activity. We need to ensure that all queued operations
1577 // are executed before any synchronous binding work is done.
1578 mHandler.flush();
1579
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001580 // Divide the set of loaded items into those that we are binding synchronously, and
1581 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001582 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1584 // arise from that.
1585 onlyBindAllApps();
1586 }
1587
Joe Onorato36115782010-06-17 13:28:48 -04001588 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001589 synchronized (mLock) {
1590 mIsLoaderTaskRunning = true;
1591 }
Joe Onorato36115782010-06-17 13:28:48 -04001592 // Optimize for end-user experience: if the Launcher is up and // running with the
1593 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1594 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001595 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001596 // Elevate priority when Home launches for the first time to avoid
1597 // starving at boot time. Staring at a blank home is not cool.
1598 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001599 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1600 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001601 android.os.Process.setThreadPriority(mIsLaunching
1602 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1603 }
Winson Chung64359a52013-07-08 17:17:08 -07001604 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001605 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001606
Joe Onorato36115782010-06-17 13:28:48 -04001607 if (mStopped) {
1608 break keep_running;
1609 }
1610
1611 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1612 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001613 synchronized (mLock) {
1614 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001615 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001616 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1617 }
1618 }
Joe Onorato36115782010-06-17 13:28:48 -04001619 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001620
1621 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001622 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1623 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001624
Sunny Goyal5b0e6692015-03-19 14:31:19 -07001625 // Remove entries for packages which changed while the launcher was dead.
1626 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews();
1627
Winson Chung7ed37742011-09-08 15:45:51 -07001628 // Restore the default thread priority after we are done loading items
1629 synchronized (mLock) {
1630 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1631 }
Joe Onorato36115782010-06-17 13:28:48 -04001632 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001633
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
1684 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001685 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001686 LauncherAppState app = LauncherAppState.getInstance();
1687 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001688 final int countX = (int) grid.numColumns;
1689 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001690
Adam Cohendcd297f2013-06-18 13:13:40 -07001691 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001692 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001693 // Return early if we detect that an item is under the hotseat button
1694 if (mCallbacks == null ||
1695 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001696 Log.e(TAG, "Error loading shortcut into hotseat " + item
1697 + " into position (" + item.screenId + ":" + item.cellX + ","
1698 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001699 return false;
1700 }
1701
Dan Sandler295ae182013-12-10 16:05:47 -05001702 final ItemInfo[][] hotseatItems =
1703 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1704
Adam Cohenae4409d2013-11-26 10:34:59 -08001705 if (item.screenId >= grid.numHotseatIcons) {
1706 Log.e(TAG, "Error loading shortcut " + item
1707 + " into hotseat position " + item.screenId
1708 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1709 + ")");
1710 return false;
1711 }
1712
Dan Sandler295ae182013-12-10 16:05:47 -05001713 if (hotseatItems != null) {
1714 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001715 Log.e(TAG, "Error loading shortcut into hotseat " + item
1716 + " into position (" + item.screenId + ":" + item.cellX + ","
1717 + item.cellY + ") occupied by "
1718 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1719 [(int) item.screenId][0]);
1720 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001721 } else {
1722 hotseatItems[(int) item.screenId][0] = item;
1723 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001724 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001725 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001726 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001727 items[(int) item.screenId][0] = item;
1728 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001729 return true;
1730 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001731 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1732 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001733 return true;
1734 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001735
Adam Cohendcd297f2013-06-18 13:13:40 -07001736 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001737 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001738 occupied.put(item.screenId, items);
1739 }
1740
Dan Sandler295ae182013-12-10 16:05:47 -05001741 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001742 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1743 item.cellX < 0 || item.cellY < 0 ||
1744 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1745 Log.e(TAG, "Error loading shortcut " + item
1746 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1747 + item.cellX + "," + item.cellY
1748 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1749 return false;
1750 }
1751
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001752 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001753 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1754 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001755 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001756 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001757 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001758 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001759 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001760 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001761 return false;
1762 }
1763 }
1764 }
1765 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1766 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001767 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001768 }
1769 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001770
Joe Onorato36115782010-06-17 13:28:48 -04001771 return true;
1772 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001773
Winson Chungba9c37f2013-08-30 14:11:37 -07001774 /** Clears all the sBg data structures */
1775 private void clearSBgDataStructures() {
1776 synchronized (sBgLock) {
1777 sBgWorkspaceItems.clear();
1778 sBgAppWidgets.clear();
1779 sBgFolders.clear();
1780 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001781 sBgWorkspaceScreens.clear();
1782 }
1783 }
1784
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001785 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001786 // Log to disk
1787 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1788
Joe Onorato36115782010-06-17 13:28:48 -04001789 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001790
Joe Onorato36115782010-06-17 13:28:48 -04001791 final Context context = mContext;
1792 final ContentResolver contentResolver = context.getContentResolver();
1793 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001794 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001795 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1796 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001797 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001798
Winson Chung892c74d2013-08-22 16:15:50 -07001799 LauncherAppState app = LauncherAppState.getInstance();
1800 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1801 int countX = (int) grid.numColumns;
1802 int countY = (int) grid.numRows;
1803
Dan Sandlerd5024042014-01-09 15:01:33 -05001804 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1805 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1806 LauncherAppState.getLauncherProvider().deleteDatabase();
1807 }
1808
1809 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1810 // append the user's Launcher2 shortcuts
1811 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1812 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1813 } else {
1814 // Make sure the default workspace is loaded
1815 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001816 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001817 }
Adam Cohene25af792013-06-06 23:08:25 -07001818
Winson Chung2abf94d2012-07-18 18:16:38 -07001819 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001820 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001821 final HashSet<String> installingPkgs = PackageInstallerCompat
1822 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001823
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001824 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001825 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001826 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001827 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001828 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001829
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001830 // +1 for the hotseat (it can be larger than the workspace)
1831 // Load workspace in reverse order to ensure that latest items are loaded first (and
1832 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001833 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001834
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001835 try {
1836 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1837 final int intentIndex = c.getColumnIndexOrThrow
1838 (LauncherSettings.Favorites.INTENT);
1839 final int titleIndex = c.getColumnIndexOrThrow
1840 (LauncherSettings.Favorites.TITLE);
1841 final int iconTypeIndex = c.getColumnIndexOrThrow(
1842 LauncherSettings.Favorites.ICON_TYPE);
1843 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1844 final int iconPackageIndex = c.getColumnIndexOrThrow(
1845 LauncherSettings.Favorites.ICON_PACKAGE);
1846 final int iconResourceIndex = c.getColumnIndexOrThrow(
1847 LauncherSettings.Favorites.ICON_RESOURCE);
1848 final int containerIndex = c.getColumnIndexOrThrow(
1849 LauncherSettings.Favorites.CONTAINER);
1850 final int itemTypeIndex = c.getColumnIndexOrThrow(
1851 LauncherSettings.Favorites.ITEM_TYPE);
1852 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1853 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001854 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1855 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001856 final int screenIndex = c.getColumnIndexOrThrow(
1857 LauncherSettings.Favorites.SCREEN);
1858 final int cellXIndex = c.getColumnIndexOrThrow
1859 (LauncherSettings.Favorites.CELLX);
1860 final int cellYIndex = c.getColumnIndexOrThrow
1861 (LauncherSettings.Favorites.CELLY);
1862 final int spanXIndex = c.getColumnIndexOrThrow
1863 (LauncherSettings.Favorites.SPANX);
1864 final int spanYIndex = c.getColumnIndexOrThrow(
1865 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001866 final int rankIndex = c.getColumnIndexOrThrow(
1867 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001868 final int restoredIndex = c.getColumnIndexOrThrow(
1869 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001870 final int profileIdIndex = c.getColumnIndexOrThrow(
1871 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001872 final int optionsIndex = c.getColumnIndexOrThrow(
1873 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001874
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001875 ShortcutInfo info;
1876 String intentDescription;
1877 LauncherAppWidgetInfo appWidgetInfo;
1878 int container;
1879 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001880 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001881 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001882 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 while (!mStopped && c.moveToNext()) {
1885 try {
1886 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001887 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001888 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001889
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001890 switch (itemType) {
1891 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1892 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001893 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001894 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001895 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001896 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001897 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001898 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001899 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001900 if (user == null) {
1901 // User has been deleted remove the item.
1902 itemsToRemove.add(id);
1903 continue;
1904 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001905 try {
1906 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001907 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001908 if (cn != null && cn.getPackageName() != null) {
1909 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1910 cn.getPackageName(), user);
1911 boolean validComponent = validPkg &&
1912 launcherApps.isActivityEnabledForProfile(cn, user);
1913
1914 if (validComponent) {
1915 if (restored) {
1916 // no special handling necessary for this item
1917 restoredRows.add(id);
1918 restored = false;
1919 }
1920 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001921 intent = null;
1922 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1923 // We allow auto install apps to have their intent
1924 // updated after an install.
1925 intent = manager.getLaunchIntentForPackage(
1926 cn.getPackageName());
1927 if (intent != null) {
1928 ContentValues values = new ContentValues();
1929 values.put(LauncherSettings.Favorites.INTENT,
1930 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001931 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001932 }
1933 }
1934
1935 if (intent == null) {
1936 // The app is installed but the component is no
1937 // longer available.
1938 Launcher.addDumpLog(TAG,
1939 "Invalid component removed: " + cn, true);
1940 itemsToRemove.add(id);
1941 continue;
1942 } else {
1943 // no special handling necessary for this item
1944 restoredRows.add(id);
1945 restored = false;
1946 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001947 } else if (restored) {
1948 // Package is not yet available but might be
1949 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001950 Launcher.addDumpLog(TAG,
1951 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001952
1953 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1954 // Restore has started once.
1955 } else if (installingPkgs.contains(cn.getPackageName())) {
1956 // App restore has started. Update the flag
1957 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1958 ContentValues values = new ContentValues();
1959 values.put(LauncherSettings.Favorites.RESTORED,
1960 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001961 updateItem(id, values);
1962 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1963 // This is a common app. Try to replace this.
1964 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1965 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1966 if (parser.findDefaultApp()) {
1967 // Default app found. Replace it.
1968 intent = parser.parsedIntent;
1969 cn = intent.getComponent();
1970 ContentValues values = parser.parsedValues;
1971 values.put(LauncherSettings.Favorites.RESTORED, 0);
1972 updateItem(id, values);
1973 restored = false;
1974 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001975
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001976 } else if (REMOVE_UNRESTORED_ICONS) {
1977 Launcher.addDumpLog(TAG,
1978 "Unrestored package removed: " + cn, true);
1979 itemsToRemove.add(id);
1980 continue;
1981 }
Sunny Goyal94485362014-09-18 16:13:58 -07001982 } else if (REMOVE_UNRESTORED_ICONS) {
1983 Launcher.addDumpLog(TAG,
1984 "Unrestored package removed: " + cn, true);
1985 itemsToRemove.add(id);
1986 continue;
1987 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001988 } else if (launcherApps.isAppEnabled(
1989 manager, cn.getPackageName(),
1990 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1991 // Package is present but not available.
1992 allowMissingTarget = true;
1993 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1994 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001995 // SdCard is not ready yet. Package might get available,
1996 // once it is ready.
1997 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1998 + " (check again later)", true);
1999 HashSet<String> pkgs = sPendingPackages.get(user);
2000 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002001 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002002 sPendingPackages.put(user, pkgs);
2003 }
2004 pkgs.add(cn.getPackageName());
2005 allowMissingTarget = true;
2006 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002007
2008 } else {
2009 // Do not wait for external media load anymore.
2010 // Log the invalid package, and remove it
2011 Launcher.addDumpLog(TAG,
2012 "Invalid package removed: " + cn, true);
2013 itemsToRemove.add(id);
2014 continue;
Winson Chungee055712013-07-30 14:46:24 -07002015 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002016 } else if (cn == null) {
2017 // For shortcuts with no component, keep them as they are
2018 restoredRows.add(id);
2019 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002020 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002021 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002022 Launcher.addDumpLog(TAG,
2023 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002024 continue;
2025 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002026
Sunny Goyal34b65272015-03-11 16:56:52 -07002027 container = c.getInt(containerIndex);
2028 boolean useLowResIcon = container >= 0 &&
2029 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2030
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002031 if (itemReplaced) {
2032 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002033 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002034 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002035 } else {
2036 // Don't replace items for other profiles.
2037 itemsToRemove.add(id);
2038 continue;
2039 }
2040 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002041 if (user.equals(UserHandleCompat.myUserHandle())) {
2042 Launcher.addDumpLog(TAG,
2043 "constructing info for partially restored package",
2044 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002045 info = getRestoredItemInfo(c, titleIndex, intent,
2046 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002047 intent = getRestoredItemIntent(c, context, intent);
2048 } else {
2049 // Don't restore items for other profiles.
2050 itemsToRemove.add(id);
2051 continue;
2052 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002053 } else if (itemType ==
2054 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002055 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002056 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002057 } else {
2058 info = getShortcutInfo(c, context, iconTypeIndex,
2059 iconPackageIndex, iconResourceIndex, iconIndex,
2060 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002061
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002062 // App shortcuts that used to be automatically added to Launcher
2063 // didn't always have the correct intent flags set, so do that
2064 // here
2065 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002066 intent.getCategories() != null &&
2067 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002068 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 intent.addFlags(
2070 Intent.FLAG_ACTIVITY_NEW_TASK |
2071 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2072 }
Michael Jurka96879562012-03-22 05:54:33 -07002073 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002074
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002075 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002076 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002078 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002079 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002080 info.cellX = c.getInt(cellXIndex);
2081 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002082 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002083 info.spanX = 1;
2084 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002085 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002086 info.isDisabled = disabledState;
2087 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2088 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2089 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002090
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002091 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002092 if (!checkItemPlacement(occupied, info)) {
2093 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002094 break;
2095 }
2096
2097 switch (container) {
2098 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2099 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2100 sBgWorkspaceItems.add(info);
2101 break;
2102 default:
2103 // Item is in a user folder
2104 FolderInfo folderInfo =
2105 findOrMakeFolder(sBgFolders, container);
2106 folderInfo.add(info);
2107 break;
2108 }
2109 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002110 } else {
2111 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002112 }
2113 break;
2114
2115 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2116 id = c.getLong(idIndex);
2117 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2118
2119 folderInfo.title = c.getString(titleIndex);
2120 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002121 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002122 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002123 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002124 folderInfo.cellX = c.getInt(cellXIndex);
2125 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002126 folderInfo.spanX = 1;
2127 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002128 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002129
Daniel Sandler8802e962010-05-26 16:28:16 -04002130 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002131 if (!checkItemPlacement(occupied, folderInfo)) {
2132 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002133 break;
2134 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002135
Joe Onorato9c1289c2009-08-17 11:03:03 -04002136 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002137 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2138 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2139 sBgWorkspaceItems.add(folderInfo);
2140 break;
Joe Onorato36115782010-06-17 13:28:48 -04002141 }
Joe Onorato17a89222011-02-08 17:26:11 -08002142
Chris Wrenf4d08112014-01-16 18:13:56 -05002143 if (restored) {
2144 // no special handling required for restored folders
2145 restoredRows.add(id);
2146 }
2147
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2149 sBgFolders.put(folderInfo.id, folderInfo);
2150 break;
2151
2152 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002153 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002155 boolean customWidget = itemType ==
2156 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2157
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002158 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002159 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002160 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002161 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002162 final ComponentName component =
2163 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002164
Sunny Goyal651077b2014-06-30 14:15:31 -07002165 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002166 final boolean isIdValid = (restoreStatus &
2167 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002168
Sunny Goyalff572272014-07-23 13:58:07 -07002169 final boolean wasProviderReady = (restoreStatus &
2170 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002171
Adam Cohen59400422014-03-05 18:07:04 -08002172 final LauncherAppWidgetProviderInfo provider =
2173 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002174 ComponentName.unflattenFromString(savedProvider),
2175 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002176
2177 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002178 if (!isSafeMode && !customWidget &&
2179 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002180 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002181 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002182
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002183 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002184 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002185 itemsToRemove.add(id);
2186 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002187 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002188 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2189 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002190
2191 if (!customWidget) {
2192 int[] minSpan =
2193 Launcher.getMinSpanForWidget(context, provider);
2194 appWidgetInfo.minSpanX = minSpan[0];
2195 appWidgetInfo.minSpanY = minSpan[1];
2196 }
Sunny Goyalff572272014-07-23 13:58:07 -07002197
2198 int status = restoreStatus;
2199 if (!wasProviderReady) {
2200 // If provider was not previously ready, update the
2201 // status and UI flag.
2202
2203 // Id would be valid only if the widget restore broadcast was received.
2204 if (isIdValid) {
2205 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2206 } else {
2207 status &= ~LauncherAppWidgetInfo
2208 .FLAG_PROVIDER_NOT_READY;
2209 }
2210 }
2211 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002212 } else {
2213 Log.v(TAG, "Widget restore pending id=" + id
2214 + " appWidgetId=" + appWidgetId
2215 + " status =" + restoreStatus);
2216 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002217 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002218 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002219
2220 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2221 // Restore has started once.
2222 } else if (installingPkgs.contains(component.getPackageName())) {
2223 // App restore has started. Update the flag
2224 appWidgetInfo.restoreStatus |=
2225 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002226 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002227 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002228 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002229 itemsToRemove.add(id);
2230 continue;
2231 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002232 }
Sunny Goyalff572272014-07-23 13:58:07 -07002233
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002234 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002235 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002236 appWidgetInfo.cellX = c.getInt(cellXIndex);
2237 appWidgetInfo.cellY = c.getInt(cellYIndex);
2238 appWidgetInfo.spanX = c.getInt(spanXIndex);
2239 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002240
Adam Cohen59400422014-03-05 18:07:04 -08002241 if (!customWidget) {
2242 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2243 appWidgetInfo.minSpanX = minSpan[0];
2244 appWidgetInfo.minSpanY = minSpan[1];
2245 }
2246
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247 container = c.getInt(containerIndex);
2248 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2249 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2250 Log.e(TAG, "Widget found where container != " +
2251 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2252 continue;
2253 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002254
Adam Cohene25af792013-06-06 23:08:25 -07002255 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002256 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002257 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2258 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002259 break;
2260 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002261
Adam Cohen59400422014-03-05 18:07:04 -08002262 if (!customWidget) {
2263 String providerName =
2264 appWidgetInfo.providerName.flattenToString();
2265 if (!providerName.equals(savedProvider) ||
2266 (appWidgetInfo.restoreStatus != restoreStatus)) {
2267 ContentValues values = new ContentValues();
2268 values.put(
2269 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2270 providerName);
2271 values.put(LauncherSettings.Favorites.RESTORED,
2272 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002273 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002274 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002275 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002276 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2277 sBgAppWidgets.add(appWidgetInfo);
2278 }
Joe Onorato36115782010-06-17 13:28:48 -04002279 break;
2280 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002281 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002282 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002283 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002284 }
2285 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002286 if (c != null) {
2287 c.close();
2288 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002289 }
2290
Winson Chungba9c37f2013-08-30 14:11:37 -07002291 // Break early if we've stopped loading
2292 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002293 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002294 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002295 }
2296
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002297 if (itemsToRemove.size() > 0) {
2298 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002299 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002300 // Remove dead items
2301 for (long id : itemsToRemove) {
2302 if (DEBUG_LOADERS) {
2303 Log.d(TAG, "Removed id = " + id);
2304 }
2305 // Don't notify content observers
2306 try {
2307 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2308 null, null);
2309 } catch (RemoteException e) {
2310 Log.w(TAG, "Could not remove id = " + id);
2311 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002312 }
2313 }
2314
Chris Wrenf4d08112014-01-16 18:13:56 -05002315 if (restoredRows.size() > 0) {
2316 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002317 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002318 // Update restored items that no longer require special handling
2319 try {
2320 StringBuilder selectionBuilder = new StringBuilder();
2321 selectionBuilder.append(LauncherSettings.Favorites._ID);
2322 selectionBuilder.append(" IN (");
2323 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2324 selectionBuilder.append(")");
2325 ContentValues values = new ContentValues();
2326 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002327 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002328 values, selectionBuilder.toString(), null);
2329 } catch (RemoteException e) {
2330 Log.w(TAG, "Could not update restored rows");
2331 }
2332 }
2333
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002334 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2335 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002336 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002337 null, sWorker);
2338 }
2339
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002340 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2341 // Log to disk
2342 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2343 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002344
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002345 // Remove any empty screens
2346 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2347 for (ItemInfo item: sBgItemsIdMap.values()) {
2348 long screenId = item.screenId;
2349 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2350 unusedScreens.contains(screenId)) {
2351 unusedScreens.remove(screenId);
2352 }
2353 }
2354
2355 // If there are any empty screens remove them, and update.
2356 if (unusedScreens.size() != 0) {
2357 // Log to disk
2358 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2359 TextUtils.join(", ", unusedScreens), true);
2360
2361 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002362 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002363 }
2364
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002365 if (DEBUG_LOADERS) {
2366 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2367 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002368 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002369 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002370 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002371
Daniel Sandler566da102013-06-25 23:43:45 -04002372 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002373 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002374 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002375 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002376 line += " | ";
2377 }
Winson Chung892c74d2013-08-22 16:15:50 -07002378 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002379 ItemInfo[][] screen = occupied.get(screenId);
2380 if (x < screen.length && y < screen[x].length) {
2381 line += (screen[x][y] != null) ? "#" : ".";
2382 } else {
2383 line += "!";
2384 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002385 }
Joe Onorato36115782010-06-17 13:28:48 -04002386 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002387 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002388 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002389 }
Joe Onorato36115782010-06-17 13:28:48 -04002390 }
Adam Cohene25af792013-06-06 23:08:25 -07002391 }
2392
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002393 /**
2394 * Partially updates the item without any notification. Must be called on the worker thread.
2395 */
2396 private void updateItem(long itemId, ContentValues update) {
2397 mContext.getContentResolver().update(
2398 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2399 update,
2400 BaseColumns._ID + "= ?",
2401 new String[]{Long.toString(itemId)});
2402 }
2403
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002404 /** Filters the set of items who are directly or indirectly (via another container) on the
2405 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002406 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002407 ArrayList<ItemInfo> allWorkspaceItems,
2408 ArrayList<ItemInfo> currentScreenItems,
2409 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002410 // Purge any null ItemInfos
2411 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2412 while (iter.hasNext()) {
2413 ItemInfo i = iter.next();
2414 if (i == null) {
2415 iter.remove();
2416 }
2417 }
2418
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002419 // Order the set of items by their containers first, this allows use to walk through the
2420 // list sequentially, build up a list of containers that are in the specified screen,
2421 // as well as all items in those containers.
2422 Set<Long> itemsOnScreen = new HashSet<Long>();
2423 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2424 @Override
2425 public int compare(ItemInfo lhs, ItemInfo rhs) {
2426 return (int) (lhs.container - rhs.container);
2427 }
2428 });
2429 for (ItemInfo info : allWorkspaceItems) {
2430 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002431 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002432 currentScreenItems.add(info);
2433 itemsOnScreen.add(info.id);
2434 } else {
2435 otherScreenItems.add(info);
2436 }
2437 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2438 currentScreenItems.add(info);
2439 itemsOnScreen.add(info.id);
2440 } else {
2441 if (itemsOnScreen.contains(info.container)) {
2442 currentScreenItems.add(info);
2443 itemsOnScreen.add(info.id);
2444 } else {
2445 otherScreenItems.add(info);
2446 }
2447 }
2448 }
2449 }
2450
2451 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002452 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453 ArrayList<LauncherAppWidgetInfo> appWidgets,
2454 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2455 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456
2457 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002458 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002460 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002461 currentScreenWidgets.add(widget);
2462 } else {
2463 otherScreenWidgets.add(widget);
2464 }
2465 }
2466 }
2467
2468 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002469 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002470 HashMap<Long, ItemInfo> itemsIdMap,
2471 HashMap<Long, FolderInfo> folders,
2472 HashMap<Long, FolderInfo> currentScreenFolders,
2473 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474
2475 for (long id : folders.keySet()) {
2476 ItemInfo info = itemsIdMap.get(id);
2477 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002478 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002479 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002480 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002481 currentScreenFolders.put(id, folder);
2482 } else {
2483 otherScreenFolders.put(id, folder);
2484 }
2485 }
2486 }
2487
2488 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2489 * right) */
2490 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002491 final LauncherAppState app = LauncherAppState.getInstance();
2492 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002493 // XXX: review this
2494 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002495 @Override
2496 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002497 int cellCountX = (int) grid.numColumns;
2498 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002499 int screenOffset = cellCountX * cellCountY;
2500 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002501 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002502 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002503 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002504 rhs.cellY * cellCountX + rhs.cellX);
2505 return (int) (lr - rr);
2506 }
2507 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002508 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002509
Adam Cohendcd297f2013-06-18 13:13:40 -07002510 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2511 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002512 final Runnable r = new Runnable() {
2513 @Override
2514 public void run() {
2515 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2516 if (callbacks != null) {
2517 callbacks.bindScreens(orderedScreens);
2518 }
2519 }
2520 };
2521 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2522 }
2523
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002524 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2525 final ArrayList<ItemInfo> workspaceItems,
2526 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2527 final HashMap<Long, FolderInfo> folders,
2528 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002529
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 final boolean postOnMainThread = (deferredBindRunnables != null);
2531
2532 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002533 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002534 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002535 final int start = i;
2536 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002537 final Runnable r = new Runnable() {
2538 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002539 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002540 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002541 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002542 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2543 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002544 }
2545 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002546 };
2547 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002548 synchronized (deferredBindRunnables) {
2549 deferredBindRunnables.add(r);
2550 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002551 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002552 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553 }
Joe Onorato36115782010-06-17 13:28:48 -04002554 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002555
2556 // Bind the folders
2557 if (!folders.isEmpty()) {
2558 final Runnable r = new Runnable() {
2559 public void run() {
2560 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2561 if (callbacks != null) {
2562 callbacks.bindFolders(folders);
2563 }
2564 }
2565 };
2566 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002567 synchronized (deferredBindRunnables) {
2568 deferredBindRunnables.add(r);
2569 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002571 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002572 }
2573 }
2574
2575 // Bind the widgets, one at a time
2576 N = appWidgets.size();
2577 for (int i = 0; i < N; i++) {
2578 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2579 final Runnable r = new Runnable() {
2580 public void run() {
2581 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2582 if (callbacks != null) {
2583 callbacks.bindAppWidget(widget);
2584 }
2585 }
2586 };
2587 if (postOnMainThread) {
2588 deferredBindRunnables.add(r);
2589 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002590 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 }
2592 }
2593 }
2594
2595 /**
2596 * Binds all loaded data to actual views on the main thread.
2597 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002598 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002599 final long t = SystemClock.uptimeMillis();
2600 Runnable r;
2601
2602 // Don't use these two variables in any of the callback runnables.
2603 // Otherwise we hold a reference to them.
2604 final Callbacks oldCallbacks = mCallbacks.get();
2605 if (oldCallbacks == null) {
2606 // This launcher has exited and nobody bothered to tell us. Just bail.
2607 Log.w(TAG, "LoaderTask running with no launcher");
2608 return;
2609 }
2610
Winson Chung9b9fb962013-11-15 15:39:34 -08002611 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002612 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2613 ArrayList<LauncherAppWidgetInfo> appWidgets =
2614 new ArrayList<LauncherAppWidgetInfo>();
2615 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2616 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002617 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002618 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002619 workspaceItems.addAll(sBgWorkspaceItems);
2620 appWidgets.addAll(sBgAppWidgets);
2621 folders.putAll(sBgFolders);
2622 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002623 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002624 }
2625
Derek Prothro7aff3992013-12-10 14:00:37 -05002626 final boolean isLoadingSynchronously =
2627 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002628 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002629 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002630 if (currScreen >= orderedScreenIds.size()) {
2631 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002632 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002633 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002634 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002635 final long currentScreenId = currentScreen < 0
2636 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002637
2638 // Load all the items that are on the current page first (and in the process, unbind
2639 // all the existing workspace items before we call startBinding() below.
2640 unbindWorkspaceItemsOnMainThread();
2641
2642 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002643 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2644 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2645 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2646 new ArrayList<LauncherAppWidgetInfo>();
2647 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2648 new ArrayList<LauncherAppWidgetInfo>();
2649 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2650 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2651
Winson Chung9b9fb962013-11-15 15:39:34 -08002652 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002654 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002656 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002657 otherFolders);
2658 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2659 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2660
2661 // Tell the workspace that we're about to start binding items
2662 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002663 public void run() {
2664 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2665 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002667 }
2668 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002669 };
Winson Chung81b52252012-08-27 15:34:29 -07002670 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002671
Adam Cohendcd297f2013-06-18 13:13:40 -07002672 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2673
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002674 // Load items on the current page
2675 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2676 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002677 if (isLoadingSynchronously) {
2678 r = new Runnable() {
2679 public void run() {
2680 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002681 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002682 callbacks.onPageBoundSynchronously(currentScreen);
2683 }
2684 }
2685 };
Winson Chung81b52252012-08-27 15:34:29 -07002686 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002687 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002688
Winson Chung4a2afa32012-07-19 14:53:05 -07002689 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2690 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002691 synchronized (mDeferredBindRunnables) {
2692 mDeferredBindRunnables.clear();
2693 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002694 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002695 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002696
2697 // Tell the workspace that we're done binding items
2698 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002699 public void run() {
2700 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2701 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002702 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002703 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002704
Winson Chung98e030b2012-05-07 16:01:11 -07002705 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002706 if (DEBUG_LOADERS) {
2707 Log.d(TAG, "bound workspace in "
2708 + (SystemClock.uptimeMillis()-t) + "ms");
2709 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002710
2711 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002712 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002713 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002714 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002715 synchronized (mDeferredBindRunnables) {
2716 mDeferredBindRunnables.add(r);
2717 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002718 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002719 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002720 }
Joe Onorato36115782010-06-17 13:28:48 -04002721 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002722
Joe Onorato36115782010-06-17 13:28:48 -04002723 private void loadAndBindAllApps() {
2724 if (DEBUG_LOADERS) {
2725 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2726 }
2727 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002728 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002729 synchronized (LoaderTask.this) {
2730 if (mStopped) {
2731 return;
2732 }
2733 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002734 }
Joe Onorato36115782010-06-17 13:28:48 -04002735 } else {
2736 onlyBindAllApps();
2737 }
2738 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002739
Joe Onorato36115782010-06-17 13:28:48 -04002740 private void onlyBindAllApps() {
2741 final Callbacks oldCallbacks = mCallbacks.get();
2742 if (oldCallbacks == null) {
2743 // This launcher has exited and nobody bothered to tell us. Just bail.
2744 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2745 return;
2746 }
2747
2748 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002749 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002750 final ArrayList<AppInfo> list
2751 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002752 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002753 public void run() {
2754 final long t = SystemClock.uptimeMillis();
2755 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2756 if (callbacks != null) {
2757 callbacks.bindAllApplications(list);
2758 }
2759 if (DEBUG_LOADERS) {
2760 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2761 + (SystemClock.uptimeMillis()-t) + "ms");
2762 }
2763 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002764 };
2765 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002766 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002767 r.run();
2768 } else {
2769 mHandler.post(r);
2770 }
Joe Onorato36115782010-06-17 13:28:48 -04002771 }
2772
Winson Chung64359a52013-07-08 17:17:08 -07002773 private void loadAllApps() {
2774 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002775
Joe Onorato36115782010-06-17 13:28:48 -04002776 final Callbacks oldCallbacks = mCallbacks.get();
2777 if (oldCallbacks == null) {
2778 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002779 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002780 return;
2781 }
2782
2783 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2784 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2785
Kenny Guyed131872014-04-30 03:02:21 +01002786 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2787
Winson Chung64359a52013-07-08 17:17:08 -07002788 // Clear the list of apps
2789 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002790 SharedPreferences prefs = mContext.getSharedPreferences(
2791 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002792 for (UserHandleCompat user : profiles) {
2793 // Query for the set of apps
2794 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2795 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2796 if (DEBUG_LOADERS) {
2797 Log.d(TAG, "getActivityList took "
2798 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2799 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2800 }
2801 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002802 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002803 if (apps == null || apps.isEmpty()) {
2804 return;
2805 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002806
2807 // Update icon cache
2808 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2809
2810 // If any package icon has changed (app was updated while launcher was dead),
2811 // update the corresponding shortcuts.
2812 if (!updatedPackages.isEmpty()) {
2813 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2814 synchronized (sBgLock) {
2815 for (ItemInfo info : sBgItemsIdMap.values()) {
2816 if (info instanceof ShortcutInfo && user.equals(info.user)
2817 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2818 ShortcutInfo si = (ShortcutInfo) info;
2819 ComponentName cn = si.getTargetComponent();
2820 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2821 si.updateIcon(mIconCache);
2822 updates.add(si);
2823 }
2824 }
2825 }
2826 }
2827
2828 if (!updates.isEmpty()) {
2829 final UserHandleCompat userFinal = user;
2830 mHandler.post(new Runnable() {
2831
2832 public void run() {
2833 Callbacks cb = getCallback();
2834 if (cb != null) {
2835 cb.bindShortcutsChanged(
2836 updates, new ArrayList<ShortcutInfo>(), userFinal);
2837 }
2838 }
2839 });
2840 }
Kenny Guyed131872014-04-30 03:02:21 +01002841 }
Joe Onorato36115782010-06-17 13:28:48 -04002842
Kenny Guyed131872014-04-30 03:02:21 +01002843 // Create the ApplicationInfos
2844 for (int i = 0; i < apps.size(); i++) {
2845 LauncherActivityInfoCompat app = apps.get(i);
2846 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002847 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002848 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002849
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002850 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002851 // Add shortcuts for packages which were installed while launcher was dead.
2852 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2853 + mUserManager.getSerialNumberForUser(user);
2854 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2855 HashSet<String> newPackageSet = new HashSet<String>();
2856
2857 for (LauncherActivityInfoCompat info : apps) {
2858 String packageName = info.getComponentName().getPackageName();
2859 if (!packagesAdded.contains(packageName)
2860 && !newPackageSet.contains(packageName)) {
2861 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2862 }
2863 newPackageSet.add(packageName);
2864 }
2865
2866 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2867 }
Winson Chung64359a52013-07-08 17:17:08 -07002868 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002869 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002870 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2871 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002872
2873 // Post callback on main thread
2874 mHandler.post(new Runnable() {
2875 public void run() {
2876 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002877 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002878 if (callbacks != null) {
2879 callbacks.bindAllApplications(added);
2880 if (DEBUG_LOADERS) {
2881 Log.d(TAG, "bound " + added.size() + " apps in "
2882 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2883 }
2884 } else {
2885 Log.i(TAG, "not binding apps: no Launcher activity");
2886 }
2887 }
2888 });
2889
Joe Onorato36115782010-06-17 13:28:48 -04002890 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002891 Log.d(TAG, "Icons processed in "
2892 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002893 }
2894 }
2895
2896 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002897 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002898 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2899 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2900 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2901 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2902 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2903 }
Joe Onorato36115782010-06-17 13:28:48 -04002904 }
2905 }
2906
2907 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002908 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002909 }
2910
Adam Cohen091440a2015-03-18 14:16:05 -07002911 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002912
2913 @Override
2914 public void onReceive(Context context, Intent intent) {
2915 synchronized (sBgLock) {
2916 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2917 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002918 final PackageManager manager = context.getPackageManager();
2919 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2920 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002921 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2922 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002923 packagesRemoved.clear();
2924 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002925 for (String pkg : entry.getValue()) {
2926 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002927 boolean packageOnSdcard = launcherApps.isAppEnabled(
2928 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2929 if (packageOnSdcard) {
2930 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2931 packagesUnavailable.add(pkg);
2932 } else {
2933 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2934 packagesRemoved.add(pkg);
2935 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002936 }
2937 }
2938 if (!packagesRemoved.isEmpty()) {
2939 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2940 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2941 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002942 if (!packagesUnavailable.isEmpty()) {
2943 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2944 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2945 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002946 }
Sunny Goyal34942622014-08-29 17:20:55 -07002947 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002948 }
2949 }
2950 }
2951
Joe Onorato36115782010-06-17 13:28:48 -04002952 private class PackageUpdatedTask implements Runnable {
2953 int mOp;
2954 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002955 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002956
2957 public static final int OP_NONE = 0;
2958 public static final int OP_ADD = 1;
2959 public static final int OP_UPDATE = 2;
2960 public static final int OP_REMOVE = 3; // uninstlled
2961 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2962
2963
Kenny Guyed131872014-04-30 03:02:21 +01002964 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002965 mOp = op;
2966 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002967 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002968 }
2969
2970 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002971 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002972
2973 final String[] packages = mPackages;
2974 final int N = packages.length;
2975 switch (mOp) {
2976 case OP_ADD:
2977 for (int i=0; i<N; i++) {
2978 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002979 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002980 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002981 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002982
2983 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002984 if (ADD_MANAGED_PROFILE_SHORTCUTS
2985 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002986 SharedPreferences prefs = context.getSharedPreferences(
2987 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2988 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2989 + mUserManager.getSerialNumberForUser(mUser);
2990 Set<String> shortcutSet = new HashSet<String>(
2991 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2992
2993 for (int i=0; i<N; i++) {
2994 if (!shortcutSet.contains(packages[i])) {
2995 shortcutSet.add(packages[i]);
2996 List<LauncherActivityInfoCompat> activities =
2997 mLauncherApps.getActivityList(packages[i], mUser);
2998 if (activities != null && !activities.isEmpty()) {
2999 InstallShortcutReceiver.queueInstallShortcut(
3000 activities.get(0), context);
3001 }
3002 }
3003 }
3004
3005 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3006 }
Joe Onorato36115782010-06-17 13:28:48 -04003007 break;
3008 case OP_UPDATE:
3009 for (int i=0; i<N; i++) {
3010 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003011 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003012 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003013 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003014 }
3015 break;
3016 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003017 // Remove the packageName for the set of auto-installed shortcuts. This
3018 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003019 if (ADD_MANAGED_PROFILE_SHORTCUTS
3020 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003021 SharedPreferences prefs = context.getSharedPreferences(
3022 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3023 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3024 + mUserManager.getSerialNumberForUser(mUser);
3025 HashSet<String> shortcutSet = new HashSet<String>(
3026 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3027 shortcutSet.removeAll(Arrays.asList(mPackages));
3028 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3029 }
Joe Onorato36115782010-06-17 13:28:48 -04003030 for (int i=0; i<N; i++) {
3031 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003032 mIconCache.removeIconsForPkg(packages[i], mUser);
3033 }
3034 // Fall through
3035 case OP_UNAVAILABLE:
3036 for (int i=0; i<N; i++) {
3037 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3038 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003039 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003040 }
3041 break;
3042 }
3043
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003044 ArrayList<AppInfo> added = null;
3045 ArrayList<AppInfo> modified = null;
3046 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003047
Adam Cohen487f7dd2012-06-28 18:12:10 -07003048 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003049 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003050 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003051 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003052 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003053 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003054 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003055 }
Winson Chung5d55f332012-07-16 20:45:03 -07003056 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003057 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003058 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003059 }
3060
Sunny Goyale0f58d72014-11-10 18:05:31 -08003061 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003062 if (callbacks == null) {
3063 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3064 return;
3065 }
3066
Sunny Goyal4390ace2014-10-13 11:33:11 -07003067 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3068 new HashMap<ComponentName, AppInfo>();
3069
Joe Onorato36115782010-06-17 13:28:48 -04003070 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003071 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003072 for (AppInfo ai : added) {
3073 addedOrUpdatedApps.put(ai.componentName, ai);
3074 }
Joe Onorato36115782010-06-17 13:28:48 -04003075 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003076
Joe Onorato36115782010-06-17 13:28:48 -04003077 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003078 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003079 for (AppInfo ai : modified) {
3080 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003081 }
3082
Joe Onorato36115782010-06-17 13:28:48 -04003083 mHandler.post(new Runnable() {
3084 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003085 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003086 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003087 callbacks.bindAppsUpdated(modifiedFinal);
3088 }
3089 }
3090 });
3091 }
Winson Chung83892cc2013-05-01 16:53:33 -07003092
Sunny Goyal4390ace2014-10-13 11:33:11 -07003093 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003094 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003095 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3096 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3097 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3098
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003099 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003100 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003101 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003102 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3103 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003104 boolean infoUpdated = false;
3105 boolean shortcutUpdated = false;
3106
3107 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003108 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003109 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003110 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3111 si.iconResource.resourceName, mIconCache, context);
3112 if (icon != null) {
3113 si.setIcon(icon);
3114 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003115 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003116 }
3117 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003118
3119 ComponentName cn = si.getTargetComponent();
3120 if (cn != null && packageSet.contains(cn.getPackageName())) {
3121 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3122
3123 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003124 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3125 // Auto install icon
3126 PackageManager pm = context.getPackageManager();
3127 ResolveInfo matched = pm.resolveActivity(
3128 new Intent(Intent.ACTION_MAIN)
3129 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3130 PackageManager.MATCH_DEFAULT_ONLY);
3131 if (matched == null) {
3132 // Try to find the best match activity.
3133 Intent intent = pm.getLaunchIntentForPackage(
3134 cn.getPackageName());
3135 if (intent != null) {
3136 cn = intent.getComponent();
3137 appInfo = addedOrUpdatedApps.get(cn);
3138 }
3139
3140 if ((intent == null) || (appInfo == null)) {
3141 removedShortcuts.add(si);
3142 continue;
3143 }
3144 si.promisedIntent = intent;
3145 }
3146 }
3147
3148 // Restore the shortcut.
3149 si.intent = si.promisedIntent;
3150 si.promisedIntent = null;
3151 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3152 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3153 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3154
3155 infoUpdated = true;
3156 si.updateIcon(mIconCache);
3157 }
3158
3159 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3160 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3161 si.updateIcon(mIconCache);
3162 si.title = appInfo.title.toString();
3163 si.contentDescription = appInfo.contentDescription;
3164 infoUpdated = true;
3165 }
3166
3167 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3168 // Since package was just updated, the target must be available now.
3169 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3170 shortcutUpdated = true;
3171 }
3172 }
3173
3174 if (infoUpdated || shortcutUpdated) {
3175 updatedShortcuts.add(si);
3176 }
3177 if (infoUpdated) {
3178 updateItemInDatabase(context, si);
3179 }
3180 } else if (info instanceof LauncherAppWidgetInfo) {
3181 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3182 if (mUser.equals(widgetInfo.user)
3183 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3184 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3185 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3186 widgets.add(widgetInfo);
3187 updateItemInDatabase(context, widgetInfo);
3188 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003189 }
3190 }
3191 }
3192
Sunny Goyal4390ace2014-10-13 11:33:11 -07003193 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3194 mHandler.post(new Runnable() {
3195
3196 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003197 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003198 if (callbacks == cb && cb != null) {
3199 callbacks.bindShortcutsChanged(
3200 updatedShortcuts, removedShortcuts, mUser);
3201 }
3202 }
3203 });
3204 if (!removedShortcuts.isEmpty()) {
3205 deleteItemsFromDatabase(context, removedShortcuts);
3206 }
3207 }
3208 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003209 mHandler.post(new Runnable() {
3210 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003211 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003212 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003213 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003214 }
3215 }
3216 });
3217 }
3218 }
3219
Winson Chungdf95eb12013-10-16 14:57:07 -07003220 final ArrayList<String> removedPackageNames =
3221 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003222 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003223 // Mark all packages in the broadcast to be removed
3224 removedPackageNames.addAll(Arrays.asList(packages));
3225 } else if (mOp == OP_UPDATE) {
3226 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003227 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003228 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003229 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003230 }
3231 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003232 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003233
Winson Chungdf95eb12013-10-16 14:57:07 -07003234 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003235 final int removeReason;
3236 if (mOp == OP_UNAVAILABLE) {
3237 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3238 } else {
3239 // Remove all the components associated with this package
3240 for (String pn : removedPackageNames) {
3241 deletePackageFromDatabase(context, pn, mUser);
3242 }
3243 // Remove all the specific components
3244 for (AppInfo a : removedApps) {
3245 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3246 deleteItemsFromDatabase(context, infos);
3247 }
3248 removeReason = 0;
3249 }
3250
Winson Chungdf95eb12013-10-16 14:57:07 -07003251 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003252 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003253 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003254 mHandler.post(new Runnable() {
3255 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003256 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003257 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003258 callbacks.bindComponentsRemoved(
3259 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003260 }
3261 }
3262 });
Joe Onoratobe386092009-11-17 17:32:16 -08003263 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003264
Michael Jurkac402cd92013-05-20 15:49:32 +02003265 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003266 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003267 mHandler.post(new Runnable() {
3268 @Override
3269 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003270 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003271 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003272 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003273 }
3274 }
3275 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003276
3277 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003278 mHandler.post(new Runnable() {
3279 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003280 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003281 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003282 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003283 }
3284 }
3285 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003286 }
3287 }
3288
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003289 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3290 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003291 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003292 if (sBgWidgetProviders == null || refresh) {
3293 sBgWidgetProviders = new HashMap<>();
3294 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3295 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003296
Robin Lee26ace122015-03-16 19:41:43 +00003297 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3298 for (AppWidgetProviderInfo pInfo : widgets) {
3299 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3300 UserHandleCompat user = wm.getUser(info);
3301 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3302 }
3303
3304 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3305 for (CustomAppWidget widget : customWidgets) {
3306 info = new LauncherAppWidgetProviderInfo(context, widget);
3307 UserHandleCompat user = wm.getUser(info);
3308 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3309 }
Adam Cohen59400422014-03-05 18:07:04 -08003310 }
Adam Cohen59400422014-03-05 18:07:04 -08003311 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3312 }
3313 }
3314
Robin Lee26ace122015-03-16 19:41:43 +00003315 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3316 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003317 synchronized (sBgLock) {
3318 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003319 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003320 }
Robin Lee26ace122015-03-16 19:41:43 +00003321 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003322 }
3323 }
3324
Winson Chungb745afb2015-03-02 11:51:23 -08003325 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003326 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003327 PackageManager packageManager = context.getPackageManager();
3328 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003329 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003330 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3331 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003332 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003333 return widgetsAndShortcuts;
3334 }
3335
Adam Cohen091440a2015-03-18 14:16:05 -07003336 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003337 UserHandleCompat user) {
3338 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3339 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003340 }
Adam Cohen556f6132014-01-15 15:18:08 -08003341
Kenny Guyed131872014-04-30 03:02:21 +01003342 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3343 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003344 if (cn == null) {
3345 return false;
3346 }
Kenny Guyed131872014-04-30 03:02:21 +01003347 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3348 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003349 return false;
3350 }
Kenny Guyed131872014-04-30 03:02:21 +01003351 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003352 }
3353
Adam Cohena28b78e2014-05-20 17:03:04 -07003354 public static boolean isValidPackage(Context context, String packageName,
3355 UserHandleCompat user) {
3356 if (packageName == null) {
3357 return false;
3358 }
3359 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3360 return launcherApps.isPackageEnabledForProfile(packageName, user);
3361 }
3362
Joe Onorato9c1289c2009-08-17 11:03:03 -04003363 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003364 * Make an ShortcutInfo object for a restored application or shortcut item that points
3365 * to a package that is not yet installed on the system.
3366 */
Sunny Goyal34942622014-08-29 17:20:55 -07003367 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003368 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003369 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003370 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003371 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003372
3373 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3374 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3375 if (!TextUtils.isEmpty(title)) {
3376 info.title = title;
3377 }
3378 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3379 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3380 if (TextUtils.isEmpty(info.title)) {
3381 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3382 }
3383 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3384 } else {
3385 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3386 }
3387
Kenny Guyc2bd8102014-06-30 12:30:31 +01003388 info.contentDescription = mUserManager.getBadgedLabelForUser(
3389 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003390 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003391 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003392 return info;
3393 }
3394
3395 /**
3396 * Make an Intent object for a restored application or shortcut item that points
3397 * to the market page for the item.
3398 */
Adam Cohen091440a2015-03-18 14:16:05 -07003399 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003400 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003401 return getMarketIntent(componentName.getPackageName());
3402 }
3403
3404 static Intent getMarketIntent(String packageName) {
3405 return new Intent(Intent.ACTION_VIEW)
3406 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003407 .scheme("market")
3408 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003409 .appendQueryParameter("id", packageName)
3410 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003411 }
3412
3413 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003414 * Make an ShortcutInfo object for a shortcut that is an application.
3415 *
3416 * If c is not null, then it will be used to fill in missing data like the title and icon.
3417 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003418 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003419 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003420 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003421 if (user == null) {
3422 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003423 return null;
3424 }
3425
Kenny Guyed131872014-04-30 03:02:21 +01003426 ComponentName componentName = intent.getComponent();
3427 if (componentName == null) {
3428 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3429 return null;
3430 }
3431
3432 Intent newIntent = new Intent(intent.getAction(), null);
3433 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3434 newIntent.setComponent(componentName);
3435 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003436 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003437 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3438 return null;
3439 }
3440
3441 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003442 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003443 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3444 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3445 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003446 }
3447
Joe Onorato56d82912010-03-07 14:32:10 -05003448 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003449 if (TextUtils.isEmpty(info.title) && c != null) {
3450 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003451 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003452
Joe Onorato56d82912010-03-07 14:32:10 -05003453 // fall back to the class name of the activity
3454 if (info.title == null) {
3455 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003456 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003457
Joe Onorato9c1289c2009-08-17 11:03:03 -04003458 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003459 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003460 info.contentDescription = mUserManager.getBadgedLabelForUser(
3461 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003462 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003463 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003464
Winson Chung64359a52013-07-08 17:17:08 -07003465 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3466 ItemInfoFilter f) {
3467 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3468 for (ItemInfo i : infos) {
3469 if (i instanceof ShortcutInfo) {
3470 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003471 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003472 if (cn != null && f.filterItem(null, info, cn)) {
3473 filtered.add(info);
3474 }
3475 } else if (i instanceof FolderInfo) {
3476 FolderInfo info = (FolderInfo) i;
3477 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003478 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003479 if (cn != null && f.filterItem(info, s, cn)) {
3480 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003481 }
3482 }
Winson Chung64359a52013-07-08 17:17:08 -07003483 } else if (i instanceof LauncherAppWidgetInfo) {
3484 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3485 ComponentName cn = info.providerName;
3486 if (cn != null && f.filterItem(null, info, cn)) {
3487 filtered.add(info);
3488 }
Winson Chung8a435102012-08-30 17:16:53 -07003489 }
3490 }
Winson Chung64359a52013-07-08 17:17:08 -07003491 return new ArrayList<ItemInfo>(filtered);
3492 }
3493
Adam Cohen091440a2015-03-18 14:16:05 -07003494 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003495 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003496 ItemInfoFilter filter = new ItemInfoFilter() {
3497 @Override
3498 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003499 if (info.user == null) {
3500 return cn.equals(cname);
3501 } else {
3502 return cn.equals(cname) && info.user.equals(user);
3503 }
Winson Chung64359a52013-07-08 17:17:08 -07003504 }
3505 };
3506 return filterItemInfos(sBgItemsIdMap.values(), filter);
3507 }
3508
Sunny Goyal1a745e82014-10-02 15:58:31 -07003509 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003510 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003511 */
Adam Cohen091440a2015-03-18 14:16:05 -07003512 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003513 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3514 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003515
Joe Onorato56d82912010-03-07 14:32:10 -05003516 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003517 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003518 // Non-app shortcuts are only supported for current user.
3519 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003520 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003521
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003522 // TODO: If there's an explicit component and we can't install that, delete it.
3523
Joe Onorato56d82912010-03-07 14:32:10 -05003524 info.title = c.getString(titleIndex);
3525
Joe Onorato9c1289c2009-08-17 11:03:03 -04003526 int iconType = c.getInt(iconTypeIndex);
3527 switch (iconType) {
3528 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3529 String packageName = c.getString(iconPackageIndex);
3530 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003531 info.customIcon = false;
3532 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003533 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003534 // the db
3535 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003536 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003537 }
3538 // the fallback icon
3539 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003540 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003541 info.usingFallbackIcon = true;
3542 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003543 break;
3544 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003545 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003546 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003547 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003548 info.customIcon = false;
3549 info.usingFallbackIcon = true;
3550 } else {
3551 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003552 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003553 break;
3554 default:
Kenny Guyed131872014-04-30 03:02:21 +01003555 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003556 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003557 info.customIcon = false;
3558 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003559 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003560 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003561 return info;
3562 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003563
Sunny Goyal2350bc92014-10-14 16:42:54 -07003564 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003565 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3566 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3567 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3568
Adam Cohend9198822011-11-22 16:42:47 -08003569 if (intent == null) {
3570 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3571 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3572 return null;
3573 }
3574
Joe Onorato0589f0f2010-02-08 13:44:00 -08003575 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003576 boolean customIcon = false;
3577 ShortcutIconResource iconResource = null;
3578
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003579 if (bitmap instanceof Bitmap) {
3580 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003581 customIcon = true;
3582 } else {
3583 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003584 if (extra instanceof ShortcutIconResource) {
3585 iconResource = (ShortcutIconResource) extra;
3586 icon = Utilities.createIconBitmap(iconResource.packageName,
3587 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003588 }
3589 }
3590
Michael Jurkac9d95c52011-08-29 14:03:34 -07003591 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003592
Kenny Guyed131872014-04-30 03:02:21 +01003593 // Only support intents for current user for now. Intents sent from other
3594 // users wouldn't get here without intent forwarding anyway.
3595 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003596 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003597 icon = mIconCache.getDefaultIcon(info.user);
3598 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003599 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003600 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003601
Joe Onorato0589f0f2010-02-08 13:44:00 -08003602 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003603 info.contentDescription = mUserManager.getBadgedLabelForUser(
3604 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003605 info.intent = intent;
3606 info.customIcon = customIcon;
3607 info.iconResource = iconResource;
3608
3609 return info;
3610 }
3611
Joe Onorato9c1289c2009-08-17 11:03:03 -04003612 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003613 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003614 * or make a new one.
3615 */
Adam Cohen091440a2015-03-18 14:16:05 -07003616 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003617 // See if a placeholder was created for us already
3618 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003619 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003620 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003621 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003622 folders.put(id, folderInfo);
3623 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003624 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003625 }
3626
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003627 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003628 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003629 return new Comparator<AppInfo>() {
3630 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003631 if (a.user.equals(b.user)) {
3632 int result = collator.compare(a.title.toString().trim(),
3633 b.title.toString().trim());
3634 if (result == 0) {
3635 result = a.componentName.compareTo(b.componentName);
3636 }
3637 return result;
3638 } else {
3639 // TODO Need to figure out rules for sorting
3640 // profiles, this puts work second.
3641 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003642 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003643 }
Winson Chung11904872012-09-17 16:58:46 -07003644 };
3645 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003646 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3647 = new Comparator<AppInfo>() {
3648 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003649 if (a.firstInstallTime < b.firstInstallTime) return 1;
3650 if (a.firstInstallTime > b.firstInstallTime) return -1;
3651 return 0;
3652 }
3653 };
Winson Chung5308f242011-08-18 12:12:41 -07003654 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3655 if (info.activityInfo != null) {
3656 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3657 } else {
3658 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3659 }
3660 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003661
Winson Chung1ed747a2011-05-03 16:18:34 -07003662 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003663 private final AppWidgetManagerCompat mManager;
3664 private final PackageManager mPackageManager;
3665 private final HashMap<Object, String> mLabelCache;
3666 private final Collator mCollator;
3667
3668 WidgetAndShortcutNameComparator(Context context) {
3669 mManager = AppWidgetManagerCompat.getInstance(context);
3670 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003671 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003672 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003673 }
3674 public final int compare(Object a, Object b) {
3675 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003676 if (mLabelCache.containsKey(a)) {
3677 labelA = mLabelCache.get(a);
3678 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003679 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3680 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003681 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003682 mLabelCache.put(a, labelA);
3683 }
3684 if (mLabelCache.containsKey(b)) {
3685 labelB = mLabelCache.get(b);
3686 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003687 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003688 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003689 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003690 mLabelCache.put(b, labelB);
3691 }
Winson Chung11904872012-09-17 16:58:46 -07003692 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003693 }
3694 };
Joe Onoratobe386092009-11-17 17:32:16 -08003695
Sunny Goyal651077b2014-06-30 14:15:31 -07003696 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3697 return (provider != null) && (provider.provider != null)
3698 && (provider.provider.getPackageName() != null);
3699 }
3700
Joe Onoratobe386092009-11-17 17:32:16 -08003701 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003702 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003703 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3704 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3705 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3706 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003707 if (mLoaderTask != null) {
3708 mLoaderTask.dumpState();
3709 } else {
3710 Log.d(TAG, "mLoaderTask=null");
3711 }
Joe Onoratobe386092009-11-17 17:32:16 -08003712 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003713
3714 public Callbacks getCallback() {
3715 return mCallbacks != null ? mCallbacks.get() : null;
3716 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003717}