blob: c6ed0da82e63628a572b7a283b08cbcc6f7cb474 [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 Goyal1d4a2df2015-03-30 11:11:46 -0700569 screenId, cordinates[0], cordinates[1]);
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
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700655 addItemToDatabase(context, item, container, screenId, cellX, cellY);
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;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700721 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700722 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;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700747 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700748 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,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700997 final long screenId, final int cellX, final int cellY) {
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() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001020 cr.insert(LauncherSettings.Favorites.CONTENT_URI, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001021
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001022 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001023 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001024 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001025 sBgItemsIdMap.put(item.id, item);
1026 switch (item.itemType) {
1027 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1028 sBgFolders.put(item.id, (FolderInfo) item);
1029 // Fall through
1030 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1031 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1032 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1033 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1034 sBgWorkspaceItems.add(item);
1035 } else {
1036 if (!sBgFolders.containsKey(item.container)) {
1037 // Adding an item to a folder that doesn't exist.
1038 String msg = "adding item: " + item + " to a folder that " +
1039 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001040 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001042 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001043 break;
1044 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1045 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1046 break;
1047 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001048 }
1049 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001050 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001051 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001052 }
1053
Joe Onorato9c1289c2009-08-17 11:03:03 -04001054 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001055 * Creates a new unique child id, for a given cell span across all layouts.
1056 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001057 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001058 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001059 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001060 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001061 }
1062
Sunny Goyal34942622014-08-29 17:20:55 -07001063 private static ArrayList<ItemInfo> getItemsByPackageName(
1064 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001065 ItemInfoFilter filter = new ItemInfoFilter() {
1066 @Override
1067 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1068 return cn.getPackageName().equals(pn) && info.user.equals(user);
1069 }
1070 };
Sunny Goyal34942622014-08-29 17:20:55 -07001071 return filterItemInfos(sBgItemsIdMap.values(), filter);
1072 }
1073
1074 /**
1075 * Removes all the items from the database corresponding to the specified package.
1076 */
1077 static void deletePackageFromDatabase(Context context, final String pn,
1078 final UserHandleCompat user) {
1079 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001080 }
1081
1082 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001083 * Removes the specified item from the database
1084 * @param context
1085 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001087 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001088 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1089 items.add(item);
1090 deleteItemsFromDatabase(context, items);
1091 }
1092
1093 /**
1094 * Removes the specified items from the database
1095 * @param context
1096 * @param item
1097 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001098 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001100
Michael Jurka83df1882011-08-31 20:59:26 -07001101 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001102 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001103 for (ItemInfo item : items) {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001104 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001105 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001107 // Lock on mBgLock *after* the db operation
1108 synchronized (sBgLock) {
1109 switch (item.itemType) {
1110 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1111 sBgFolders.remove(item.id);
1112 for (ItemInfo info: sBgItemsIdMap.values()) {
1113 if (info.container == item.id) {
1114 // We are deleting a folder which still contains items that
1115 // think they are contained by that folder.
1116 String msg = "deleting a folder (" + item + ") which still " +
1117 "contains items (" + info + ")";
1118 Log.e(TAG, msg);
1119 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001120 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001121 sBgWorkspaceItems.remove(item);
1122 break;
1123 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1124 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1125 sBgWorkspaceItems.remove(item);
1126 break;
1127 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1128 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1129 break;
1130 }
1131 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001132 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001133 }
1134 }
Michael Jurka83df1882011-08-31 20:59:26 -07001135 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001136 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001137 }
1138
1139 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 * Update the order of the workspace screens in the database. The array list contains
1141 * a list of screen ids in the order that they should appear.
1142 */
Winson Chungc9168342013-06-26 14:54:55 -07001143 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001144 // Log to disk
1145 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1146 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1147
Winson Chung64359a52013-07-08 17:17:08 -07001148 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001149 final ContentResolver cr = context.getContentResolver();
1150 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1151
1152 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001153 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 while (iter.hasNext()) {
1155 long id = iter.next();
1156 if (id < 0) {
1157 iter.remove();
1158 }
1159 }
1160
1161 Runnable r = new Runnable() {
1162 @Override
1163 public void run() {
Yura085c8532014-02-11 15:15:29 +00001164 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001165 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001166 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001167 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 for (int i = 0; i < count; i++) {
1169 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001170 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1172 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001173 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001174 }
Yura085c8532014-02-11 15:15:29 +00001175
1176 try {
1177 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1178 } catch (Exception ex) {
1179 throw new RuntimeException(ex);
1180 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001181
Winson Chungba9c37f2013-08-30 14:11:37 -07001182 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001183 sBgWorkspaceScreens.clear();
1184 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001185 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001186 }
1187 };
1188 runOnWorkerThread(r);
1189 }
1190
1191 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001192 * Remove the contents of the specified folder from the database
1193 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001194 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001195 final ContentResolver cr = context.getContentResolver();
1196
Michael Jurkac9d95c52011-08-29 14:03:34 -07001197 Runnable r = new Runnable() {
1198 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001199 cr.delete(LauncherSettings.Favorites.getContentUri(info.id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001200 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001201 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001202 sBgItemsIdMap.remove(info.id);
1203 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 sBgWorkspaceItems.remove(info);
1205 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001206
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001207 cr.delete(LauncherSettings.Favorites.CONTENT_URI,
Michael Jurkac9d95c52011-08-29 14:03:34 -07001208 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001209 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001210 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 for (ItemInfo childInfo : info.contents) {
1212 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001213 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001214 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001215 }
1216 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001217 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001218 }
1219
1220 /**
1221 * Set this as the current Launcher activity object for the loader.
1222 */
1223 public void initialize(Callbacks callbacks) {
1224 synchronized (mLock) {
1225 mCallbacks = new WeakReference<Callbacks>(callbacks);
1226 }
1227 }
1228
Kenny Guyed131872014-04-30 03:02:21 +01001229 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001230 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001231 int op = PackageUpdatedTask.OP_UPDATE;
1232 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1233 user));
1234 }
1235
1236 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001237 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001238 int op = PackageUpdatedTask.OP_REMOVE;
1239 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1240 user));
1241 }
1242
1243 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001244 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001245 int op = PackageUpdatedTask.OP_ADD;
1246 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1247 user));
1248 }
1249
1250 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001251 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001252 boolean replacing) {
1253 if (!replacing) {
1254 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1255 user));
1256 if (mAppsCanBeOnRemoveableStorage) {
1257 // Only rebind if we support removable storage. It catches the
1258 // case where
1259 // apps on the external sd card need to be reloaded
1260 startLoaderFromBackground();
1261 }
1262 } else {
1263 // If we are replacing then just update the packages in the list
1264 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1265 packageNames, user));
1266 }
1267 }
1268
1269 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001270 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001271 boolean replacing) {
1272 if (!replacing) {
1273 enqueuePackageUpdated(new PackageUpdatedTask(
1274 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1275 user));
1276 }
Kenny Guyed131872014-04-30 03:02:21 +01001277 }
1278
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001279 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001280 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1281 * ACTION_PACKAGE_CHANGED.
1282 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001283 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001284 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001285 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001286
Joe Onorato36115782010-06-17 13:28:48 -04001287 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001288 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001289 // If we have changed locale we need to clear out the labels in all apps/workspace.
1290 forceReload();
1291 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1292 // Check if configuration change was an mcc/mnc change which would affect app resources
1293 // and we would need to clear out the labels in all apps/workspace. Same handling as
1294 // above for ACTION_LOCALE_CHANGED
1295 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001296 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001297 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001298 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001299 forceReload();
1300 }
1301 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001302 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001303 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1304 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001305 Callbacks callbacks = getCallback();
1306 if (callbacks != null) {
1307 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001308 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001309 }
1310 }
1311
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001312 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001313 resetLoadedState(true, true);
1314
Reena Lee93f824a2011-09-23 17:20:28 -07001315 // Do this here because if the launcher activity is running it will be restarted.
1316 // If it's not running startLoaderFromBackground will merely tell it that it needs
1317 // to reload.
1318 startLoaderFromBackground();
1319 }
1320
Winson Chungf0c6ae02012-03-21 16:10:31 -07001321 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1322 synchronized (mLock) {
1323 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1324 // mWorkspaceLoaded to true later
1325 stopLoaderLocked();
1326 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1327 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1328 }
1329 }
1330
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001331 /**
1332 * When the launcher is in the background, it's possible for it to miss paired
1333 * configuration changes. So whenever we trigger the loader from the background
1334 * tell the launcher that it needs to re-run the loader when it comes back instead
1335 * of doing it now.
1336 */
1337 public void startLoaderFromBackground() {
1338 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001339 Callbacks callbacks = getCallback();
1340 if (callbacks != null) {
1341 // Only actually run the loader if they're not paused.
1342 if (!callbacks.setLoadOnResume()) {
1343 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001344 }
1345 }
1346 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001347 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001348 }
Joe Onorato36115782010-06-17 13:28:48 -04001349 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001350
Reena Lee93f824a2011-09-23 17:20:28 -07001351 // If there is already a loader task running, tell it to stop.
1352 // returns true if isLaunching() was true on the old task
1353 private boolean stopLoaderLocked() {
1354 boolean isLaunching = false;
1355 LoaderTask oldTask = mLoaderTask;
1356 if (oldTask != null) {
1357 if (oldTask.isLaunching()) {
1358 isLaunching = true;
1359 }
1360 oldTask.stopLocked();
1361 }
1362 return isLaunching;
1363 }
1364
Adam Cohen1a85c582014-09-30 09:48:49 -07001365 public boolean isCurrentCallbacks(Callbacks callbacks) {
1366 return (mCallbacks != null && mCallbacks.get() == callbacks);
1367 }
1368
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001369 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001370 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1371 }
1372
1373 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001374 synchronized (mLock) {
1375 if (DEBUG_LOADERS) {
1376 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1377 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001378
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001379 // Clear any deferred bind-runnables from the synchronized load process
1380 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001381 synchronized (mDeferredBindRunnables) {
1382 mDeferredBindRunnables.clear();
1383 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001384
Joe Onorato36115782010-06-17 13:28:48 -04001385 // Don't bother to start the thread if we know it's not going to do anything
1386 if (mCallbacks != null && mCallbacks.get() != null) {
1387 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001388 // also, don't downgrade isLaunching if we're already running
1389 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001390 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001391 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1392 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001393 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1394 } else {
1395 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1396 sWorker.post(mLoaderTask);
1397 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001398 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001399 }
1400 }
1401
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 void bindRemainingSynchronousPages() {
1403 // Post the remaining side pages to be loaded
1404 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001405 Runnable[] deferredBindRunnables = null;
1406 synchronized (mDeferredBindRunnables) {
1407 deferredBindRunnables = mDeferredBindRunnables.toArray(
1408 new Runnable[mDeferredBindRunnables.size()]);
1409 mDeferredBindRunnables.clear();
1410 }
1411 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001412 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001413 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001414 }
1415 }
1416
Joe Onorato36115782010-06-17 13:28:48 -04001417 public void stopLoader() {
1418 synchronized (mLock) {
1419 if (mLoaderTask != null) {
1420 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001421 }
1422 }
Joe Onorato36115782010-06-17 13:28:48 -04001423 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001424
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001425 /**
1426 * Loads the workspace screen ids in an ordered list.
1427 */
Adam Cohen091440a2015-03-18 14:16:05 -07001428 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001429 final ContentResolver contentResolver = context.getContentResolver();
1430 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001431
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001432 // Get screens ordered by rank.
1433 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1434 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1435 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001436 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001437 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001438 while (sc.moveToNext()) {
1439 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001440 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001441 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001442 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1443 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001444 }
1445 }
1446 } finally {
1447 sc.close();
1448 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001449 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001450 }
1451
Michael Jurkac57b7a82011-08-09 22:02:20 -07001452 public boolean isAllAppsLoaded() {
1453 return mAllAppsLoaded;
1454 }
1455
Winson Chung36a62fe2012-05-06 18:04:42 -07001456 boolean isLoadingWorkspace() {
1457 synchronized (mLock) {
1458 if (mLoaderTask != null) {
1459 return mLoaderTask.isLoadingWorkspace();
1460 }
1461 }
1462 return false;
1463 }
1464
Joe Onorato36115782010-06-17 13:28:48 -04001465 /**
1466 * Runnable for the thread that loads the contents of the launcher:
1467 * - workspace icons
1468 * - widgets
1469 * - all apps icons
1470 */
1471 private class LoaderTask implements Runnable {
1472 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001474 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001475 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001476 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001477 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001478
Dan Sandlerd5024042014-01-09 15:01:33 -05001479 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001480 mContext = context;
1481 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001482 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 boolean isLaunching() {
1486 return mIsLaunching;
1487 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 boolean isLoadingWorkspace() {
1490 return mIsLoadingAndBindingWorkspace;
1491 }
1492
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001493 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001494 mIsLoadingAndBindingWorkspace = true;
1495
Joe Onorato36115782010-06-17 13:28:48 -04001496 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001497 if (DEBUG_LOADERS) {
1498 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001499 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001500
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001501 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001502 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001503 synchronized (LoaderTask.this) {
1504 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001505 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001506 }
1507 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001508 }
1509 }
1510
Joe Onorato36115782010-06-17 13:28:48 -04001511 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001512 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001513 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001514
Joe Onorato36115782010-06-17 13:28:48 -04001515 private void waitForIdle() {
1516 // Wait until the either we're stopped or the other threads are done.
1517 // This way we don't start loading all apps until the workspace has settled
1518 // down.
1519 synchronized (LoaderTask.this) {
1520 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001521
Joe Onorato36115782010-06-17 13:28:48 -04001522 mHandler.postIdle(new Runnable() {
1523 public void run() {
1524 synchronized (LoaderTask.this) {
1525 mLoadAndBindStepFinished = true;
1526 if (DEBUG_LOADERS) {
1527 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001528 }
Joe Onorato36115782010-06-17 13:28:48 -04001529 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001530 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Joe Onorato36115782010-06-17 13:28:48 -04001532 });
1533
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001534 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001535 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001536 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1537 // wait no longer than 1sec at a time
1538 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001539 } catch (InterruptedException ex) {
1540 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001541 }
1542 }
Joe Onorato36115782010-06-17 13:28:48 -04001543 if (DEBUG_LOADERS) {
1544 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001545 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001546 + "ms for previous step to finish binding");
1547 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001548 }
Joe Onorato36115782010-06-17 13:28:48 -04001549 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001550
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001551 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001552 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001553 // Ensure that we have a valid page index to load synchronously
1554 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1555 "valid page index");
1556 }
1557 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1558 // Ensure that we don't try and bind a specified page when the pages have not been
1559 // loaded already (we should load everything asynchronously in that case)
1560 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1561 }
1562 synchronized (mLock) {
1563 if (mIsLoaderTaskRunning) {
1564 // Ensure that we are never running the background loading at this point since
1565 // we also touch the background collections
1566 throw new RuntimeException("Error! Background loading is already running");
1567 }
1568 }
1569
1570 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1571 // data structures, we can't allow any other thread to touch that data, but because
1572 // this call is synchronous, we can get away with not locking).
1573
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001574 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001575 // operations from the previous activity. We need to ensure that all queued operations
1576 // are executed before any synchronous binding work is done.
1577 mHandler.flush();
1578
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001579 // Divide the set of loaded items into those that we are binding synchronously, and
1580 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001581 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1583 // arise from that.
1584 onlyBindAllApps();
1585 }
1586
Joe Onorato36115782010-06-17 13:28:48 -04001587 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001588 synchronized (mLock) {
1589 mIsLoaderTaskRunning = true;
1590 }
Joe Onorato36115782010-06-17 13:28:48 -04001591 // Optimize for end-user experience: if the Launcher is up and // running with the
1592 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1593 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001594 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001595 // Elevate priority when Home launches for the first time to avoid
1596 // starving at boot time. Staring at a blank home is not cool.
1597 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001598 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1599 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001600 android.os.Process.setThreadPriority(mIsLaunching
1601 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1602 }
Winson Chung64359a52013-07-08 17:17:08 -07001603 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001604 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001605
Joe Onorato36115782010-06-17 13:28:48 -04001606 if (mStopped) {
1607 break keep_running;
1608 }
1609
1610 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1611 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001612 synchronized (mLock) {
1613 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001614 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001615 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1616 }
1617 }
Joe Onorato36115782010-06-17 13:28:48 -04001618 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001619
1620 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001621 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1622 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001623
Sunny Goyal5b0e6692015-03-19 14:31:19 -07001624 // Remove entries for packages which changed while the launcher was dead.
1625 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews();
1626
Winson Chung7ed37742011-09-08 15:45:51 -07001627 // Restore the default thread priority after we are done loading items
1628 synchronized (mLock) {
1629 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1630 }
Joe Onorato36115782010-06-17 13:28:48 -04001631 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001632
Joe Onorato36115782010-06-17 13:28:48 -04001633 // Clear out this reference, otherwise we end up holding it until all of the
1634 // callback runnables are done.
1635 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001636
Joe Onorato36115782010-06-17 13:28:48 -04001637 synchronized (mLock) {
1638 // If we are still the last one to be scheduled, remove ourselves.
1639 if (mLoaderTask == this) {
1640 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001641 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001642 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001643 }
Joe Onorato36115782010-06-17 13:28:48 -04001644 }
1645
1646 public void stopLocked() {
1647 synchronized (LoaderTask.this) {
1648 mStopped = true;
1649 this.notify();
1650 }
1651 }
1652
1653 /**
1654 * Gets the callbacks object. If we've been stopped, or if the launcher object
1655 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1656 * object that was around when the deferred message was scheduled, and if there's
1657 * a new Callbacks object around then also return null. This will save us from
1658 * calling onto it with data that will be ignored.
1659 */
1660 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1661 synchronized (mLock) {
1662 if (mStopped) {
1663 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001664 }
Joe Onorato36115782010-06-17 13:28:48 -04001665
1666 if (mCallbacks == null) {
1667 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001668 }
Joe Onorato36115782010-06-17 13:28:48 -04001669
1670 final Callbacks callbacks = mCallbacks.get();
1671 if (callbacks != oldCallbacks) {
1672 return null;
1673 }
1674 if (callbacks == null) {
1675 Log.w(TAG, "no mCallbacks");
1676 return null;
1677 }
1678
1679 return callbacks;
1680 }
1681 }
1682
1683 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001684 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001685 LauncherAppState app = LauncherAppState.getInstance();
1686 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001687 final int countX = (int) grid.numColumns;
1688 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001689
Adam Cohendcd297f2013-06-18 13:13:40 -07001690 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001691 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001692 // Return early if we detect that an item is under the hotseat button
1693 if (mCallbacks == null ||
1694 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001695 Log.e(TAG, "Error loading shortcut into hotseat " + item
1696 + " into position (" + item.screenId + ":" + item.cellX + ","
1697 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001698 return false;
1699 }
1700
Dan Sandler295ae182013-12-10 16:05:47 -05001701 final ItemInfo[][] hotseatItems =
1702 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1703
Adam Cohenae4409d2013-11-26 10:34:59 -08001704 if (item.screenId >= grid.numHotseatIcons) {
1705 Log.e(TAG, "Error loading shortcut " + item
1706 + " into hotseat position " + item.screenId
1707 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1708 + ")");
1709 return false;
1710 }
1711
Dan Sandler295ae182013-12-10 16:05:47 -05001712 if (hotseatItems != null) {
1713 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001714 Log.e(TAG, "Error loading shortcut into hotseat " + item
1715 + " into position (" + item.screenId + ":" + item.cellX + ","
1716 + item.cellY + ") occupied by "
1717 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1718 [(int) item.screenId][0]);
1719 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001720 } else {
1721 hotseatItems[(int) item.screenId][0] = item;
1722 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001723 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001724 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001725 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001726 items[(int) item.screenId][0] = item;
1727 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001728 return true;
1729 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001730 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1731 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001732 return true;
1733 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001734
Adam Cohendcd297f2013-06-18 13:13:40 -07001735 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001736 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001737 occupied.put(item.screenId, items);
1738 }
1739
Dan Sandler295ae182013-12-10 16:05:47 -05001740 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001741 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1742 item.cellX < 0 || item.cellY < 0 ||
1743 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1744 Log.e(TAG, "Error loading shortcut " + item
1745 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1746 + item.cellX + "," + item.cellY
1747 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1748 return false;
1749 }
1750
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001751 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001752 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1753 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001755 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001756 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001757 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001758 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001759 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001760 return false;
1761 }
1762 }
1763 }
1764 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1765 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001766 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001767 }
1768 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001769
Joe Onorato36115782010-06-17 13:28:48 -04001770 return true;
1771 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001772
Winson Chungba9c37f2013-08-30 14:11:37 -07001773 /** Clears all the sBg data structures */
1774 private void clearSBgDataStructures() {
1775 synchronized (sBgLock) {
1776 sBgWorkspaceItems.clear();
1777 sBgAppWidgets.clear();
1778 sBgFolders.clear();
1779 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001780 sBgWorkspaceScreens.clear();
1781 }
1782 }
1783
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001784 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001785 // Log to disk
1786 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1787
Joe Onorato36115782010-06-17 13:28:48 -04001788 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001789
Joe Onorato36115782010-06-17 13:28:48 -04001790 final Context context = mContext;
1791 final ContentResolver contentResolver = context.getContentResolver();
1792 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001793 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001794 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1795 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001796 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001797
Winson Chung892c74d2013-08-22 16:15:50 -07001798 LauncherAppState app = LauncherAppState.getInstance();
1799 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1800 int countX = (int) grid.numColumns;
1801 int countY = (int) grid.numRows;
1802
Dan Sandlerd5024042014-01-09 15:01:33 -05001803 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1804 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1805 LauncherAppState.getLauncherProvider().deleteDatabase();
1806 }
1807
1808 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1809 // append the user's Launcher2 shortcuts
1810 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1811 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1812 } else {
1813 // Make sure the default workspace is loaded
1814 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001815 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001816 }
Adam Cohene25af792013-06-06 23:08:25 -07001817
Winson Chung2abf94d2012-07-18 18:16:38 -07001818 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001819 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001820 final HashSet<String> installingPkgs = PackageInstallerCompat
1821 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001822
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001823 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001824 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001825 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001826 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001827 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001828
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001829 // +1 for the hotseat (it can be larger than the workspace)
1830 // Load workspace in reverse order to ensure that latest items are loaded first (and
1831 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001832 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001833
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001834 try {
1835 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1836 final int intentIndex = c.getColumnIndexOrThrow
1837 (LauncherSettings.Favorites.INTENT);
1838 final int titleIndex = c.getColumnIndexOrThrow
1839 (LauncherSettings.Favorites.TITLE);
1840 final int iconTypeIndex = c.getColumnIndexOrThrow(
1841 LauncherSettings.Favorites.ICON_TYPE);
1842 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1843 final int iconPackageIndex = c.getColumnIndexOrThrow(
1844 LauncherSettings.Favorites.ICON_PACKAGE);
1845 final int iconResourceIndex = c.getColumnIndexOrThrow(
1846 LauncherSettings.Favorites.ICON_RESOURCE);
1847 final int containerIndex = c.getColumnIndexOrThrow(
1848 LauncherSettings.Favorites.CONTAINER);
1849 final int itemTypeIndex = c.getColumnIndexOrThrow(
1850 LauncherSettings.Favorites.ITEM_TYPE);
1851 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1852 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001853 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1854 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001855 final int screenIndex = c.getColumnIndexOrThrow(
1856 LauncherSettings.Favorites.SCREEN);
1857 final int cellXIndex = c.getColumnIndexOrThrow
1858 (LauncherSettings.Favorites.CELLX);
1859 final int cellYIndex = c.getColumnIndexOrThrow
1860 (LauncherSettings.Favorites.CELLY);
1861 final int spanXIndex = c.getColumnIndexOrThrow
1862 (LauncherSettings.Favorites.SPANX);
1863 final int spanYIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001865 final int rankIndex = c.getColumnIndexOrThrow(
1866 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001867 final int restoredIndex = c.getColumnIndexOrThrow(
1868 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001869 final int profileIdIndex = c.getColumnIndexOrThrow(
1870 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001871 final int optionsIndex = c.getColumnIndexOrThrow(
1872 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001873
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001874 ShortcutInfo info;
1875 String intentDescription;
1876 LauncherAppWidgetInfo appWidgetInfo;
1877 int container;
1878 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001879 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001880 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001881 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001882
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 while (!mStopped && c.moveToNext()) {
1884 try {
1885 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001886 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001887 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001888
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001889 switch (itemType) {
1890 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1891 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001892 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001893 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001894 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001895 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001896 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001897 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001898 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001899 if (user == null) {
1900 // User has been deleted remove the item.
1901 itemsToRemove.add(id);
1902 continue;
1903 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001904 try {
1905 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001906 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001907 if (cn != null && cn.getPackageName() != null) {
1908 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1909 cn.getPackageName(), user);
1910 boolean validComponent = validPkg &&
1911 launcherApps.isActivityEnabledForProfile(cn, user);
1912
1913 if (validComponent) {
1914 if (restored) {
1915 // no special handling necessary for this item
1916 restoredRows.add(id);
1917 restored = false;
1918 }
1919 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001920 intent = null;
1921 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1922 // We allow auto install apps to have their intent
1923 // updated after an install.
1924 intent = manager.getLaunchIntentForPackage(
1925 cn.getPackageName());
1926 if (intent != null) {
1927 ContentValues values = new ContentValues();
1928 values.put(LauncherSettings.Favorites.INTENT,
1929 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001930 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001931 }
1932 }
1933
1934 if (intent == null) {
1935 // The app is installed but the component is no
1936 // longer available.
1937 Launcher.addDumpLog(TAG,
1938 "Invalid component removed: " + cn, true);
1939 itemsToRemove.add(id);
1940 continue;
1941 } else {
1942 // no special handling necessary for this item
1943 restoredRows.add(id);
1944 restored = false;
1945 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001946 } else if (restored) {
1947 // Package is not yet available but might be
1948 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001949 Launcher.addDumpLog(TAG,
1950 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001951
1952 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1953 // Restore has started once.
1954 } else if (installingPkgs.contains(cn.getPackageName())) {
1955 // App restore has started. Update the flag
1956 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1957 ContentValues values = new ContentValues();
1958 values.put(LauncherSettings.Favorites.RESTORED,
1959 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001960 updateItem(id, values);
1961 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1962 // This is a common app. Try to replace this.
1963 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1964 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1965 if (parser.findDefaultApp()) {
1966 // Default app found. Replace it.
1967 intent = parser.parsedIntent;
1968 cn = intent.getComponent();
1969 ContentValues values = parser.parsedValues;
1970 values.put(LauncherSettings.Favorites.RESTORED, 0);
1971 updateItem(id, values);
1972 restored = false;
1973 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001974
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001975 } else if (REMOVE_UNRESTORED_ICONS) {
1976 Launcher.addDumpLog(TAG,
1977 "Unrestored package removed: " + cn, true);
1978 itemsToRemove.add(id);
1979 continue;
1980 }
Sunny Goyal94485362014-09-18 16:13:58 -07001981 } else if (REMOVE_UNRESTORED_ICONS) {
1982 Launcher.addDumpLog(TAG,
1983 "Unrestored package removed: " + cn, true);
1984 itemsToRemove.add(id);
1985 continue;
1986 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001987 } else if (launcherApps.isAppEnabled(
1988 manager, cn.getPackageName(),
1989 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1990 // Package is present but not available.
1991 allowMissingTarget = true;
1992 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1993 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001994 // SdCard is not ready yet. Package might get available,
1995 // once it is ready.
1996 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1997 + " (check again later)", true);
1998 HashSet<String> pkgs = sPendingPackages.get(user);
1999 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07002000 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002001 sPendingPackages.put(user, pkgs);
2002 }
2003 pkgs.add(cn.getPackageName());
2004 allowMissingTarget = true;
2005 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002006
2007 } else {
2008 // Do not wait for external media load anymore.
2009 // Log the invalid package, and remove it
2010 Launcher.addDumpLog(TAG,
2011 "Invalid package removed: " + cn, true);
2012 itemsToRemove.add(id);
2013 continue;
Winson Chungee055712013-07-30 14:46:24 -07002014 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002015 } else if (cn == null) {
2016 // For shortcuts with no component, keep them as they are
2017 restoredRows.add(id);
2018 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002019 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002020 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002021 Launcher.addDumpLog(TAG,
2022 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002023 continue;
2024 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002025
Sunny Goyal34b65272015-03-11 16:56:52 -07002026 container = c.getInt(containerIndex);
2027 boolean useLowResIcon = container >= 0 &&
2028 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2029
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002030 if (itemReplaced) {
2031 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002032 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002033 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002034 } else {
2035 // Don't replace items for other profiles.
2036 itemsToRemove.add(id);
2037 continue;
2038 }
2039 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002040 if (user.equals(UserHandleCompat.myUserHandle())) {
2041 Launcher.addDumpLog(TAG,
2042 "constructing info for partially restored package",
2043 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002044 info = getRestoredItemInfo(c, titleIndex, intent,
2045 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002046 intent = getRestoredItemIntent(c, context, intent);
2047 } else {
2048 // Don't restore items for other profiles.
2049 itemsToRemove.add(id);
2050 continue;
2051 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002052 } else if (itemType ==
2053 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002054 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002055 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002056 } else {
2057 info = getShortcutInfo(c, context, iconTypeIndex,
2058 iconPackageIndex, iconResourceIndex, iconIndex,
2059 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002060
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002061 // App shortcuts that used to be automatically added to Launcher
2062 // didn't always have the correct intent flags set, so do that
2063 // here
2064 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002065 intent.getCategories() != null &&
2066 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002067 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 intent.addFlags(
2069 Intent.FLAG_ACTIVITY_NEW_TASK |
2070 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2071 }
Michael Jurka96879562012-03-22 05:54:33 -07002072 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002073
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002075 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002077 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002078 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002079 info.cellX = c.getInt(cellXIndex);
2080 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002081 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002082 info.spanX = 1;
2083 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002084 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002085 info.isDisabled = disabledState;
2086 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2087 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2088 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002089
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002090 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002091 if (!checkItemPlacement(occupied, info)) {
2092 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002093 break;
2094 }
2095
2096 switch (container) {
2097 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2098 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2099 sBgWorkspaceItems.add(info);
2100 break;
2101 default:
2102 // Item is in a user folder
2103 FolderInfo folderInfo =
2104 findOrMakeFolder(sBgFolders, container);
2105 folderInfo.add(info);
2106 break;
2107 }
2108 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002109 } else {
2110 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002111 }
2112 break;
2113
2114 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2115 id = c.getLong(idIndex);
2116 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2117
2118 folderInfo.title = c.getString(titleIndex);
2119 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002120 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002121 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002122 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002123 folderInfo.cellX = c.getInt(cellXIndex);
2124 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002125 folderInfo.spanX = 1;
2126 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002127 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002128
Daniel Sandler8802e962010-05-26 16:28:16 -04002129 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002130 if (!checkItemPlacement(occupied, folderInfo)) {
2131 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002132 break;
2133 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002134
Joe Onorato9c1289c2009-08-17 11:03:03 -04002135 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002136 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2137 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2138 sBgWorkspaceItems.add(folderInfo);
2139 break;
Joe Onorato36115782010-06-17 13:28:48 -04002140 }
Joe Onorato17a89222011-02-08 17:26:11 -08002141
Chris Wrenf4d08112014-01-16 18:13:56 -05002142 if (restored) {
2143 // no special handling required for restored folders
2144 restoredRows.add(id);
2145 }
2146
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2148 sBgFolders.put(folderInfo.id, folderInfo);
2149 break;
2150
2151 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002152 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002153 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002154 boolean customWidget = itemType ==
2155 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2156
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002157 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002158 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002159 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002160 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002161 final ComponentName component =
2162 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002163
Sunny Goyal651077b2014-06-30 14:15:31 -07002164 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002165 final boolean isIdValid = (restoreStatus &
2166 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002167
Sunny Goyalff572272014-07-23 13:58:07 -07002168 final boolean wasProviderReady = (restoreStatus &
2169 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002170
Adam Cohen59400422014-03-05 18:07:04 -08002171 final LauncherAppWidgetProviderInfo provider =
2172 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002173 ComponentName.unflattenFromString(savedProvider),
2174 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002175
2176 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002177 if (!isSafeMode && !customWidget &&
2178 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002179 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002180 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002181
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002182 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002183 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002184 itemsToRemove.add(id);
2185 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002186 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002187 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2188 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002189
2190 if (!customWidget) {
2191 int[] minSpan =
2192 Launcher.getMinSpanForWidget(context, provider);
2193 appWidgetInfo.minSpanX = minSpan[0];
2194 appWidgetInfo.minSpanY = minSpan[1];
2195 }
Sunny Goyalff572272014-07-23 13:58:07 -07002196
2197 int status = restoreStatus;
2198 if (!wasProviderReady) {
2199 // If provider was not previously ready, update the
2200 // status and UI flag.
2201
2202 // Id would be valid only if the widget restore broadcast was received.
2203 if (isIdValid) {
2204 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2205 } else {
2206 status &= ~LauncherAppWidgetInfo
2207 .FLAG_PROVIDER_NOT_READY;
2208 }
2209 }
2210 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 } else {
2212 Log.v(TAG, "Widget restore pending id=" + id
2213 + " appWidgetId=" + appWidgetId
2214 + " status =" + restoreStatus);
2215 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002216 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002217 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002218
2219 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2220 // Restore has started once.
2221 } else if (installingPkgs.contains(component.getPackageName())) {
2222 // App restore has started. Update the flag
2223 appWidgetInfo.restoreStatus |=
2224 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002225 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002226 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002227 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002228 itemsToRemove.add(id);
2229 continue;
2230 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002231 }
Sunny Goyalff572272014-07-23 13:58:07 -07002232
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002233 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002234 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002235 appWidgetInfo.cellX = c.getInt(cellXIndex);
2236 appWidgetInfo.cellY = c.getInt(cellYIndex);
2237 appWidgetInfo.spanX = c.getInt(spanXIndex);
2238 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002239
Adam Cohen59400422014-03-05 18:07:04 -08002240 if (!customWidget) {
2241 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2242 appWidgetInfo.minSpanX = minSpan[0];
2243 appWidgetInfo.minSpanY = minSpan[1];
2244 }
2245
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002246 container = c.getInt(containerIndex);
2247 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2248 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2249 Log.e(TAG, "Widget found where container != " +
2250 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2251 continue;
2252 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002253
Adam Cohene25af792013-06-06 23:08:25 -07002254 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002255 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002256 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2257 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002258 break;
2259 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002260
Adam Cohen59400422014-03-05 18:07:04 -08002261 if (!customWidget) {
2262 String providerName =
2263 appWidgetInfo.providerName.flattenToString();
2264 if (!providerName.equals(savedProvider) ||
2265 (appWidgetInfo.restoreStatus != restoreStatus)) {
2266 ContentValues values = new ContentValues();
2267 values.put(
2268 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2269 providerName);
2270 values.put(LauncherSettings.Favorites.RESTORED,
2271 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002272 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002273 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002274 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2276 sBgAppWidgets.add(appWidgetInfo);
2277 }
Joe Onorato36115782010-06-17 13:28:48 -04002278 break;
2279 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002281 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002282 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002283 }
2284 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002285 if (c != null) {
2286 c.close();
2287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 }
2289
Winson Chungba9c37f2013-08-30 14:11:37 -07002290 // Break early if we've stopped loading
2291 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002292 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002293 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002294 }
2295
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002296 if (itemsToRemove.size() > 0) {
2297 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002298 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002299 // Remove dead items
2300 for (long id : itemsToRemove) {
2301 if (DEBUG_LOADERS) {
2302 Log.d(TAG, "Removed id = " + id);
2303 }
2304 // Don't notify content observers
2305 try {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002306 client.delete(LauncherSettings.Favorites.getContentUri(id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002307 } catch (RemoteException e) {
2308 Log.w(TAG, "Could not remove id = " + id);
2309 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002310 }
2311 }
2312
Chris Wrenf4d08112014-01-16 18:13:56 -05002313 if (restoredRows.size() > 0) {
2314 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002315 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002316 // Update restored items that no longer require special handling
2317 try {
2318 StringBuilder selectionBuilder = new StringBuilder();
2319 selectionBuilder.append(LauncherSettings.Favorites._ID);
2320 selectionBuilder.append(" IN (");
2321 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2322 selectionBuilder.append(")");
2323 ContentValues values = new ContentValues();
2324 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002325 updater.update(LauncherSettings.Favorites.CONTENT_URI,
Chris Wrenf4d08112014-01-16 18:13:56 -05002326 values, selectionBuilder.toString(), null);
2327 } catch (RemoteException e) {
2328 Log.w(TAG, "Could not update restored rows");
2329 }
2330 }
2331
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002332 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2333 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002334 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002335 null, sWorker);
2336 }
2337
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002338 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2339 // Log to disk
2340 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2341 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002342
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002343 // Remove any empty screens
2344 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2345 for (ItemInfo item: sBgItemsIdMap.values()) {
2346 long screenId = item.screenId;
2347 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2348 unusedScreens.contains(screenId)) {
2349 unusedScreens.remove(screenId);
2350 }
2351 }
2352
2353 // If there are any empty screens remove them, and update.
2354 if (unusedScreens.size() != 0) {
2355 // Log to disk
2356 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2357 TextUtils.join(", ", unusedScreens), true);
2358
2359 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002360 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002361 }
2362
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002363 if (DEBUG_LOADERS) {
2364 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2365 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002367 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002368 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002369
Daniel Sandler566da102013-06-25 23:43:45 -04002370 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002371 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002372 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002373 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002374 line += " | ";
2375 }
Winson Chung892c74d2013-08-22 16:15:50 -07002376 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002377 ItemInfo[][] screen = occupied.get(screenId);
2378 if (x < screen.length && y < screen[x].length) {
2379 line += (screen[x][y] != null) ? "#" : ".";
2380 } else {
2381 line += "!";
2382 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002383 }
Joe Onorato36115782010-06-17 13:28:48 -04002384 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002385 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002386 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002387 }
Joe Onorato36115782010-06-17 13:28:48 -04002388 }
Adam Cohene25af792013-06-06 23:08:25 -07002389 }
2390
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002391 /**
2392 * Partially updates the item without any notification. Must be called on the worker thread.
2393 */
2394 private void updateItem(long itemId, ContentValues update) {
2395 mContext.getContentResolver().update(
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002396 LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002397 update,
2398 BaseColumns._ID + "= ?",
2399 new String[]{Long.toString(itemId)});
2400 }
2401
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002402 /** Filters the set of items who are directly or indirectly (via another container) on the
2403 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002404 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002405 ArrayList<ItemInfo> allWorkspaceItems,
2406 ArrayList<ItemInfo> currentScreenItems,
2407 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002408 // Purge any null ItemInfos
2409 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2410 while (iter.hasNext()) {
2411 ItemInfo i = iter.next();
2412 if (i == null) {
2413 iter.remove();
2414 }
2415 }
2416
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002417 // Order the set of items by their containers first, this allows use to walk through the
2418 // list sequentially, build up a list of containers that are in the specified screen,
2419 // as well as all items in those containers.
2420 Set<Long> itemsOnScreen = new HashSet<Long>();
2421 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2422 @Override
2423 public int compare(ItemInfo lhs, ItemInfo rhs) {
2424 return (int) (lhs.container - rhs.container);
2425 }
2426 });
2427 for (ItemInfo info : allWorkspaceItems) {
2428 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002429 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002430 currentScreenItems.add(info);
2431 itemsOnScreen.add(info.id);
2432 } else {
2433 otherScreenItems.add(info);
2434 }
2435 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2436 currentScreenItems.add(info);
2437 itemsOnScreen.add(info.id);
2438 } else {
2439 if (itemsOnScreen.contains(info.container)) {
2440 currentScreenItems.add(info);
2441 itemsOnScreen.add(info.id);
2442 } else {
2443 otherScreenItems.add(info);
2444 }
2445 }
2446 }
2447 }
2448
2449 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002450 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 ArrayList<LauncherAppWidgetInfo> appWidgets,
2452 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2453 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002454
2455 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002456 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002458 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459 currentScreenWidgets.add(widget);
2460 } else {
2461 otherScreenWidgets.add(widget);
2462 }
2463 }
2464 }
2465
2466 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002467 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002468 HashMap<Long, ItemInfo> itemsIdMap,
2469 HashMap<Long, FolderInfo> folders,
2470 HashMap<Long, FolderInfo> currentScreenFolders,
2471 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002472
2473 for (long id : folders.keySet()) {
2474 ItemInfo info = itemsIdMap.get(id);
2475 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002476 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002477 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002478 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002479 currentScreenFolders.put(id, folder);
2480 } else {
2481 otherScreenFolders.put(id, folder);
2482 }
2483 }
2484 }
2485
2486 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2487 * right) */
2488 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002489 final LauncherAppState app = LauncherAppState.getInstance();
2490 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002491 // XXX: review this
2492 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002493 @Override
2494 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002495 int cellCountX = (int) grid.numColumns;
2496 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002497 int screenOffset = cellCountX * cellCountY;
2498 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002499 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002500 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002501 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002502 rhs.cellY * cellCountX + rhs.cellX);
2503 return (int) (lr - rr);
2504 }
2505 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002506 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002507
Adam Cohendcd297f2013-06-18 13:13:40 -07002508 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2509 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002510 final Runnable r = new Runnable() {
2511 @Override
2512 public void run() {
2513 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2514 if (callbacks != null) {
2515 callbacks.bindScreens(orderedScreens);
2516 }
2517 }
2518 };
2519 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2520 }
2521
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2523 final ArrayList<ItemInfo> workspaceItems,
2524 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2525 final HashMap<Long, FolderInfo> folders,
2526 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002527
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002528 final boolean postOnMainThread = (deferredBindRunnables != null);
2529
2530 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002531 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002532 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002533 final int start = i;
2534 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002535 final Runnable r = new Runnable() {
2536 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002537 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002538 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002539 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002540 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2541 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002542 }
2543 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544 };
2545 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002546 synchronized (deferredBindRunnables) {
2547 deferredBindRunnables.add(r);
2548 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002550 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002551 }
Joe Onorato36115782010-06-17 13:28:48 -04002552 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002553
2554 // Bind the folders
2555 if (!folders.isEmpty()) {
2556 final Runnable r = new Runnable() {
2557 public void run() {
2558 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2559 if (callbacks != null) {
2560 callbacks.bindFolders(folders);
2561 }
2562 }
2563 };
2564 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002565 synchronized (deferredBindRunnables) {
2566 deferredBindRunnables.add(r);
2567 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002568 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002569 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002570 }
2571 }
2572
2573 // Bind the widgets, one at a time
2574 N = appWidgets.size();
2575 for (int i = 0; i < N; i++) {
2576 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2577 final Runnable r = new Runnable() {
2578 public void run() {
2579 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2580 if (callbacks != null) {
2581 callbacks.bindAppWidget(widget);
2582 }
2583 }
2584 };
2585 if (postOnMainThread) {
2586 deferredBindRunnables.add(r);
2587 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002588 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002589 }
2590 }
2591 }
2592
2593 /**
2594 * Binds all loaded data to actual views on the main thread.
2595 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002596 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002597 final long t = SystemClock.uptimeMillis();
2598 Runnable r;
2599
2600 // Don't use these two variables in any of the callback runnables.
2601 // Otherwise we hold a reference to them.
2602 final Callbacks oldCallbacks = mCallbacks.get();
2603 if (oldCallbacks == null) {
2604 // This launcher has exited and nobody bothered to tell us. Just bail.
2605 Log.w(TAG, "LoaderTask running with no launcher");
2606 return;
2607 }
2608
Winson Chung9b9fb962013-11-15 15:39:34 -08002609 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002610 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2611 ArrayList<LauncherAppWidgetInfo> appWidgets =
2612 new ArrayList<LauncherAppWidgetInfo>();
2613 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2614 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002615 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002616 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002617 workspaceItems.addAll(sBgWorkspaceItems);
2618 appWidgets.addAll(sBgAppWidgets);
2619 folders.putAll(sBgFolders);
2620 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002621 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002622 }
2623
Derek Prothro7aff3992013-12-10 14:00:37 -05002624 final boolean isLoadingSynchronously =
2625 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002626 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002627 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002628 if (currScreen >= orderedScreenIds.size()) {
2629 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002630 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002631 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002632 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002633 final long currentScreenId = currentScreen < 0
2634 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002635
2636 // Load all the items that are on the current page first (and in the process, unbind
2637 // all the existing workspace items before we call startBinding() below.
2638 unbindWorkspaceItemsOnMainThread();
2639
2640 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002641 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2642 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2643 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2644 new ArrayList<LauncherAppWidgetInfo>();
2645 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2646 new ArrayList<LauncherAppWidgetInfo>();
2647 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2648 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2649
Winson Chung9b9fb962013-11-15 15:39:34 -08002650 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002651 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002652 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002654 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002655 otherFolders);
2656 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2657 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2658
2659 // Tell the workspace that we're about to start binding items
2660 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002661 public void run() {
2662 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2663 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002664 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002665 }
2666 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667 };
Winson Chung81b52252012-08-27 15:34:29 -07002668 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002669
Adam Cohendcd297f2013-06-18 13:13:40 -07002670 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2671
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 // Load items on the current page
2673 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2674 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002675 if (isLoadingSynchronously) {
2676 r = new Runnable() {
2677 public void run() {
2678 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002679 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002680 callbacks.onPageBoundSynchronously(currentScreen);
2681 }
2682 }
2683 };
Winson Chung81b52252012-08-27 15:34:29 -07002684 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002685 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002686
Winson Chung4a2afa32012-07-19 14:53:05 -07002687 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2688 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002689 synchronized (mDeferredBindRunnables) {
2690 mDeferredBindRunnables.clear();
2691 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002692 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002693 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002694
2695 // Tell the workspace that we're done binding items
2696 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002697 public void run() {
2698 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2699 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002700 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002701 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002702
Winson Chung98e030b2012-05-07 16:01:11 -07002703 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002704 if (DEBUG_LOADERS) {
2705 Log.d(TAG, "bound workspace in "
2706 + (SystemClock.uptimeMillis()-t) + "ms");
2707 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002708
2709 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002710 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002711 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002712 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002713 synchronized (mDeferredBindRunnables) {
2714 mDeferredBindRunnables.add(r);
2715 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002716 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002717 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002718 }
Joe Onorato36115782010-06-17 13:28:48 -04002719 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002720
Joe Onorato36115782010-06-17 13:28:48 -04002721 private void loadAndBindAllApps() {
2722 if (DEBUG_LOADERS) {
2723 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2724 }
2725 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002726 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002727 synchronized (LoaderTask.this) {
2728 if (mStopped) {
2729 return;
2730 }
2731 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002732 }
Joe Onorato36115782010-06-17 13:28:48 -04002733 } else {
2734 onlyBindAllApps();
2735 }
2736 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002737
Joe Onorato36115782010-06-17 13:28:48 -04002738 private void onlyBindAllApps() {
2739 final Callbacks oldCallbacks = mCallbacks.get();
2740 if (oldCallbacks == null) {
2741 // This launcher has exited and nobody bothered to tell us. Just bail.
2742 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2743 return;
2744 }
2745
2746 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002747 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002748 final ArrayList<AppInfo> list
2749 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002750 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002751 public void run() {
2752 final long t = SystemClock.uptimeMillis();
2753 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2754 if (callbacks != null) {
2755 callbacks.bindAllApplications(list);
2756 }
2757 if (DEBUG_LOADERS) {
2758 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2759 + (SystemClock.uptimeMillis()-t) + "ms");
2760 }
2761 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002762 };
2763 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002764 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002765 r.run();
2766 } else {
2767 mHandler.post(r);
2768 }
Joe Onorato36115782010-06-17 13:28:48 -04002769 }
2770
Winson Chung64359a52013-07-08 17:17:08 -07002771 private void loadAllApps() {
2772 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002773
Joe Onorato36115782010-06-17 13:28:48 -04002774 final Callbacks oldCallbacks = mCallbacks.get();
2775 if (oldCallbacks == null) {
2776 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002777 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002778 return;
2779 }
2780
2781 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2782 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2783
Kenny Guyed131872014-04-30 03:02:21 +01002784 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2785
Winson Chung64359a52013-07-08 17:17:08 -07002786 // Clear the list of apps
2787 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002788 SharedPreferences prefs = mContext.getSharedPreferences(
2789 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002790 for (UserHandleCompat user : profiles) {
2791 // Query for the set of apps
2792 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2793 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2794 if (DEBUG_LOADERS) {
2795 Log.d(TAG, "getActivityList took "
2796 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2797 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2798 }
2799 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002800 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002801 if (apps == null || apps.isEmpty()) {
2802 return;
2803 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002804
2805 // Update icon cache
2806 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2807
2808 // If any package icon has changed (app was updated while launcher was dead),
2809 // update the corresponding shortcuts.
2810 if (!updatedPackages.isEmpty()) {
2811 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2812 synchronized (sBgLock) {
2813 for (ItemInfo info : sBgItemsIdMap.values()) {
2814 if (info instanceof ShortcutInfo && user.equals(info.user)
2815 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2816 ShortcutInfo si = (ShortcutInfo) info;
2817 ComponentName cn = si.getTargetComponent();
2818 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2819 si.updateIcon(mIconCache);
2820 updates.add(si);
2821 }
2822 }
2823 }
2824 }
2825
2826 if (!updates.isEmpty()) {
2827 final UserHandleCompat userFinal = user;
2828 mHandler.post(new Runnable() {
2829
2830 public void run() {
2831 Callbacks cb = getCallback();
2832 if (cb != null) {
2833 cb.bindShortcutsChanged(
2834 updates, new ArrayList<ShortcutInfo>(), userFinal);
2835 }
2836 }
2837 });
2838 }
Kenny Guyed131872014-04-30 03:02:21 +01002839 }
Joe Onorato36115782010-06-17 13:28:48 -04002840
Kenny Guyed131872014-04-30 03:02:21 +01002841 // Create the ApplicationInfos
2842 for (int i = 0; i < apps.size(); i++) {
2843 LauncherActivityInfoCompat app = apps.get(i);
2844 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002845 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002846 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002847
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002848 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002849 // Add shortcuts for packages which were installed while launcher was dead.
2850 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2851 + mUserManager.getSerialNumberForUser(user);
2852 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2853 HashSet<String> newPackageSet = new HashSet<String>();
2854
2855 for (LauncherActivityInfoCompat info : apps) {
2856 String packageName = info.getComponentName().getPackageName();
2857 if (!packagesAdded.contains(packageName)
2858 && !newPackageSet.contains(packageName)) {
2859 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2860 }
2861 newPackageSet.add(packageName);
2862 }
2863
2864 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2865 }
Winson Chung64359a52013-07-08 17:17:08 -07002866 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002867 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002868 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2869 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002870
2871 // Post callback on main thread
2872 mHandler.post(new Runnable() {
2873 public void run() {
2874 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002875 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002876 if (callbacks != null) {
2877 callbacks.bindAllApplications(added);
2878 if (DEBUG_LOADERS) {
2879 Log.d(TAG, "bound " + added.size() + " apps in "
2880 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2881 }
2882 } else {
2883 Log.i(TAG, "not binding apps: no Launcher activity");
2884 }
2885 }
2886 });
2887
Joe Onorato36115782010-06-17 13:28:48 -04002888 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002889 Log.d(TAG, "Icons processed in "
2890 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002891 }
2892 }
2893
2894 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002895 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002896 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2897 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2898 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2899 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2900 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2901 }
Joe Onorato36115782010-06-17 13:28:48 -04002902 }
2903 }
2904
2905 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002906 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002907 }
2908
Adam Cohen091440a2015-03-18 14:16:05 -07002909 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002910
2911 @Override
2912 public void onReceive(Context context, Intent intent) {
2913 synchronized (sBgLock) {
2914 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2915 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002916 final PackageManager manager = context.getPackageManager();
2917 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2918 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002919 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2920 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002921 packagesRemoved.clear();
2922 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002923 for (String pkg : entry.getValue()) {
2924 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002925 boolean packageOnSdcard = launcherApps.isAppEnabled(
2926 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2927 if (packageOnSdcard) {
2928 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2929 packagesUnavailable.add(pkg);
2930 } else {
2931 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2932 packagesRemoved.add(pkg);
2933 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002934 }
2935 }
2936 if (!packagesRemoved.isEmpty()) {
2937 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2938 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2939 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002940 if (!packagesUnavailable.isEmpty()) {
2941 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2942 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2943 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002944 }
Sunny Goyal34942622014-08-29 17:20:55 -07002945 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002946 }
2947 }
2948 }
2949
Joe Onorato36115782010-06-17 13:28:48 -04002950 private class PackageUpdatedTask implements Runnable {
2951 int mOp;
2952 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002953 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002954
2955 public static final int OP_NONE = 0;
2956 public static final int OP_ADD = 1;
2957 public static final int OP_UPDATE = 2;
2958 public static final int OP_REMOVE = 3; // uninstlled
2959 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2960
2961
Kenny Guyed131872014-04-30 03:02:21 +01002962 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002963 mOp = op;
2964 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002965 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002966 }
2967
2968 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002969 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002970
2971 final String[] packages = mPackages;
2972 final int N = packages.length;
2973 switch (mOp) {
2974 case OP_ADD:
2975 for (int i=0; i<N; i++) {
2976 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002977 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002978 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002979 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002980
2981 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002982 if (ADD_MANAGED_PROFILE_SHORTCUTS
2983 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002984 SharedPreferences prefs = context.getSharedPreferences(
2985 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2986 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2987 + mUserManager.getSerialNumberForUser(mUser);
2988 Set<String> shortcutSet = new HashSet<String>(
2989 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2990
2991 for (int i=0; i<N; i++) {
2992 if (!shortcutSet.contains(packages[i])) {
2993 shortcutSet.add(packages[i]);
2994 List<LauncherActivityInfoCompat> activities =
2995 mLauncherApps.getActivityList(packages[i], mUser);
2996 if (activities != null && !activities.isEmpty()) {
2997 InstallShortcutReceiver.queueInstallShortcut(
2998 activities.get(0), context);
2999 }
3000 }
3001 }
3002
3003 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3004 }
Joe Onorato36115782010-06-17 13:28:48 -04003005 break;
3006 case OP_UPDATE:
3007 for (int i=0; i<N; i++) {
3008 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003009 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003010 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003011 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003012 }
3013 break;
3014 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003015 // Remove the packageName for the set of auto-installed shortcuts. This
3016 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003017 if (ADD_MANAGED_PROFILE_SHORTCUTS
3018 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003019 SharedPreferences prefs = context.getSharedPreferences(
3020 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3021 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3022 + mUserManager.getSerialNumberForUser(mUser);
3023 HashSet<String> shortcutSet = new HashSet<String>(
3024 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3025 shortcutSet.removeAll(Arrays.asList(mPackages));
3026 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3027 }
Joe Onorato36115782010-06-17 13:28:48 -04003028 for (int i=0; i<N; i++) {
3029 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003030 mIconCache.removeIconsForPkg(packages[i], mUser);
3031 }
3032 // Fall through
3033 case OP_UNAVAILABLE:
3034 for (int i=0; i<N; i++) {
3035 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3036 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003037 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003038 }
3039 break;
3040 }
3041
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003042 ArrayList<AppInfo> added = null;
3043 ArrayList<AppInfo> modified = null;
3044 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003045
Adam Cohen487f7dd2012-06-28 18:12:10 -07003046 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003047 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003048 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003049 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003050 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003051 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003052 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003053 }
Winson Chung5d55f332012-07-16 20:45:03 -07003054 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003055 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003056 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003057 }
3058
Sunny Goyale0f58d72014-11-10 18:05:31 -08003059 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003060 if (callbacks == null) {
3061 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3062 return;
3063 }
3064
Sunny Goyal4390ace2014-10-13 11:33:11 -07003065 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3066 new HashMap<ComponentName, AppInfo>();
3067
Joe Onorato36115782010-06-17 13:28:48 -04003068 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003069 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003070 for (AppInfo ai : added) {
3071 addedOrUpdatedApps.put(ai.componentName, ai);
3072 }
Joe Onorato36115782010-06-17 13:28:48 -04003073 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003074
Joe Onorato36115782010-06-17 13:28:48 -04003075 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003076 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003077 for (AppInfo ai : modified) {
3078 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003079 }
3080
Joe Onorato36115782010-06-17 13:28:48 -04003081 mHandler.post(new Runnable() {
3082 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003083 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003084 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003085 callbacks.bindAppsUpdated(modifiedFinal);
3086 }
3087 }
3088 });
3089 }
Winson Chung83892cc2013-05-01 16:53:33 -07003090
Sunny Goyal4390ace2014-10-13 11:33:11 -07003091 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003092 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003093 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3094 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3095 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3096
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003097 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003098 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003099 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003100 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3101 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003102 boolean infoUpdated = false;
3103 boolean shortcutUpdated = false;
3104
3105 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003106 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003107 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003108 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3109 si.iconResource.resourceName, mIconCache, context);
3110 if (icon != null) {
3111 si.setIcon(icon);
3112 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003113 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003114 }
3115 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003116
3117 ComponentName cn = si.getTargetComponent();
3118 if (cn != null && packageSet.contains(cn.getPackageName())) {
3119 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3120
3121 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003122 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3123 // Auto install icon
3124 PackageManager pm = context.getPackageManager();
3125 ResolveInfo matched = pm.resolveActivity(
3126 new Intent(Intent.ACTION_MAIN)
3127 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3128 PackageManager.MATCH_DEFAULT_ONLY);
3129 if (matched == null) {
3130 // Try to find the best match activity.
3131 Intent intent = pm.getLaunchIntentForPackage(
3132 cn.getPackageName());
3133 if (intent != null) {
3134 cn = intent.getComponent();
3135 appInfo = addedOrUpdatedApps.get(cn);
3136 }
3137
3138 if ((intent == null) || (appInfo == null)) {
3139 removedShortcuts.add(si);
3140 continue;
3141 }
3142 si.promisedIntent = intent;
3143 }
3144 }
3145
3146 // Restore the shortcut.
3147 si.intent = si.promisedIntent;
3148 si.promisedIntent = null;
3149 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3150 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3151 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3152
3153 infoUpdated = true;
3154 si.updateIcon(mIconCache);
3155 }
3156
3157 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3158 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3159 si.updateIcon(mIconCache);
3160 si.title = appInfo.title.toString();
3161 si.contentDescription = appInfo.contentDescription;
3162 infoUpdated = true;
3163 }
3164
3165 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3166 // Since package was just updated, the target must be available now.
3167 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3168 shortcutUpdated = true;
3169 }
3170 }
3171
3172 if (infoUpdated || shortcutUpdated) {
3173 updatedShortcuts.add(si);
3174 }
3175 if (infoUpdated) {
3176 updateItemInDatabase(context, si);
3177 }
3178 } else if (info instanceof LauncherAppWidgetInfo) {
3179 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3180 if (mUser.equals(widgetInfo.user)
3181 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3182 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3183 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3184 widgets.add(widgetInfo);
3185 updateItemInDatabase(context, widgetInfo);
3186 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003187 }
3188 }
3189 }
3190
Sunny Goyal4390ace2014-10-13 11:33:11 -07003191 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3192 mHandler.post(new Runnable() {
3193
3194 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003195 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003196 if (callbacks == cb && cb != null) {
3197 callbacks.bindShortcutsChanged(
3198 updatedShortcuts, removedShortcuts, mUser);
3199 }
3200 }
3201 });
3202 if (!removedShortcuts.isEmpty()) {
3203 deleteItemsFromDatabase(context, removedShortcuts);
3204 }
3205 }
3206 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003207 mHandler.post(new Runnable() {
3208 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003209 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003210 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003211 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003212 }
3213 }
3214 });
3215 }
3216 }
3217
Winson Chungdf95eb12013-10-16 14:57:07 -07003218 final ArrayList<String> removedPackageNames =
3219 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003220 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003221 // Mark all packages in the broadcast to be removed
3222 removedPackageNames.addAll(Arrays.asList(packages));
3223 } else if (mOp == OP_UPDATE) {
3224 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003225 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003226 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003227 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003228 }
3229 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003230 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003231
Winson Chungdf95eb12013-10-16 14:57:07 -07003232 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003233 final int removeReason;
3234 if (mOp == OP_UNAVAILABLE) {
3235 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3236 } else {
3237 // Remove all the components associated with this package
3238 for (String pn : removedPackageNames) {
3239 deletePackageFromDatabase(context, pn, mUser);
3240 }
3241 // Remove all the specific components
3242 for (AppInfo a : removedApps) {
3243 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3244 deleteItemsFromDatabase(context, infos);
3245 }
3246 removeReason = 0;
3247 }
3248
Winson Chungdf95eb12013-10-16 14:57:07 -07003249 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003250 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003251 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003252 mHandler.post(new Runnable() {
3253 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003254 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003255 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003256 callbacks.bindComponentsRemoved(
3257 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003258 }
3259 }
3260 });
Joe Onoratobe386092009-11-17 17:32:16 -08003261 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003262
Michael Jurkac402cd92013-05-20 15:49:32 +02003263 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003264 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003265 mHandler.post(new Runnable() {
3266 @Override
3267 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003268 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003269 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003270 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003271 }
3272 }
3273 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003274
3275 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003276 mHandler.post(new Runnable() {
3277 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003278 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003279 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003280 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003281 }
3282 }
3283 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003284 }
3285 }
3286
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003287 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3288 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003289 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003290 if (sBgWidgetProviders == null || refresh) {
3291 sBgWidgetProviders = new HashMap<>();
3292 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3293 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003294
Robin Lee26ace122015-03-16 19:41:43 +00003295 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3296 for (AppWidgetProviderInfo pInfo : widgets) {
3297 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3298 UserHandleCompat user = wm.getUser(info);
3299 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3300 }
3301
3302 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3303 for (CustomAppWidget widget : customWidgets) {
3304 info = new LauncherAppWidgetProviderInfo(context, widget);
3305 UserHandleCompat user = wm.getUser(info);
3306 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3307 }
Adam Cohen59400422014-03-05 18:07:04 -08003308 }
Adam Cohen59400422014-03-05 18:07:04 -08003309 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3310 }
3311 }
3312
Robin Lee26ace122015-03-16 19:41:43 +00003313 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3314 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003315 synchronized (sBgLock) {
3316 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003317 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003318 }
Robin Lee26ace122015-03-16 19:41:43 +00003319 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003320 }
3321 }
3322
Winson Chungb745afb2015-03-02 11:51:23 -08003323 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003324 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003325 PackageManager packageManager = context.getPackageManager();
3326 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003327 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003328 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3329 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003330 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003331 return widgetsAndShortcuts;
3332 }
3333
Adam Cohen091440a2015-03-18 14:16:05 -07003334 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003335 UserHandleCompat user) {
3336 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3337 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003338 }
Adam Cohen556f6132014-01-15 15:18:08 -08003339
Kenny Guyed131872014-04-30 03:02:21 +01003340 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3341 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003342 if (cn == null) {
3343 return false;
3344 }
Kenny Guyed131872014-04-30 03:02:21 +01003345 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3346 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003347 return false;
3348 }
Kenny Guyed131872014-04-30 03:02:21 +01003349 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003350 }
3351
Adam Cohena28b78e2014-05-20 17:03:04 -07003352 public static boolean isValidPackage(Context context, String packageName,
3353 UserHandleCompat user) {
3354 if (packageName == null) {
3355 return false;
3356 }
3357 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3358 return launcherApps.isPackageEnabledForProfile(packageName, user);
3359 }
3360
Joe Onorato9c1289c2009-08-17 11:03:03 -04003361 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003362 * Make an ShortcutInfo object for a restored application or shortcut item that points
3363 * to a package that is not yet installed on the system.
3364 */
Sunny Goyal34942622014-08-29 17:20:55 -07003365 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003366 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003367 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003368 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003369 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003370
3371 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3372 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3373 if (!TextUtils.isEmpty(title)) {
3374 info.title = title;
3375 }
3376 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3377 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3378 if (TextUtils.isEmpty(info.title)) {
3379 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3380 }
3381 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3382 } else {
3383 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3384 }
3385
Kenny Guyc2bd8102014-06-30 12:30:31 +01003386 info.contentDescription = mUserManager.getBadgedLabelForUser(
3387 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003388 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003389 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003390 return info;
3391 }
3392
3393 /**
3394 * Make an Intent object for a restored application or shortcut item that points
3395 * to the market page for the item.
3396 */
Adam Cohen091440a2015-03-18 14:16:05 -07003397 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003398 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003399 return getMarketIntent(componentName.getPackageName());
3400 }
3401
3402 static Intent getMarketIntent(String packageName) {
3403 return new Intent(Intent.ACTION_VIEW)
3404 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003405 .scheme("market")
3406 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003407 .appendQueryParameter("id", packageName)
3408 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003409 }
3410
3411 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003412 * Make an ShortcutInfo object for a shortcut that is an application.
3413 *
3414 * If c is not null, then it will be used to fill in missing data like the title and icon.
3415 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003416 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003417 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003418 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003419 if (user == null) {
3420 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003421 return null;
3422 }
3423
Kenny Guyed131872014-04-30 03:02:21 +01003424 ComponentName componentName = intent.getComponent();
3425 if (componentName == null) {
3426 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3427 return null;
3428 }
3429
3430 Intent newIntent = new Intent(intent.getAction(), null);
3431 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3432 newIntent.setComponent(componentName);
3433 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003434 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003435 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3436 return null;
3437 }
3438
3439 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003440 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003441 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3442 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3443 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003444 }
3445
Joe Onorato56d82912010-03-07 14:32:10 -05003446 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003447 if (TextUtils.isEmpty(info.title) && c != null) {
3448 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003449 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003450
Joe Onorato56d82912010-03-07 14:32:10 -05003451 // fall back to the class name of the activity
3452 if (info.title == null) {
3453 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003454 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003455
Joe Onorato9c1289c2009-08-17 11:03:03 -04003456 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003457 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003458 info.contentDescription = mUserManager.getBadgedLabelForUser(
3459 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003460 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003461 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003462
Winson Chung64359a52013-07-08 17:17:08 -07003463 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3464 ItemInfoFilter f) {
3465 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3466 for (ItemInfo i : infos) {
3467 if (i instanceof ShortcutInfo) {
3468 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003469 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003470 if (cn != null && f.filterItem(null, info, cn)) {
3471 filtered.add(info);
3472 }
3473 } else if (i instanceof FolderInfo) {
3474 FolderInfo info = (FolderInfo) i;
3475 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003476 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003477 if (cn != null && f.filterItem(info, s, cn)) {
3478 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003479 }
3480 }
Winson Chung64359a52013-07-08 17:17:08 -07003481 } else if (i instanceof LauncherAppWidgetInfo) {
3482 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3483 ComponentName cn = info.providerName;
3484 if (cn != null && f.filterItem(null, info, cn)) {
3485 filtered.add(info);
3486 }
Winson Chung8a435102012-08-30 17:16:53 -07003487 }
3488 }
Winson Chung64359a52013-07-08 17:17:08 -07003489 return new ArrayList<ItemInfo>(filtered);
3490 }
3491
Adam Cohen091440a2015-03-18 14:16:05 -07003492 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003493 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003494 ItemInfoFilter filter = new ItemInfoFilter() {
3495 @Override
3496 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003497 if (info.user == null) {
3498 return cn.equals(cname);
3499 } else {
3500 return cn.equals(cname) && info.user.equals(user);
3501 }
Winson Chung64359a52013-07-08 17:17:08 -07003502 }
3503 };
3504 return filterItemInfos(sBgItemsIdMap.values(), filter);
3505 }
3506
Sunny Goyal1a745e82014-10-02 15:58:31 -07003507 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003508 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003509 */
Adam Cohen091440a2015-03-18 14:16:05 -07003510 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003511 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3512 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003513
Joe Onorato56d82912010-03-07 14:32:10 -05003514 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003515 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003516 // Non-app shortcuts are only supported for current user.
3517 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003518 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003519
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003520 // TODO: If there's an explicit component and we can't install that, delete it.
3521
Joe Onorato56d82912010-03-07 14:32:10 -05003522 info.title = c.getString(titleIndex);
3523
Joe Onorato9c1289c2009-08-17 11:03:03 -04003524 int iconType = c.getInt(iconTypeIndex);
3525 switch (iconType) {
3526 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3527 String packageName = c.getString(iconPackageIndex);
3528 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003529 info.customIcon = false;
3530 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003531 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003532 // the db
3533 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003534 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003535 }
3536 // the fallback icon
3537 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003538 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003539 info.usingFallbackIcon = true;
3540 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003541 break;
3542 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003543 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003544 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003545 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003546 info.customIcon = false;
3547 info.usingFallbackIcon = true;
3548 } else {
3549 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003550 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003551 break;
3552 default:
Kenny Guyed131872014-04-30 03:02:21 +01003553 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003554 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003555 info.customIcon = false;
3556 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003557 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003558 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003559 return info;
3560 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003561
Sunny Goyal2350bc92014-10-14 16:42:54 -07003562 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003563 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3564 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3565 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3566
Adam Cohend9198822011-11-22 16:42:47 -08003567 if (intent == null) {
3568 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3569 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3570 return null;
3571 }
3572
Joe Onorato0589f0f2010-02-08 13:44:00 -08003573 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003574 boolean customIcon = false;
3575 ShortcutIconResource iconResource = null;
3576
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003577 if (bitmap instanceof Bitmap) {
3578 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003579 customIcon = true;
3580 } else {
3581 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003582 if (extra instanceof ShortcutIconResource) {
3583 iconResource = (ShortcutIconResource) extra;
3584 icon = Utilities.createIconBitmap(iconResource.packageName,
3585 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003586 }
3587 }
3588
Michael Jurkac9d95c52011-08-29 14:03:34 -07003589 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003590
Kenny Guyed131872014-04-30 03:02:21 +01003591 // Only support intents for current user for now. Intents sent from other
3592 // users wouldn't get here without intent forwarding anyway.
3593 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003594 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003595 icon = mIconCache.getDefaultIcon(info.user);
3596 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003597 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003598 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003599
Joe Onorato0589f0f2010-02-08 13:44:00 -08003600 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003601 info.contentDescription = mUserManager.getBadgedLabelForUser(
3602 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003603 info.intent = intent;
3604 info.customIcon = customIcon;
3605 info.iconResource = iconResource;
3606
3607 return info;
3608 }
3609
Joe Onorato9c1289c2009-08-17 11:03:03 -04003610 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003611 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003612 * or make a new one.
3613 */
Adam Cohen091440a2015-03-18 14:16:05 -07003614 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003615 // See if a placeholder was created for us already
3616 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003617 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003618 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003619 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003620 folders.put(id, folderInfo);
3621 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003622 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003623 }
3624
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003625 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003626 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003627 return new Comparator<AppInfo>() {
3628 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003629 if (a.user.equals(b.user)) {
3630 int result = collator.compare(a.title.toString().trim(),
3631 b.title.toString().trim());
3632 if (result == 0) {
3633 result = a.componentName.compareTo(b.componentName);
3634 }
3635 return result;
3636 } else {
3637 // TODO Need to figure out rules for sorting
3638 // profiles, this puts work second.
3639 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003640 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003641 }
Winson Chung11904872012-09-17 16:58:46 -07003642 };
3643 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003644 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3645 = new Comparator<AppInfo>() {
3646 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003647 if (a.firstInstallTime < b.firstInstallTime) return 1;
3648 if (a.firstInstallTime > b.firstInstallTime) return -1;
3649 return 0;
3650 }
3651 };
Winson Chung5308f242011-08-18 12:12:41 -07003652 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3653 if (info.activityInfo != null) {
3654 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3655 } else {
3656 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3657 }
3658 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003659
Winson Chung1ed747a2011-05-03 16:18:34 -07003660 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003661 private final AppWidgetManagerCompat mManager;
3662 private final PackageManager mPackageManager;
3663 private final HashMap<Object, String> mLabelCache;
3664 private final Collator mCollator;
3665
3666 WidgetAndShortcutNameComparator(Context context) {
3667 mManager = AppWidgetManagerCompat.getInstance(context);
3668 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003669 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003670 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003671 }
3672 public final int compare(Object a, Object b) {
3673 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003674 if (mLabelCache.containsKey(a)) {
3675 labelA = mLabelCache.get(a);
3676 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003677 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3678 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003679 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003680 mLabelCache.put(a, labelA);
3681 }
3682 if (mLabelCache.containsKey(b)) {
3683 labelB = mLabelCache.get(b);
3684 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003685 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c1652015-01-30 10:28:23 -08003686 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003687 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003688 mLabelCache.put(b, labelB);
3689 }
Winson Chung11904872012-09-17 16:58:46 -07003690 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003691 }
3692 };
Joe Onoratobe386092009-11-17 17:32:16 -08003693
Sunny Goyal651077b2014-06-30 14:15:31 -07003694 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3695 return (provider != null) && (provider.provider != null)
3696 && (provider.provider.getPackageName() != null);
3697 }
3698
Joe Onoratobe386092009-11-17 17:32:16 -08003699 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003700 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003701 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3702 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3703 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3704 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003705 if (mLoaderTask != null) {
3706 mLoaderTask.dumpState();
3707 } else {
3708 Log.d(TAG, "mLoaderTask=null");
3709 }
Joe Onoratobe386092009-11-17 17:32:16 -08003710 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003711
3712 public Callbacks getCallback() {
3713 return mCallbacks != null ? mCallbacks.get() : null;
3714 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003715}