blob: e5561e219114f17d8f800a19824ed03a7d445951 [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;
Hyunyoung Songd4af1482015-04-20 20:40:03 -070041import android.os.Build;
Joe Onorato17a89222011-02-08 17:26:11 -080042import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040043import android.os.Handler;
44import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080045import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040048import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040049import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080050import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070051import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080052import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070053import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010056import com.android.launcher3.compat.LauncherActivityInfoCompat;
57import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070058import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070059import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010060import com.android.launcher3.compat.UserHandleCompat;
61import com.android.launcher3.compat.UserManagerCompat;
Robin Lee26ace122015-03-16 19:41:43 +000062import com.android.launcher3.util.ComponentKey;
Sunny Goyal18bf8e22015-04-08 18:13:46 -070063import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Romain Guyedcce092010-03-04 13:03:17 -080065
Michael Jurkac2f801e2011-07-12 14:19:46 -070066import java.lang.ref.WeakReference;
67import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070068import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070069import java.text.Collator;
70import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070071import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070072import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070073import java.util.Collections;
74import java.util.Comparator;
75import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070076import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070077import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070079import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070080import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070081
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082/**
83 * Maintains in-memory state of the Launcher. It is expected that there should be only one
84 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070085 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 */
Kenny Guyed131872014-04-30 03:02:21 +010087public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010088 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080089 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040090 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070091 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Chris Wrenb358f812014-04-16 13:37:00 -040092
Joe Onorato9c1289c2009-08-17 11:03:03 -040093 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070094
Dan Sandlerd5024042014-01-09 15:01:33 -050095 public static final int LOADER_FLAG_NONE = 0;
96 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
97 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
98
Joe Onorato36115782010-06-17 13:28:48 -040099 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500100 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800101
Adam Cohen091440a2015-03-18 14:16:05 -0700102 @Thunk final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800103 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400104
Adam Cohen091440a2015-03-18 14:16:05 -0700105 @Thunk final LauncherAppState mApp;
106 @Thunk final Object mLock = new Object();
107 @Thunk DeferredHandler mHandler = new DeferredHandler();
108 @Thunk LoaderTask mLoaderTask;
109 @Thunk boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
Winson Chung81b52252012-08-27 15:34:29 -0700111 // Specific runnable types that are run on the main thread deferred handler, this allows us to
112 // clear all queued binding runnables when the Launcher activity is destroyed.
113 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
114 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
115
Jason Monkbbe1e242014-05-16 17:37:34 -0400116 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700117
Adam Cohen091440a2015-03-18 14:16:05 -0700118 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700119 static {
120 sWorkerThread.start();
121 }
Adam Cohen091440a2015-03-18 14:16:05 -0700122 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700123
Joe Onoratocc67f472010-06-08 10:54:30 -0700124 // We start off with everything not loaded. After that, we assume that
125 // our monitoring of the package manager provides all updates and we never
126 // need to do a requery. These are only ever touched from the loader thread.
Adam Cohen091440a2015-03-18 14:16:05 -0700127 @Thunk boolean mWorkspaceLoaded;
128 @Thunk boolean mAllAppsLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700129
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700130 // When we are loading pages synchronously, we can't just post the binding of items on the side
131 // pages as this delays the rotation process. Instead, we wait for a callback from the first
132 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
133 // a normal load, we also clear this set of Runnables.
134 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
135
Adam Cohen091440a2015-03-18 14:16:05 -0700136 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700138 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700139 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800140
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700141 // The lock that must be acquired before referencing any static bg data structures. Unlike
142 // other locks, this one can generally be held long-term because we never expect any of these
143 // static data structures to be referenced outside of the worker thread except on the first
144 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700145 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700146
Adam Cohen487f7dd2012-06-28 18:12:10 -0700147 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700148 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700149 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700150
Adam Cohen487f7dd2012-06-28 18:12:10 -0700151 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
152 // created by LauncherModel that are directly on the home screen (however, no widgets or
153 // shortcuts within folders).
154 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700155
Adam Cohen487f7dd2012-06-28 18:12:10 -0700156 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
157 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158 new ArrayList<LauncherAppWidgetInfo>();
159
Adam Cohen487f7dd2012-06-28 18:12:10 -0700160 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
161 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700162
Adam Cohendcd297f2013-06-18 13:13:40 -0700163 // sBgWorkspaceScreens is the ordered set of workspace screens.
164 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
165
Adam Cohen59400422014-03-05 18:07:04 -0800166 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000167 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800168
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700169 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700170 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
171 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700172
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 // </ only access in worker thread >
174
Adam Cohen091440a2015-03-18 14:16:05 -0700175 @Thunk IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
Reena Lee99a73f32011-10-24 17:27:37 -0700177 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700178
Adam Cohen091440a2015-03-18 14:16:05 -0700179 @Thunk final LauncherAppsCompat mLauncherApps;
180 @Thunk final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100181
Joe Onorato9c1289c2009-08-17 11:03:03 -0400182 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700183 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400184 public int getCurrentWorkspaceScreen();
185 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700186 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
187 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700188 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700189 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500190 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800191 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400192 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200193 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700194 public void bindAppsAdded(ArrayList<Long> newScreens,
195 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700196 ArrayList<ItemInfo> addAnimated,
197 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200198 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700199 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
200 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
201 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700202 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700203 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700204 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700205 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200206 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100207 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700208 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700209 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700210 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800211 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
212 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400213 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214
Winson Chung64359a52013-07-08 17:17:08 -0700215 public interface ItemInfoFilter {
216 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
217 }
218
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800219 public interface ScreenPosProvider {
220 int getScreenIndex(ArrayList<Long> screenIDs);
221 }
222
Bjorn Bringert1307f632013-10-03 22:31:03 +0100223 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800224 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400225
Winson Chungee055712013-07-30 14:46:24 -0700226 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700227 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400228 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
229 // resource string.
230 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
231 ProviderInfo providerInfo =
232 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
233 ProviderInfo redirectProvider =
234 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700235
236 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400237 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700238
239 if (mOldContentProviderExists) {
240 Log.d(TAG, "Old launcher provider exists.");
241 } else {
242 Log.d(TAG, "Old launcher provider does not exist.");
243 }
244
Daniel Sandlere4f98912013-06-25 15:13:26 -0400245 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100246 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800247 mIconCache = iconCache;
248
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400249 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700250 Configuration config = res.getConfiguration();
251 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100252 mLauncherApps = LauncherAppsCompat.getInstance(context);
253 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800254 }
255
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700256 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
257 * posted on the main thread handler. */
Adam Cohen091440a2015-03-18 14:16:05 -0700258 @Thunk void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700259 runOnMainThread(r, 0);
260 }
Adam Cohen091440a2015-03-18 14:16:05 -0700261 @Thunk void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700262 if (sWorkerThread.getThreadId() == Process.myTid()) {
263 // If we are on the worker thread, post onto the main handler
264 mHandler.post(r);
265 } else {
266 r.run();
267 }
268 }
269
270 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
271 * posted on the worker thread handler. */
272 private static void runOnWorkerThread(Runnable r) {
273 if (sWorkerThread.getThreadId() == Process.myTid()) {
274 r.run();
275 } else {
276 // If we are not on the worker thread, then post to the worker handler
277 sWorker.post(r);
278 }
279 }
280
Winson Chunge43a1e72014-01-15 10:33:02 -0800281 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
282 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800283 }
284
Sunny Goyale755d462014-07-22 13:48:29 -0700285 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500286 // Process the updated package state
287 Runnable r = new Runnable() {
288 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800289 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500290 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700291 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500292 }
293 }
294 };
295 mHandler.post(r);
296 }
297
Sunny Goyala22666f2014-09-18 13:25:15 -0700298 public void updatePackageBadge(final String packageName) {
299 // Process the updated package badge
300 Runnable r = new Runnable() {
301 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800302 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700303 if (callbacks != null) {
304 callbacks.updatePackageBadge(packageName);
305 }
306 }
307 };
308 mHandler.post(r);
309 }
310
Adam Cohen76a47a12014-02-05 11:47:43 -0800311 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800312 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800313
314 if (allAppsApps == null) {
315 throw new RuntimeException("allAppsApps must not be null");
316 }
317 if (allAppsApps.isEmpty()) {
318 return;
319 }
320
321 // Process the newly added applications and add them to the database first
322 Runnable r = new Runnable() {
323 public void run() {
324 runOnMainThread(new Runnable() {
325 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800326 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800327 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500328 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800329 }
330 }
331 });
332 }
333 };
334 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700335 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800336
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700337 public void addAndBindAddedWorkspaceItems(final Context context,
Adam Cohen76a47a12014-02-05 11:47:43 -0800338 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700339 addAndBindAddedWorkspaceItems(context, workspaceApps,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800340 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800341
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800342 @Override
343 public int getScreenIndex(ArrayList<Long> screenIDs) {
344 return screenIDs.isEmpty() ? 0 : 1;
345 }
346 }, 1, false);
347 }
348
349 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
350 int[] xy, int spanX, int spanY) {
351 LauncherAppState app = LauncherAppState.getInstance();
352 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
353 final int xCount = (int) grid.numColumns;
354 final int yCount = (int) grid.numRows;
355 boolean[][] occupied = new boolean[xCount][yCount];
356 if (occupiedPos != null) {
357 for (Rect r : occupiedPos) {
358 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
359 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
360 occupied[x][y] = true;
361 }
362 }
363 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800364 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800365 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
366 }
367
368 /**
369 * Find a position on the screen for the given size or adds a new screen.
370 * @return screenId and the coordinates for the item.
371 */
Adam Cohen091440a2015-03-18 14:16:05 -0700372 @Thunk static Pair<Long, int[]> findSpaceForItem(
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800373 Context context,
374 ScreenPosProvider preferredScreen,
375 int fallbackStartScreen,
376 ArrayList<Long> workspaceScreens,
377 ArrayList<Long> addedWorkspaceScreensFinal,
378 int spanX, int spanY) {
379 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
380 // loadWorkspace() may not have been called.
381 final ContentResolver cr = context.getContentResolver();
382 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
383 new String[] {
384 LauncherSettings.Favorites.SCREEN,
385 LauncherSettings.Favorites.CELLX,
386 LauncherSettings.Favorites.CELLY,
387 LauncherSettings.Favorites.SPANX,
388 LauncherSettings.Favorites.SPANY,
389 LauncherSettings.Favorites.CONTAINER
390 },
391 "container=?",
392 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
393 null);
394
395 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
396 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
397 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
398 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
399 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
400 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
401 try {
402 while (c.moveToNext()) {
403 Rect rect = new Rect();
404 rect.left = c.getInt(cellXIndex);
405 rect.top = c.getInt(cellYIndex);
406 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
407 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
408
409 long screenId = c.getInt(screenIndex);
410 ArrayList<Rect> items = screenItems.get(screenId);
411 if (items == null) {
412 items = new ArrayList<Rect>();
413 screenItems.put(screenId, items);
414 }
415 items.add(rect);
416 }
417 } catch (Exception e) {
418 screenItems.clear();
419 } finally {
420 c.close();
421 }
422
423 // Find appropriate space for the item.
424 long screenId = 0;
425 int[] cordinates = new int[2];
426 boolean found = false;
427
428 int screenCount = workspaceScreens.size();
429 // First check the preferred screen.
430 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
431 if (preferredScreenIndex < screenCount) {
432 screenId = workspaceScreens.get(preferredScreenIndex);
433 found = findNextAvailableIconSpaceInScreen(
434 screenItems.get(screenId), cordinates, spanX, spanY);
435 }
436
437 if (!found) {
438 // Search on any of the screens.
439 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
440 screenId = workspaceScreens.get(screen);
441 if (findNextAvailableIconSpaceInScreen(
442 screenItems.get(screenId), cordinates, spanX, spanY)) {
443 // We found a space for it
444 found = true;
445 break;
446 }
447 }
448 }
449
450 if (!found) {
451 // Still no position found. Add a new screen to the end.
452 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
453
454 // Save the screen id for binding in the workspace
455 workspaceScreens.add(screenId);
456 addedWorkspaceScreensFinal.add(screenId);
457
458 // If we still can't find an empty space, then God help us all!!!
459 if (!findNextAvailableIconSpaceInScreen(
460 screenItems.get(screenId), cordinates, spanX, spanY)) {
461 throw new RuntimeException("Can't find space to add the item");
462 }
463 }
464 return Pair.create(screenId, cordinates);
465 }
466
467 /**
468 * Adds the provided items to the workspace.
469 * @param preferredScreen the screen where we should try to add the app first
470 * @param fallbackStartScreen the screen to start search for empty space if
471 * preferredScreen is not available.
472 */
473 public void addAndBindPendingItem(
474 final Context context,
475 final PendingAddItemInfo addInfo,
476 final ScreenPosProvider preferredScreen,
477 final int fallbackStartScreen) {
478 final Callbacks callbacks = getCallback();
479 // Process the newly added applications and add them to the database first
480 Runnable r = new Runnable() {
481 public void run() {
482 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800483 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800484
485 // Find appropriate space for the item.
486 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
487 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
488 addInfo.spanX,
489 addInfo.spanY);
490 final long screenId = coords.first;
491 final int[] cordinates = coords.second;
492
493 // Update the workspace screens
494 updateWorkspaceScreenOrder(context, workspaceScreens);
495 runOnMainThread(new Runnable() {
496 public void run() {
497 Callbacks cb = getCallback();
498 if (callbacks == cb && cb != null) {
499 cb.bindAddScreens(addedWorkspaceScreensFinal);
500 cb.bindAddPendingItem(addInfo,
501 LauncherSettings.Favorites.CONTAINER_DESKTOP,
502 screenId, cordinates, addInfo.spanX, addInfo.spanY);
503 }
504 }
505 });
506 }
507 };
508 runOnWorkerThread(r);
509 }
510
511 /**
512 * Adds the provided items to the workspace.
513 * @param preferredScreen the screen where we should try to add the app first
514 * @param fallbackStartScreen the screen to start search for empty space if
515 * preferredScreen is not available.
516 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700517 public void addAndBindAddedWorkspaceItems(final Context context,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800518 final ArrayList<ItemInfo> workspaceApps,
519 final ScreenPosProvider preferredScreen,
520 final int fallbackStartScreen,
521 final boolean allowDuplicate) {
522 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800523 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700524 return;
Winson Chung997a9232013-07-24 15:33:46 -0700525 }
Winson Chung64359a52013-07-08 17:17:08 -0700526 // Process the newly added applications and add them to the database first
527 Runnable r = new Runnable() {
528 public void run() {
529 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
530 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
531
Winson Chung76828c82013-08-19 15:43:29 -0700532 // Get the list of workspace screens. We need to append to this list and
533 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
534 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800535 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700536 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800537 for (ItemInfo item : workspaceApps) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700538 if (!allowDuplicate && item instanceof ShortcutInfo) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800539 // Short-circuit this logic if the icon exists somewhere on the workspace
540 if (shortcutExists(context, item.title.toString(),
541 item.getIntent(), item.user)) {
542 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700543 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800544 }
Winson Chung76828c82013-08-19 15:43:29 -0700545
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800546 // Find appropriate space for the item.
547 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
548 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
549 1, 1);
550 long screenId = coords.first;
551 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700552
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700553 ItemInfo itemInfo;
554 if (item instanceof ShortcutInfo || item instanceof FolderInfo) {
555 itemInfo = item;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800556 } else if (item instanceof AppInfo) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700557 itemInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700558 } else {
559 throw new RuntimeException("Unexpected info type");
560 }
Winson Chung94d67682013-09-25 16:29:40 -0700561
Winson Chung64359a52013-07-08 17:17:08 -0700562 // Add the shortcut to the db
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700563 addItemToDatabase(context, itemInfo,
Winson Chung64359a52013-07-08 17:17:08 -0700564 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700565 screenId, cordinates[0], cordinates[1]);
Winson Chung64359a52013-07-08 17:17:08 -0700566 // Save the ShortcutInfo for binding in the workspace
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700567 addedShortcutsFinal.add(itemInfo);
Winson Chung64359a52013-07-08 17:17:08 -0700568 }
569 }
570
Winson Chung76828c82013-08-19 15:43:29 -0700571 // Update the workspace screens
572 updateWorkspaceScreenOrder(context, workspaceScreens);
573
Adam Cohen76a47a12014-02-05 11:47:43 -0800574 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700575 runOnMainThread(new Runnable() {
576 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800577 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700578 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700579 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
580 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700581 if (!addedShortcutsFinal.isEmpty()) {
582 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
583 long lastScreenId = info.screenId;
584 for (ItemInfo i : addedShortcutsFinal) {
585 if (i.screenId == lastScreenId) {
586 addAnimated.add(i);
587 } else {
588 addNotAnimated.add(i);
589 }
Winson Chung997a9232013-07-24 15:33:46 -0700590 }
591 }
Winson Chungd64d1762013-08-20 14:37:16 -0700592 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800593 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700594 }
Winson Chung64359a52013-07-08 17:17:08 -0700595 }
Winson Chung997a9232013-07-24 15:33:46 -0700596 });
597 }
Winson Chung64359a52013-07-08 17:17:08 -0700598 }
599 };
600 runOnWorkerThread(r);
601 }
602
Winson Chung81b52252012-08-27 15:34:29 -0700603 public void unbindItemInfosAndClearQueuedBindRunnables() {
604 if (sWorkerThread.getThreadId() == Process.myTid()) {
605 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
606 "main thread");
607 }
608
609 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400610 synchronized (mDeferredBindRunnables) {
611 mDeferredBindRunnables.clear();
612 }
Winson Chung81b52252012-08-27 15:34:29 -0700613 // Remove any queued bind runnables
614 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
615 // Unbind all the workspace items
616 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700617 }
618
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700619 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700620 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700621 // Ensure that we don't use the same workspace items data structure on the main thread
622 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700623 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
624 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700625 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700626 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
627 tmpAppWidgets.addAll(sBgAppWidgets);
628 }
629 Runnable r = new Runnable() {
630 @Override
631 public void run() {
632 for (ItemInfo item : tmpWorkspaceItems) {
633 item.unbind();
634 }
635 for (ItemInfo item : tmpAppWidgets) {
636 item.unbind();
637 }
638 }
639 };
640 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700641 }
642
Joe Onorato9c1289c2009-08-17 11:03:03 -0400643 /**
644 * Adds an item to the DB if it was not created previously, or move it to a new
645 * <container, screen, cellX, cellY>
646 */
647 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700648 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400649 if (item.container == ItemInfo.NO_ID) {
650 // From all apps
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700651 addItemToDatabase(context, item, container, screenId, cellX, cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400652 } else {
653 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700654 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800655 }
656 }
657
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700658 static void checkItemInfoLocked(
659 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
660 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
661 if (modelItem != null && item != modelItem) {
662 // check all the data is consistent
663 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
664 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
665 ShortcutInfo shortcut = (ShortcutInfo) item;
666 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
667 modelShortcut.intent.filterEquals(shortcut.intent) &&
668 modelShortcut.id == shortcut.id &&
669 modelShortcut.itemType == shortcut.itemType &&
670 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700671 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700672 modelShortcut.cellX == shortcut.cellX &&
673 modelShortcut.cellY == shortcut.cellY &&
674 modelShortcut.spanX == shortcut.spanX &&
675 modelShortcut.spanY == shortcut.spanY &&
676 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
677 (modelShortcut.dropPos != null &&
678 shortcut.dropPos != null &&
679 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
680 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
681 // For all intents and purposes, this is the same object
682 return;
683 }
684 }
685
686 // the modelItem needs to match up perfectly with item if our model is
687 // to be consistent with the database-- for now, just require
688 // modelItem == item or the equality check above
689 String msg = "item: " + ((item != null) ? item.toString() : "null") +
690 "modelItem: " +
691 ((modelItem != null) ? modelItem.toString() : "null") +
692 "Error: ItemInfo passed to checkItemInfo doesn't match original";
693 RuntimeException e = new RuntimeException(msg);
694 if (stackTrace != null) {
695 e.setStackTrace(stackTrace);
696 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800697 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700698 }
699 }
700
Michael Jurka816474f2012-06-25 14:49:02 -0700701 static void checkItemInfo(final ItemInfo item) {
702 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
703 final long itemId = item.id;
704 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700705 public void run() {
706 synchronized (sBgLock) {
707 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700708 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700709 }
710 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700711 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700712 }
713
Michael Jurkac9d95c52011-08-29 14:03:34 -0700714 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
715 final ItemInfo item, final String callingFunction) {
716 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700717 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700718 final ContentResolver cr = context.getContentResolver();
719
Adam Cohen487f7dd2012-06-28 18:12:10 -0700720 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700721 Runnable r = new Runnable() {
722 public void run() {
723 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700724 updateItemArrays(item, itemId, stackTrace);
725 }
726 };
727 runOnWorkerThread(r);
728 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700729
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700730 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
731 final ArrayList<ItemInfo> items, final String callingFunction) {
732 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700733
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700734 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
735 Runnable r = new Runnable() {
736 public void run() {
737 ArrayList<ContentProviderOperation> ops =
738 new ArrayList<ContentProviderOperation>();
739 int count = items.size();
740 for (int i = 0; i < count; i++) {
741 ItemInfo item = items.get(i);
742 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700743 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700744 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700745
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700746 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
747 updateItemArrays(item, itemId, stackTrace);
748
749 }
750 try {
751 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
752 } catch (Exception e) {
753 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700754 }
755 }
756 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700757 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700758 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700759
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700760 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
761 // Lock on mBgLock *after* the db operation
762 synchronized (sBgLock) {
763 checkItemInfoLocked(itemId, item, stackTrace);
764
765 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
766 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
767 // Item is in a folder, make sure this folder exists
768 if (!sBgFolders.containsKey(item.container)) {
769 // An items container is being set to a that of an item which is not in
770 // the list of Folders.
771 String msg = "item: " + item + " container being set to: " +
772 item.container + ", not in the list of folders";
773 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700774 }
775 }
776
777 // Items are added/removed from the corresponding FolderInfo elsewhere, such
778 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
779 // that are on the desktop, as appropriate
780 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800781 if (modelItem != null &&
782 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
783 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700784 switch (modelItem.itemType) {
785 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
786 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
787 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
788 if (!sBgWorkspaceItems.contains(modelItem)) {
789 sBgWorkspaceItems.add(modelItem);
790 }
791 break;
792 default:
793 break;
794 }
795 } else {
796 sBgWorkspaceItems.remove(modelItem);
797 }
798 }
799 }
800
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800801 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400802 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700803 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700804 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700805 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400807 item.cellX = cellX;
808 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700809
Winson Chung3d503fb2011-07-13 17:25:49 -0700810 // We store hotseat items in canonical form which is this orientation invariant position
811 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700812 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700813 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700814 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700815 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700816 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700817 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400818
819 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400820 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700821 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
822 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800823 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700824 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400825
Michael Jurkac9d95c52011-08-29 14:03:34 -0700826 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700827 }
828
829 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700830 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
831 * cellX, cellY have already been updated on the ItemInfos.
832 */
833 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
834 final long container, final int screen) {
835
836 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
837 int count = items.size();
838
839 for (int i = 0; i < count; i++) {
840 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700841 item.container = container;
842
843 // We store hotseat items in canonical form which is this orientation invariant position
844 // in the hotseat
845 if (context instanceof Launcher && screen < 0 &&
846 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700847 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700848 item.cellY);
849 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700850 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700851 }
852
853 final ContentValues values = new ContentValues();
854 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
855 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
856 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800857 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700858 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700859
860 contentValues.add(values);
861 }
862 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
863 }
864
865 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700866 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800867 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700868 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700869 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700870 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800871 item.cellX = cellX;
872 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700873 item.spanX = spanX;
874 item.spanY = spanY;
875
876 // We store hotseat items in canonical form which is this orientation invariant position
877 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700878 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700879 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700880 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700881 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700882 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700883 }
Adam Cohend4844c32011-02-18 19:25:06 -0800884
Adam Cohend4844c32011-02-18 19:25:06 -0800885 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800886 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700887 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
888 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800889 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700890 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
891 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700892 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800893
Michael Jurka816474f2012-06-25 14:49:02 -0700894 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700895 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700896
897 /**
898 * Update an item to the database in a specified container.
899 */
900 static void updateItemInDatabase(Context context, final ItemInfo item) {
901 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100902 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700903 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800904 }
905
906 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400907 * Returns true if the shortcuts already exists in the database.
908 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800909 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800910 static boolean shortcutExists(Context context, String title, Intent intent,
911 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400912 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700913 final Intent intentWithPkg, intentWithoutPkg;
914
915 if (intent.getComponent() != null) {
916 // If component is not null, an intent with null package will produce
917 // the same result and should also be a match.
918 if (intent.getPackage() != null) {
919 intentWithPkg = intent;
920 intentWithoutPkg = new Intent(intent).setPackage(null);
921 } else {
922 intentWithPkg = new Intent(intent).setPackage(
923 intent.getComponent().getPackageName());
924 intentWithoutPkg = intent;
925 }
926 } else {
927 intentWithPkg = intent;
928 intentWithoutPkg = intent;
929 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800930 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
931 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400932 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800933 new String[] { "title", "intent", "profileId" },
934 "title=? and (intent=? or intent=?) and profileId=?",
935 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
936 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400937 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800938 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400939 } finally {
940 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800941 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700942 }
943
Joe Onorato9c1289c2009-08-17 11:03:03 -0400944 /**
945 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
946 */
947 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
948 final ContentResolver cr = context.getContentResolver();
949 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
950 "_id=? and (itemType=? or itemType=?)",
951 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700952 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700953
Joe Onorato9c1289c2009-08-17 11:03:03 -0400954 try {
955 if (c.moveToFirst()) {
956 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
957 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
958 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
959 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
960 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
961 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700962 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963
Joe Onorato9c1289c2009-08-17 11:03:03 -0400964 FolderInfo folderInfo = null;
965 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700966 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
967 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400968 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700969 }
970
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 folderInfo.title = c.getString(titleIndex);
972 folderInfo.id = id;
973 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700974 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700975 folderInfo.cellX = c.getInt(cellXIndex);
976 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700977 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400978
979 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700980 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981 } finally {
982 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700983 }
984
985 return null;
986 }
987
Joe Onorato9c1289c2009-08-17 11:03:03 -0400988 /**
989 * Add an item to the database in a specified container. Sets the container, screen, cellX and
990 * cellY fields of the item. Also assigns an ID to the item.
991 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700992 public static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700993 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400995 item.cellX = cellX;
996 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700997 // We store hotseat items in canonical form which is this orientation invariant position
998 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700999 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001000 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001002 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001003 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001004 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001005
1006 final ContentValues values = new ContentValues();
1007 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001008 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
Michael Jurka414300a2013-08-27 15:42:35 +02001010 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001011 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001012
Jason Monk8e19cf22014-03-20 15:06:57 -04001013 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001014 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001016 cr.insert(LauncherSettings.Favorites.CONTENT_URI, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001017
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001018 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001019 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001020 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001021 sBgItemsIdMap.put(item.id, item);
1022 switch (item.itemType) {
1023 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1024 sBgFolders.put(item.id, (FolderInfo) item);
1025 // Fall through
1026 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1027 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1028 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1029 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1030 sBgWorkspaceItems.add(item);
1031 } else {
1032 if (!sBgFolders.containsKey(item.container)) {
1033 // Adding an item to a folder that doesn't exist.
1034 String msg = "adding item: " + item + " to a folder that " +
1035 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001036 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001037 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001038 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001039 break;
1040 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1041 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1042 break;
1043 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 }
1045 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001046 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001047 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001048 }
1049
Joe Onorato9c1289c2009-08-17 11:03:03 -04001050 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001051 * Creates a new unique child id, for a given cell span across all layouts.
1052 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001053 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001054 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001055 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001056 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001057 }
1058
Sunny Goyal34942622014-08-29 17:20:55 -07001059 private static ArrayList<ItemInfo> getItemsByPackageName(
1060 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001061 ItemInfoFilter filter = new ItemInfoFilter() {
1062 @Override
1063 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1064 return cn.getPackageName().equals(pn) && info.user.equals(user);
1065 }
1066 };
Sunny Goyal34942622014-08-29 17:20:55 -07001067 return filterItemInfos(sBgItemsIdMap.values(), filter);
1068 }
1069
1070 /**
1071 * Removes all the items from the database corresponding to the specified package.
1072 */
1073 static void deletePackageFromDatabase(Context context, final String pn,
1074 final UserHandleCompat user) {
1075 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001076 }
1077
1078 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001079 * Removes the specified item from the database
1080 * @param context
1081 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001082 */
Sunny Goyalfa401a12015-04-10 13:45:42 -07001083 public static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001084 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1085 items.add(item);
1086 deleteItemsFromDatabase(context, items);
1087 }
1088
1089 /**
1090 * Removes the specified items from the database
1091 * @param context
1092 * @param item
1093 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001094 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001095 final ContentResolver cr = context.getContentResolver();
Michael Jurka83df1882011-08-31 20:59:26 -07001096 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001097 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001098 for (ItemInfo item : items) {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001099 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001100 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001101
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001102 // Lock on mBgLock *after* the db operation
1103 synchronized (sBgLock) {
1104 switch (item.itemType) {
1105 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1106 sBgFolders.remove(item.id);
1107 for (ItemInfo info: sBgItemsIdMap.values()) {
1108 if (info.container == item.id) {
1109 // We are deleting a folder which still contains items that
1110 // think they are contained by that folder.
1111 String msg = "deleting a folder (" + item + ") which still " +
1112 "contains items (" + info + ")";
1113 Log.e(TAG, msg);
1114 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001115 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001116 sBgWorkspaceItems.remove(item);
1117 break;
1118 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1119 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1120 sBgWorkspaceItems.remove(item);
1121 break;
1122 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1123 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1124 break;
1125 }
1126 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001127 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001128 }
1129 }
Michael Jurka83df1882011-08-31 20:59:26 -07001130 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001131 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001132 }
1133
1134 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001135 * Update the order of the workspace screens in the database. The array list contains
1136 * a list of screen ids in the order that they should appear.
1137 */
Winson Chungc9168342013-06-26 14:54:55 -07001138 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001139 // Log to disk
1140 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1141 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1142
Winson Chung64359a52013-07-08 17:17:08 -07001143 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001144 final ContentResolver cr = context.getContentResolver();
1145 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1146
1147 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001148 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001149 while (iter.hasNext()) {
1150 long id = iter.next();
1151 if (id < 0) {
1152 iter.remove();
1153 }
1154 }
1155
1156 Runnable r = new Runnable() {
1157 @Override
1158 public void run() {
Yura085c8532014-02-11 15:15:29 +00001159 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001160 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001161 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001162 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001163 for (int i = 0; i < count; i++) {
1164 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001165 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001166 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1167 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001168 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001169 }
Yura085c8532014-02-11 15:15:29 +00001170
1171 try {
1172 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1173 } catch (Exception ex) {
1174 throw new RuntimeException(ex);
1175 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001176
Winson Chungba9c37f2013-08-30 14:11:37 -07001177 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001178 sBgWorkspaceScreens.clear();
1179 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001180 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001181 }
1182 };
1183 runOnWorkerThread(r);
1184 }
1185
1186 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001187 * Remove the contents of the specified folder from the database
1188 */
Sunny Goyalfa401a12015-04-10 13:45:42 -07001189 public static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001190 final ContentResolver cr = context.getContentResolver();
1191
Michael Jurkac9d95c52011-08-29 14:03:34 -07001192 Runnable r = new Runnable() {
1193 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001194 cr.delete(LauncherSettings.Favorites.getContentUri(info.id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001195 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001196 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 sBgItemsIdMap.remove(info.id);
1198 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001199 sBgWorkspaceItems.remove(info);
1200 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001201
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001202 cr.delete(LauncherSettings.Favorites.CONTENT_URI,
Michael Jurkac9d95c52011-08-29 14:03:34 -07001203 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001205 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001206 for (ItemInfo childInfo : info.contents) {
1207 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001208 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001209 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001210 }
1211 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001212 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001213 }
1214
1215 /**
1216 * Set this as the current Launcher activity object for the loader.
1217 */
1218 public void initialize(Callbacks callbacks) {
1219 synchronized (mLock) {
1220 mCallbacks = new WeakReference<Callbacks>(callbacks);
1221 }
1222 }
1223
Kenny Guyed131872014-04-30 03:02:21 +01001224 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001225 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001226 int op = PackageUpdatedTask.OP_UPDATE;
1227 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1228 user));
1229 }
1230
1231 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001232 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001233 int op = PackageUpdatedTask.OP_REMOVE;
1234 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1235 user));
1236 }
1237
1238 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001239 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001240 int op = PackageUpdatedTask.OP_ADD;
1241 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1242 user));
1243 }
1244
1245 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001246 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001247 boolean replacing) {
1248 if (!replacing) {
1249 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1250 user));
1251 if (mAppsCanBeOnRemoveableStorage) {
1252 // Only rebind if we support removable storage. It catches the
1253 // case where
1254 // apps on the external sd card need to be reloaded
1255 startLoaderFromBackground();
1256 }
1257 } else {
1258 // If we are replacing then just update the packages in the list
1259 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1260 packageNames, user));
1261 }
1262 }
1263
1264 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001265 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001266 boolean replacing) {
1267 if (!replacing) {
1268 enqueuePackageUpdated(new PackageUpdatedTask(
1269 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1270 user));
1271 }
Kenny Guyed131872014-04-30 03:02:21 +01001272 }
1273
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001274 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001275 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1276 * ACTION_PACKAGE_CHANGED.
1277 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001278 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001279 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001280 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001281
Joe Onorato36115782010-06-17 13:28:48 -04001282 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001283 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001284 // If we have changed locale we need to clear out the labels in all apps/workspace.
1285 forceReload();
1286 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1287 // Check if configuration change was an mcc/mnc change which would affect app resources
1288 // and we would need to clear out the labels in all apps/workspace. Same handling as
1289 // above for ACTION_LOCALE_CHANGED
1290 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001291 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001292 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001293 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001294 forceReload();
1295 }
1296 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001297 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001298 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1299 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001300 Callbacks callbacks = getCallback();
1301 if (callbacks != null) {
1302 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001303 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001304 }
1305 }
1306
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001307 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001308 resetLoadedState(true, true);
1309
Reena Lee93f824a2011-09-23 17:20:28 -07001310 // Do this here because if the launcher activity is running it will be restarted.
1311 // If it's not running startLoaderFromBackground will merely tell it that it needs
1312 // to reload.
1313 startLoaderFromBackground();
1314 }
1315
Winson Chungf0c6ae02012-03-21 16:10:31 -07001316 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1317 synchronized (mLock) {
1318 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1319 // mWorkspaceLoaded to true later
1320 stopLoaderLocked();
1321 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1322 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1323 }
1324 }
1325
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001326 /**
1327 * When the launcher is in the background, it's possible for it to miss paired
1328 * configuration changes. So whenever we trigger the loader from the background
1329 * tell the launcher that it needs to re-run the loader when it comes back instead
1330 * of doing it now.
1331 */
1332 public void startLoaderFromBackground() {
1333 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001334 Callbacks callbacks = getCallback();
1335 if (callbacks != null) {
1336 // Only actually run the loader if they're not paused.
1337 if (!callbacks.setLoadOnResume()) {
1338 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001339 }
1340 }
1341 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001342 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001343 }
Joe Onorato36115782010-06-17 13:28:48 -04001344 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001345
Reena Lee93f824a2011-09-23 17:20:28 -07001346 // If there is already a loader task running, tell it to stop.
1347 // returns true if isLaunching() was true on the old task
1348 private boolean stopLoaderLocked() {
1349 boolean isLaunching = false;
1350 LoaderTask oldTask = mLoaderTask;
1351 if (oldTask != null) {
1352 if (oldTask.isLaunching()) {
1353 isLaunching = true;
1354 }
1355 oldTask.stopLocked();
1356 }
1357 return isLaunching;
1358 }
1359
Adam Cohen1a85c582014-09-30 09:48:49 -07001360 public boolean isCurrentCallbacks(Callbacks callbacks) {
1361 return (mCallbacks != null && mCallbacks.get() == callbacks);
1362 }
1363
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001364 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001365 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1366 }
1367
1368 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001369 synchronized (mLock) {
1370 if (DEBUG_LOADERS) {
1371 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1372 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001373
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001374 // Clear any deferred bind-runnables from the synchronized load process
1375 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001376 synchronized (mDeferredBindRunnables) {
1377 mDeferredBindRunnables.clear();
1378 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001379
Joe Onorato36115782010-06-17 13:28:48 -04001380 // Don't bother to start the thread if we know it's not going to do anything
1381 if (mCallbacks != null && mCallbacks.get() != null) {
1382 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001383 // also, don't downgrade isLaunching if we're already running
1384 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001385 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001386 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1387 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001388 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1389 } else {
1390 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1391 sWorker.post(mLoaderTask);
1392 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001393 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001394 }
1395 }
1396
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001397 void bindRemainingSynchronousPages() {
1398 // Post the remaining side pages to be loaded
1399 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001400 Runnable[] deferredBindRunnables = null;
1401 synchronized (mDeferredBindRunnables) {
1402 deferredBindRunnables = mDeferredBindRunnables.toArray(
1403 new Runnable[mDeferredBindRunnables.size()]);
1404 mDeferredBindRunnables.clear();
1405 }
1406 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001407 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001408 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001409 }
1410 }
1411
Joe Onorato36115782010-06-17 13:28:48 -04001412 public void stopLoader() {
1413 synchronized (mLock) {
1414 if (mLoaderTask != null) {
1415 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001416 }
1417 }
Joe Onorato36115782010-06-17 13:28:48 -04001418 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001419
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001420 /**
1421 * Loads the workspace screen ids in an ordered list.
1422 */
Adam Cohen091440a2015-03-18 14:16:05 -07001423 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001424 final ContentResolver contentResolver = context.getContentResolver();
1425 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001426
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001427 // Get screens ordered by rank.
1428 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1429 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1430 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001431 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001432 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001433 while (sc.moveToNext()) {
1434 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001435 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001436 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001437 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1438 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001439 }
1440 }
1441 } finally {
1442 sc.close();
1443 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001444 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001445 }
1446
Michael Jurkac57b7a82011-08-09 22:02:20 -07001447 public boolean isAllAppsLoaded() {
1448 return mAllAppsLoaded;
1449 }
1450
Winson Chung36a62fe2012-05-06 18:04:42 -07001451 boolean isLoadingWorkspace() {
1452 synchronized (mLock) {
1453 if (mLoaderTask != null) {
1454 return mLoaderTask.isLoadingWorkspace();
1455 }
1456 }
1457 return false;
1458 }
1459
Joe Onorato36115782010-06-17 13:28:48 -04001460 /**
1461 * Runnable for the thread that loads the contents of the launcher:
1462 * - workspace icons
1463 * - widgets
1464 * - all apps icons
1465 */
1466 private class LoaderTask implements Runnable {
1467 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001468 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001469 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001470 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001471 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001472 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001473
Dan Sandlerd5024042014-01-09 15:01:33 -05001474 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001475 mContext = context;
1476 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001477 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001478 }
1479
Joe Onorato36115782010-06-17 13:28:48 -04001480 boolean isLaunching() {
1481 return mIsLaunching;
1482 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001483
Winson Chung36a62fe2012-05-06 18:04:42 -07001484 boolean isLoadingWorkspace() {
1485 return mIsLoadingAndBindingWorkspace;
1486 }
1487
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001488 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 mIsLoadingAndBindingWorkspace = true;
1490
Joe Onorato36115782010-06-17 13:28:48 -04001491 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001492 if (DEBUG_LOADERS) {
1493 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001494 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001495
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001496 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001497 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001498 synchronized (LoaderTask.this) {
1499 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001500 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001501 }
1502 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001503 }
1504 }
1505
Joe Onorato36115782010-06-17 13:28:48 -04001506 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001507 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001508 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001509
Joe Onorato36115782010-06-17 13:28:48 -04001510 private void waitForIdle() {
1511 // Wait until the either we're stopped or the other threads are done.
1512 // This way we don't start loading all apps until the workspace has settled
1513 // down.
1514 synchronized (LoaderTask.this) {
1515 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001516
Joe Onorato36115782010-06-17 13:28:48 -04001517 mHandler.postIdle(new Runnable() {
1518 public void run() {
1519 synchronized (LoaderTask.this) {
1520 mLoadAndBindStepFinished = true;
1521 if (DEBUG_LOADERS) {
1522 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001523 }
Joe Onorato36115782010-06-17 13:28:48 -04001524 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001525 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001526 }
Joe Onorato36115782010-06-17 13:28:48 -04001527 });
1528
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001529 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001530 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001531 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1532 // wait no longer than 1sec at a time
1533 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001534 } catch (InterruptedException ex) {
1535 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001536 }
1537 }
Joe Onorato36115782010-06-17 13:28:48 -04001538 if (DEBUG_LOADERS) {
1539 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001540 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001541 + "ms for previous step to finish binding");
1542 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001543 }
Joe Onorato36115782010-06-17 13:28:48 -04001544 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001545
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001546 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001547 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001548 // Ensure that we have a valid page index to load synchronously
1549 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1550 "valid page index");
1551 }
1552 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1553 // Ensure that we don't try and bind a specified page when the pages have not been
1554 // loaded already (we should load everything asynchronously in that case)
1555 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1556 }
1557 synchronized (mLock) {
1558 if (mIsLoaderTaskRunning) {
1559 // Ensure that we are never running the background loading at this point since
1560 // we also touch the background collections
1561 throw new RuntimeException("Error! Background loading is already running");
1562 }
1563 }
1564
1565 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1566 // data structures, we can't allow any other thread to touch that data, but because
1567 // this call is synchronous, we can get away with not locking).
1568
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001569 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001570 // operations from the previous activity. We need to ensure that all queued operations
1571 // are executed before any synchronous binding work is done.
1572 mHandler.flush();
1573
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001574 // Divide the set of loaded items into those that we are binding synchronously, and
1575 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001576 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001577 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1578 // arise from that.
1579 onlyBindAllApps();
1580 }
1581
Joe Onorato36115782010-06-17 13:28:48 -04001582 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001583 synchronized (mLock) {
1584 mIsLoaderTaskRunning = true;
1585 }
Joe Onorato36115782010-06-17 13:28:48 -04001586 // Optimize for end-user experience: if the Launcher is up and // running with the
1587 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1588 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001589 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001590 // Elevate priority when Home launches for the first time to avoid
1591 // starving at boot time. Staring at a blank home is not cool.
1592 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001593 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1594 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001595 android.os.Process.setThreadPriority(mIsLaunching
1596 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1597 }
Winson Chung64359a52013-07-08 17:17:08 -07001598 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001599 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001600
Joe Onorato36115782010-06-17 13:28:48 -04001601 if (mStopped) {
1602 break keep_running;
1603 }
1604
1605 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1606 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001607 synchronized (mLock) {
1608 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001609 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001610 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1611 }
1612 }
Joe Onorato36115782010-06-17 13:28:48 -04001613 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001614
1615 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001616 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1617 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001618
Sunny Goyal5b0e6692015-03-19 14:31:19 -07001619 // Remove entries for packages which changed while the launcher was dead.
1620 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews();
1621
Winson Chung7ed37742011-09-08 15:45:51 -07001622 // Restore the default thread priority after we are done loading items
1623 synchronized (mLock) {
1624 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1625 }
Joe Onorato36115782010-06-17 13:28:48 -04001626 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001627
Joe Onorato36115782010-06-17 13:28:48 -04001628 // Clear out this reference, otherwise we end up holding it until all of the
1629 // callback runnables are done.
1630 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001631
Joe Onorato36115782010-06-17 13:28:48 -04001632 synchronized (mLock) {
1633 // If we are still the last one to be scheduled, remove ourselves.
1634 if (mLoaderTask == this) {
1635 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001636 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001637 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001638 }
Joe Onorato36115782010-06-17 13:28:48 -04001639 }
1640
1641 public void stopLocked() {
1642 synchronized (LoaderTask.this) {
1643 mStopped = true;
1644 this.notify();
1645 }
1646 }
1647
1648 /**
1649 * Gets the callbacks object. If we've been stopped, or if the launcher object
1650 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1651 * object that was around when the deferred message was scheduled, and if there's
1652 * a new Callbacks object around then also return null. This will save us from
1653 * calling onto it with data that will be ignored.
1654 */
1655 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1656 synchronized (mLock) {
1657 if (mStopped) {
1658 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001659 }
Joe Onorato36115782010-06-17 13:28:48 -04001660
1661 if (mCallbacks == null) {
1662 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001663 }
Joe Onorato36115782010-06-17 13:28:48 -04001664
1665 final Callbacks callbacks = mCallbacks.get();
1666 if (callbacks != oldCallbacks) {
1667 return null;
1668 }
1669 if (callbacks == null) {
1670 Log.w(TAG, "no mCallbacks");
1671 return null;
1672 }
1673
1674 return callbacks;
1675 }
1676 }
1677
1678 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001679 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001680 LauncherAppState app = LauncherAppState.getInstance();
1681 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001682 final int countX = (int) grid.numColumns;
1683 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001684
Adam Cohendcd297f2013-06-18 13:13:40 -07001685 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001686 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001687 // Return early if we detect that an item is under the hotseat button
1688 if (mCallbacks == null ||
1689 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001690 Log.e(TAG, "Error loading shortcut into hotseat " + item
1691 + " into position (" + item.screenId + ":" + item.cellX + ","
1692 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001693 return false;
1694 }
1695
Dan Sandler295ae182013-12-10 16:05:47 -05001696 final ItemInfo[][] hotseatItems =
1697 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1698
Adam Cohenae4409d2013-11-26 10:34:59 -08001699 if (item.screenId >= grid.numHotseatIcons) {
1700 Log.e(TAG, "Error loading shortcut " + item
1701 + " into hotseat position " + item.screenId
1702 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1703 + ")");
1704 return false;
1705 }
1706
Dan Sandler295ae182013-12-10 16:05:47 -05001707 if (hotseatItems != null) {
1708 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001709 Log.e(TAG, "Error loading shortcut into hotseat " + item
1710 + " into position (" + item.screenId + ":" + item.cellX + ","
1711 + item.cellY + ") occupied by "
1712 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1713 [(int) item.screenId][0]);
1714 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001715 } else {
1716 hotseatItems[(int) item.screenId][0] = item;
1717 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001718 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001719 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001720 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001721 items[(int) item.screenId][0] = item;
1722 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001723 return true;
1724 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001725 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1726 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001727 return true;
1728 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001729
Adam Cohendcd297f2013-06-18 13:13:40 -07001730 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001731 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 occupied.put(item.screenId, items);
1733 }
1734
Dan Sandler295ae182013-12-10 16:05:47 -05001735 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001736 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1737 item.cellX < 0 || item.cellY < 0 ||
1738 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1739 Log.e(TAG, "Error loading shortcut " + item
1740 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1741 + item.cellX + "," + item.cellY
1742 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1743 return false;
1744 }
1745
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001746 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001747 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1748 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001749 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001750 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001751 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001752 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001753 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001754 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001755 return false;
1756 }
1757 }
1758 }
1759 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1760 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001761 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001762 }
1763 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001764
Joe Onorato36115782010-06-17 13:28:48 -04001765 return true;
1766 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001767
Winson Chungba9c37f2013-08-30 14:11:37 -07001768 /** Clears all the sBg data structures */
1769 private void clearSBgDataStructures() {
1770 synchronized (sBgLock) {
1771 sBgWorkspaceItems.clear();
1772 sBgAppWidgets.clear();
1773 sBgFolders.clear();
1774 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001775 sBgWorkspaceScreens.clear();
1776 }
1777 }
1778
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001779 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001780 // Log to disk
1781 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1782
Joe Onorato36115782010-06-17 13:28:48 -04001783 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001784
Joe Onorato36115782010-06-17 13:28:48 -04001785 final Context context = mContext;
1786 final ContentResolver contentResolver = context.getContentResolver();
1787 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001788 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001789 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1790 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001791 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001792
Winson Chung892c74d2013-08-22 16:15:50 -07001793 LauncherAppState app = LauncherAppState.getInstance();
1794 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1795 int countX = (int) grid.numColumns;
1796 int countY = (int) grid.numRows;
1797
Dan Sandlerd5024042014-01-09 15:01:33 -05001798 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1799 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1800 LauncherAppState.getLauncherProvider().deleteDatabase();
1801 }
1802
1803 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1804 // append the user's Launcher2 shortcuts
1805 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1806 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1807 } else {
1808 // Make sure the default workspace is loaded
1809 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001810 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001811 }
Adam Cohene25af792013-06-06 23:08:25 -07001812
Winson Chung2abf94d2012-07-18 18:16:38 -07001813 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001814 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001815 final HashSet<String> installingPkgs = PackageInstallerCompat
1816 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001817
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001818 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001819 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001820 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001821 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001822 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001823
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001824 // +1 for the hotseat (it can be larger than the workspace)
1825 // Load workspace in reverse order to ensure that latest items are loaded first (and
1826 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001827 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001828
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001829 try {
1830 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1831 final int intentIndex = c.getColumnIndexOrThrow
1832 (LauncherSettings.Favorites.INTENT);
1833 final int titleIndex = c.getColumnIndexOrThrow
1834 (LauncherSettings.Favorites.TITLE);
1835 final int iconTypeIndex = c.getColumnIndexOrThrow(
1836 LauncherSettings.Favorites.ICON_TYPE);
1837 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1838 final int iconPackageIndex = c.getColumnIndexOrThrow(
1839 LauncherSettings.Favorites.ICON_PACKAGE);
1840 final int iconResourceIndex = c.getColumnIndexOrThrow(
1841 LauncherSettings.Favorites.ICON_RESOURCE);
1842 final int containerIndex = c.getColumnIndexOrThrow(
1843 LauncherSettings.Favorites.CONTAINER);
1844 final int itemTypeIndex = c.getColumnIndexOrThrow(
1845 LauncherSettings.Favorites.ITEM_TYPE);
1846 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1847 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001848 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1849 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001850 final int screenIndex = c.getColumnIndexOrThrow(
1851 LauncherSettings.Favorites.SCREEN);
1852 final int cellXIndex = c.getColumnIndexOrThrow
1853 (LauncherSettings.Favorites.CELLX);
1854 final int cellYIndex = c.getColumnIndexOrThrow
1855 (LauncherSettings.Favorites.CELLY);
1856 final int spanXIndex = c.getColumnIndexOrThrow
1857 (LauncherSettings.Favorites.SPANX);
1858 final int spanYIndex = c.getColumnIndexOrThrow(
1859 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001860 final int rankIndex = c.getColumnIndexOrThrow(
1861 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001862 final int restoredIndex = c.getColumnIndexOrThrow(
1863 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001864 final int profileIdIndex = c.getColumnIndexOrThrow(
1865 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001866 final int optionsIndex = c.getColumnIndexOrThrow(
1867 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001868
Sunny Goyal7f834d22015-04-21 10:10:23 -07001869 final LongSparseArray<UserHandleCompat> allUsers = new LongSparseArray<>();
1870 for (UserHandleCompat user : mUserManager.getUserProfiles()) {
1871 allUsers.put(mUserManager.getSerialNumberForUser(user), user);
1872 }
1873
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);
Sunny Goyal7f834d22015-04-21 10:10:23 -07001895 user = allUsers.get(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);
Sunny Goyal7f834d22015-04-21 10:10:23 -07002158 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 Goyal7f834d22015-04-21 10:10:23 -07002161 user = allUsers.get(serialNumber);
2162 if (user == null) {
2163 itemsToRemove.add(id);
2164 continue;
2165 }
2166
Sunny Goyalff572272014-07-23 13:58:07 -07002167 final ComponentName component =
2168 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002169
Sunny Goyal651077b2014-06-30 14:15:31 -07002170 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002171 final boolean isIdValid = (restoreStatus &
2172 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Sunny Goyalff572272014-07-23 13:58:07 -07002173 final boolean wasProviderReady = (restoreStatus &
2174 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002175
Adam Cohen59400422014-03-05 18:07:04 -08002176 final LauncherAppWidgetProviderInfo provider =
2177 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002178 ComponentName.unflattenFromString(savedProvider),
Sunny Goyal7f834d22015-04-21 10:10:23 -07002179 user);
Sunny Goyalff572272014-07-23 13:58:07 -07002180
2181 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002182 if (!isSafeMode && !customWidget &&
2183 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002184 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002185 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002186
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002187 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002188 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002189 itemsToRemove.add(id);
2190 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002191 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002192 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2193 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002194
2195 if (!customWidget) {
2196 int[] minSpan =
2197 Launcher.getMinSpanForWidget(context, provider);
2198 appWidgetInfo.minSpanX = minSpan[0];
2199 appWidgetInfo.minSpanY = minSpan[1];
2200 }
Sunny Goyalff572272014-07-23 13:58:07 -07002201
2202 int status = restoreStatus;
2203 if (!wasProviderReady) {
2204 // If provider was not previously ready, update the
2205 // status and UI flag.
2206
2207 // Id would be valid only if the widget restore broadcast was received.
2208 if (isIdValid) {
2209 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2210 } else {
2211 status &= ~LauncherAppWidgetInfo
2212 .FLAG_PROVIDER_NOT_READY;
2213 }
2214 }
2215 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002216 } else {
2217 Log.v(TAG, "Widget restore pending id=" + id
2218 + " appWidgetId=" + appWidgetId
2219 + " status =" + restoreStatus);
2220 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002221 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002222 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002223
2224 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2225 // Restore has started once.
2226 } else if (installingPkgs.contains(component.getPackageName())) {
2227 // App restore has started. Update the flag
2228 appWidgetInfo.restoreStatus |=
2229 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002230 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002231 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002232 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002233 itemsToRemove.add(id);
2234 continue;
2235 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002236 }
Sunny Goyalff572272014-07-23 13:58:07 -07002237
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002238 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002239 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 appWidgetInfo.cellX = c.getInt(cellXIndex);
2241 appWidgetInfo.cellY = c.getInt(cellYIndex);
2242 appWidgetInfo.spanX = c.getInt(spanXIndex);
2243 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002244
Adam Cohen59400422014-03-05 18:07:04 -08002245 if (!customWidget) {
2246 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2247 appWidgetInfo.minSpanX = minSpan[0];
2248 appWidgetInfo.minSpanY = minSpan[1];
2249 }
2250
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002251 container = c.getInt(containerIndex);
2252 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2253 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2254 Log.e(TAG, "Widget found where container != " +
2255 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2256 continue;
2257 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002258
Adam Cohene25af792013-06-06 23:08:25 -07002259 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002260 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002261 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2262 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002263 break;
2264 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002265
Adam Cohen59400422014-03-05 18:07:04 -08002266 if (!customWidget) {
2267 String providerName =
2268 appWidgetInfo.providerName.flattenToString();
2269 if (!providerName.equals(savedProvider) ||
2270 (appWidgetInfo.restoreStatus != restoreStatus)) {
2271 ContentValues values = new ContentValues();
2272 values.put(
2273 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2274 providerName);
2275 values.put(LauncherSettings.Favorites.RESTORED,
2276 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002277 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002278 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002279 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2281 sBgAppWidgets.add(appWidgetInfo);
2282 }
Joe Onorato36115782010-06-17 13:28:48 -04002283 break;
2284 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002286 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002287 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002288 }
2289 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002290 if (c != null) {
2291 c.close();
2292 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 }
2294
Winson Chungba9c37f2013-08-30 14:11:37 -07002295 // Break early if we've stopped loading
2296 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002297 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002298 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002299 }
2300
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 if (itemsToRemove.size() > 0) {
2302 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002303 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002304 // Remove dead items
2305 for (long id : itemsToRemove) {
2306 if (DEBUG_LOADERS) {
2307 Log.d(TAG, "Removed id = " + id);
2308 }
2309 // Don't notify content observers
2310 try {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002311 client.delete(LauncherSettings.Favorites.getContentUri(id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002312 } catch (RemoteException e) {
2313 Log.w(TAG, "Could not remove id = " + id);
2314 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002315 }
2316 }
2317
Chris Wrenf4d08112014-01-16 18:13:56 -05002318 if (restoredRows.size() > 0) {
2319 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002320 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002321 // Update restored items that no longer require special handling
2322 try {
2323 StringBuilder selectionBuilder = new StringBuilder();
2324 selectionBuilder.append(LauncherSettings.Favorites._ID);
2325 selectionBuilder.append(" IN (");
2326 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2327 selectionBuilder.append(")");
2328 ContentValues values = new ContentValues();
2329 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002330 updater.update(LauncherSettings.Favorites.CONTENT_URI,
Chris Wrenf4d08112014-01-16 18:13:56 -05002331 values, selectionBuilder.toString(), null);
2332 } catch (RemoteException e) {
2333 Log.w(TAG, "Could not update restored rows");
2334 }
2335 }
2336
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002337 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2338 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002339 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002340 null, sWorker);
2341 }
2342
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002343 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2344 // Log to disk
2345 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2346 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002347
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002348 // Remove any empty screens
2349 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2350 for (ItemInfo item: sBgItemsIdMap.values()) {
2351 long screenId = item.screenId;
2352 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2353 unusedScreens.contains(screenId)) {
2354 unusedScreens.remove(screenId);
2355 }
2356 }
2357
2358 // If there are any empty screens remove them, and update.
2359 if (unusedScreens.size() != 0) {
2360 // Log to disk
2361 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2362 TextUtils.join(", ", unusedScreens), true);
2363
2364 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002365 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 }
2367
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002368 if (DEBUG_LOADERS) {
2369 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2370 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002371 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002372 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002373 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002374
Daniel Sandler566da102013-06-25 23:43:45 -04002375 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002376 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002377 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002378 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 line += " | ";
2380 }
Winson Chung892c74d2013-08-22 16:15:50 -07002381 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002382 ItemInfo[][] screen = occupied.get(screenId);
2383 if (x < screen.length && y < screen[x].length) {
2384 line += (screen[x][y] != null) ? "#" : ".";
2385 } else {
2386 line += "!";
2387 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002388 }
Joe Onorato36115782010-06-17 13:28:48 -04002389 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002390 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002391 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002392 }
Joe Onorato36115782010-06-17 13:28:48 -04002393 }
Adam Cohene25af792013-06-06 23:08:25 -07002394 }
2395
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002396 /**
2397 * Partially updates the item without any notification. Must be called on the worker thread.
2398 */
2399 private void updateItem(long itemId, ContentValues update) {
2400 mContext.getContentResolver().update(
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002401 LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002402 update,
2403 BaseColumns._ID + "= ?",
2404 new String[]{Long.toString(itemId)});
2405 }
2406
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002407 /** Filters the set of items who are directly or indirectly (via another container) on the
2408 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002409 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002410 ArrayList<ItemInfo> allWorkspaceItems,
2411 ArrayList<ItemInfo> currentScreenItems,
2412 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002413 // Purge any null ItemInfos
2414 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2415 while (iter.hasNext()) {
2416 ItemInfo i = iter.next();
2417 if (i == null) {
2418 iter.remove();
2419 }
2420 }
2421
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002422 // Order the set of items by their containers first, this allows use to walk through the
2423 // list sequentially, build up a list of containers that are in the specified screen,
2424 // as well as all items in those containers.
2425 Set<Long> itemsOnScreen = new HashSet<Long>();
2426 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2427 @Override
2428 public int compare(ItemInfo lhs, ItemInfo rhs) {
2429 return (int) (lhs.container - rhs.container);
2430 }
2431 });
2432 for (ItemInfo info : allWorkspaceItems) {
2433 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002434 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002435 currentScreenItems.add(info);
2436 itemsOnScreen.add(info.id);
2437 } else {
2438 otherScreenItems.add(info);
2439 }
2440 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2441 currentScreenItems.add(info);
2442 itemsOnScreen.add(info.id);
2443 } else {
2444 if (itemsOnScreen.contains(info.container)) {
2445 currentScreenItems.add(info);
2446 itemsOnScreen.add(info.id);
2447 } else {
2448 otherScreenItems.add(info);
2449 }
2450 }
2451 }
2452 }
2453
2454 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002455 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002456 ArrayList<LauncherAppWidgetInfo> appWidgets,
2457 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2458 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002459
2460 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002461 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002462 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002463 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002464 currentScreenWidgets.add(widget);
2465 } else {
2466 otherScreenWidgets.add(widget);
2467 }
2468 }
2469 }
2470
2471 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002472 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473 HashMap<Long, ItemInfo> itemsIdMap,
2474 HashMap<Long, FolderInfo> folders,
2475 HashMap<Long, FolderInfo> currentScreenFolders,
2476 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002477
2478 for (long id : folders.keySet()) {
2479 ItemInfo info = itemsIdMap.get(id);
2480 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002481 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002482 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002483 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002484 currentScreenFolders.put(id, folder);
2485 } else {
2486 otherScreenFolders.put(id, folder);
2487 }
2488 }
2489 }
2490
2491 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2492 * right) */
2493 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002494 final LauncherAppState app = LauncherAppState.getInstance();
2495 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002496 // XXX: review this
2497 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002498 @Override
2499 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002500 int cellCountX = (int) grid.numColumns;
2501 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002502 int screenOffset = cellCountX * cellCountY;
2503 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002504 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002505 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002506 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002507 rhs.cellY * cellCountX + rhs.cellX);
2508 return (int) (lr - rr);
2509 }
2510 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002511 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002512
Adam Cohendcd297f2013-06-18 13:13:40 -07002513 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2514 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002515 final Runnable r = new Runnable() {
2516 @Override
2517 public void run() {
2518 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2519 if (callbacks != null) {
2520 callbacks.bindScreens(orderedScreens);
2521 }
2522 }
2523 };
2524 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2525 }
2526
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002527 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2528 final ArrayList<ItemInfo> workspaceItems,
2529 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2530 final HashMap<Long, FolderInfo> folders,
2531 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002532
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 final boolean postOnMainThread = (deferredBindRunnables != null);
2534
2535 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002536 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002537 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002538 final int start = i;
2539 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002540 final Runnable r = new Runnable() {
2541 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002542 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002543 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002544 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002545 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2546 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002547 }
2548 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 };
2550 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002551 synchronized (deferredBindRunnables) {
2552 deferredBindRunnables.add(r);
2553 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002554 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002555 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002556 }
Joe Onorato36115782010-06-17 13:28:48 -04002557 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002558
2559 // Bind the folders
2560 if (!folders.isEmpty()) {
2561 final Runnable r = new Runnable() {
2562 public void run() {
2563 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2564 if (callbacks != null) {
2565 callbacks.bindFolders(folders);
2566 }
2567 }
2568 };
2569 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002570 synchronized (deferredBindRunnables) {
2571 deferredBindRunnables.add(r);
2572 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002573 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002574 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002575 }
2576 }
2577
2578 // Bind the widgets, one at a time
2579 N = appWidgets.size();
2580 for (int i = 0; i < N; i++) {
2581 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2582 final Runnable r = new Runnable() {
2583 public void run() {
2584 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2585 if (callbacks != null) {
2586 callbacks.bindAppWidget(widget);
2587 }
2588 }
2589 };
2590 if (postOnMainThread) {
2591 deferredBindRunnables.add(r);
2592 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002593 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002594 }
2595 }
2596 }
2597
2598 /**
2599 * Binds all loaded data to actual views on the main thread.
2600 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002601 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002602 final long t = SystemClock.uptimeMillis();
2603 Runnable r;
2604
2605 // Don't use these two variables in any of the callback runnables.
2606 // Otherwise we hold a reference to them.
2607 final Callbacks oldCallbacks = mCallbacks.get();
2608 if (oldCallbacks == null) {
2609 // This launcher has exited and nobody bothered to tell us. Just bail.
2610 Log.w(TAG, "LoaderTask running with no launcher");
2611 return;
2612 }
2613
Winson Chung9b9fb962013-11-15 15:39:34 -08002614 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2616 ArrayList<LauncherAppWidgetInfo> appWidgets =
2617 new ArrayList<LauncherAppWidgetInfo>();
2618 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2619 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002620 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002621 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002622 workspaceItems.addAll(sBgWorkspaceItems);
2623 appWidgets.addAll(sBgAppWidgets);
2624 folders.putAll(sBgFolders);
2625 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002626 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002627 }
2628
Derek Prothro7aff3992013-12-10 14:00:37 -05002629 final boolean isLoadingSynchronously =
2630 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002631 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002632 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002633 if (currScreen >= orderedScreenIds.size()) {
2634 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002635 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002636 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002637 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002638 final long currentScreenId = currentScreen < 0
2639 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002640
2641 // Load all the items that are on the current page first (and in the process, unbind
2642 // all the existing workspace items before we call startBinding() below.
2643 unbindWorkspaceItemsOnMainThread();
2644
2645 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002646 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2647 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2648 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2649 new ArrayList<LauncherAppWidgetInfo>();
2650 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2651 new ArrayList<LauncherAppWidgetInfo>();
2652 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2653 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2654
Winson Chung9b9fb962013-11-15 15:39:34 -08002655 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002656 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002657 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002659 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002660 otherFolders);
2661 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2662 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2663
2664 // Tell the workspace that we're about to start binding items
2665 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002666 public void run() {
2667 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2668 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002669 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002670 }
2671 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002672 };
Winson Chung81b52252012-08-27 15:34:29 -07002673 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002674
Adam Cohendcd297f2013-06-18 13:13:40 -07002675 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2676
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002677 // Load items on the current page
2678 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2679 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002680 if (isLoadingSynchronously) {
2681 r = new Runnable() {
2682 public void run() {
2683 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002684 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002685 callbacks.onPageBoundSynchronously(currentScreen);
2686 }
2687 }
2688 };
Winson Chung81b52252012-08-27 15:34:29 -07002689 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002690 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002691
Winson Chung4a2afa32012-07-19 14:53:05 -07002692 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2693 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002694 synchronized (mDeferredBindRunnables) {
2695 mDeferredBindRunnables.clear();
2696 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002697 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002698 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002699
2700 // Tell the workspace that we're done binding items
2701 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002702 public void run() {
2703 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2704 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002705 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002706 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002707
Winson Chung98e030b2012-05-07 16:01:11 -07002708 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002709 if (DEBUG_LOADERS) {
2710 Log.d(TAG, "bound workspace in "
2711 + (SystemClock.uptimeMillis()-t) + "ms");
2712 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002713
2714 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002715 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002716 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002717 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002718 synchronized (mDeferredBindRunnables) {
2719 mDeferredBindRunnables.add(r);
2720 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002721 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002722 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002723 }
Joe Onorato36115782010-06-17 13:28:48 -04002724 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002725
Joe Onorato36115782010-06-17 13:28:48 -04002726 private void loadAndBindAllApps() {
2727 if (DEBUG_LOADERS) {
2728 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2729 }
2730 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002731 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002732 synchronized (LoaderTask.this) {
2733 if (mStopped) {
2734 return;
2735 }
2736 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002737 }
Joe Onorato36115782010-06-17 13:28:48 -04002738 } else {
2739 onlyBindAllApps();
2740 }
2741 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002742
Joe Onorato36115782010-06-17 13:28:48 -04002743 private void onlyBindAllApps() {
2744 final Callbacks oldCallbacks = mCallbacks.get();
2745 if (oldCallbacks == null) {
2746 // This launcher has exited and nobody bothered to tell us. Just bail.
2747 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2748 return;
2749 }
2750
2751 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002752 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002753 final ArrayList<AppInfo> list
2754 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002755 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002756 public void run() {
2757 final long t = SystemClock.uptimeMillis();
2758 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2759 if (callbacks != null) {
2760 callbacks.bindAllApplications(list);
2761 }
2762 if (DEBUG_LOADERS) {
2763 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2764 + (SystemClock.uptimeMillis()-t) + "ms");
2765 }
2766 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002767 };
2768 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002769 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002770 r.run();
2771 } else {
2772 mHandler.post(r);
2773 }
Joe Onorato36115782010-06-17 13:28:48 -04002774 }
2775
Winson Chung64359a52013-07-08 17:17:08 -07002776 private void loadAllApps() {
2777 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002778
Joe Onorato36115782010-06-17 13:28:48 -04002779 final Callbacks oldCallbacks = mCallbacks.get();
2780 if (oldCallbacks == null) {
2781 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002782 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002783 return;
2784 }
2785
2786 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2787 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2788
Kenny Guyed131872014-04-30 03:02:21 +01002789 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2790
Winson Chung64359a52013-07-08 17:17:08 -07002791 // Clear the list of apps
2792 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002793 SharedPreferences prefs = mContext.getSharedPreferences(
2794 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002795 for (UserHandleCompat user : profiles) {
2796 // Query for the set of apps
2797 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2798 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2799 if (DEBUG_LOADERS) {
2800 Log.d(TAG, "getActivityList took "
2801 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2802 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2803 }
2804 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002805 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002806 if (apps == null || apps.isEmpty()) {
2807 return;
2808 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002809
2810 // Update icon cache
2811 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2812
2813 // If any package icon has changed (app was updated while launcher was dead),
2814 // update the corresponding shortcuts.
2815 if (!updatedPackages.isEmpty()) {
2816 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2817 synchronized (sBgLock) {
2818 for (ItemInfo info : sBgItemsIdMap.values()) {
2819 if (info instanceof ShortcutInfo && user.equals(info.user)
2820 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2821 ShortcutInfo si = (ShortcutInfo) info;
2822 ComponentName cn = si.getTargetComponent();
2823 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2824 si.updateIcon(mIconCache);
2825 updates.add(si);
2826 }
2827 }
2828 }
2829 }
2830
2831 if (!updates.isEmpty()) {
2832 final UserHandleCompat userFinal = user;
2833 mHandler.post(new Runnable() {
2834
2835 public void run() {
2836 Callbacks cb = getCallback();
2837 if (cb != null) {
2838 cb.bindShortcutsChanged(
2839 updates, new ArrayList<ShortcutInfo>(), userFinal);
2840 }
2841 }
2842 });
2843 }
Kenny Guyed131872014-04-30 03:02:21 +01002844 }
Joe Onorato36115782010-06-17 13:28:48 -04002845
Kenny Guyed131872014-04-30 03:02:21 +01002846 // Create the ApplicationInfos
2847 for (int i = 0; i < apps.size(); i++) {
2848 LauncherActivityInfoCompat app = apps.get(i);
2849 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002850 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002851 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002852
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002853 if (!user.equals(UserHandleCompat.myUserHandle())) {
2854 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
2855 if (heuristic != null) {
2856 heuristic.processUserApps(apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002857 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002858 }
Winson Chung64359a52013-07-08 17:17:08 -07002859 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002860 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002861 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2862 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002863
2864 // Post callback on main thread
2865 mHandler.post(new Runnable() {
2866 public void run() {
2867 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002868 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002869 if (callbacks != null) {
2870 callbacks.bindAllApplications(added);
2871 if (DEBUG_LOADERS) {
2872 Log.d(TAG, "bound " + added.size() + " apps in "
2873 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2874 }
2875 } else {
2876 Log.i(TAG, "not binding apps: no Launcher activity");
2877 }
2878 }
2879 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002880 // Cleanup any data stored for a deleted user.
2881 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Winson Chung64359a52013-07-08 17:17:08 -07002882
Joe Onorato36115782010-06-17 13:28:48 -04002883 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002884 Log.d(TAG, "Icons processed in "
2885 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002886 }
2887 }
2888
2889 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002890 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002891 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2892 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2893 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2894 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2895 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2896 }
Joe Onorato36115782010-06-17 13:28:48 -04002897 }
2898 }
2899
2900 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002901 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002902 }
2903
Adam Cohen091440a2015-03-18 14:16:05 -07002904 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002905
2906 @Override
2907 public void onReceive(Context context, Intent intent) {
2908 synchronized (sBgLock) {
2909 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2910 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002911 final PackageManager manager = context.getPackageManager();
2912 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2913 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002914 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2915 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002916 packagesRemoved.clear();
2917 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002918 for (String pkg : entry.getValue()) {
2919 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002920 boolean packageOnSdcard = launcherApps.isAppEnabled(
2921 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2922 if (packageOnSdcard) {
2923 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2924 packagesUnavailable.add(pkg);
2925 } else {
2926 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2927 packagesRemoved.add(pkg);
2928 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002929 }
2930 }
2931 if (!packagesRemoved.isEmpty()) {
2932 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2933 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2934 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002935 if (!packagesUnavailable.isEmpty()) {
2936 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2937 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2938 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002939 }
Sunny Goyal34942622014-08-29 17:20:55 -07002940 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002941 }
2942 }
2943 }
2944
Joe Onorato36115782010-06-17 13:28:48 -04002945 private class PackageUpdatedTask implements Runnable {
2946 int mOp;
2947 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002948 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002949
2950 public static final int OP_NONE = 0;
2951 public static final int OP_ADD = 1;
2952 public static final int OP_UPDATE = 2;
2953 public static final int OP_REMOVE = 3; // uninstlled
2954 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2955
2956
Kenny Guyed131872014-04-30 03:02:21 +01002957 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002958 mOp = op;
2959 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002960 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002961 }
2962
2963 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002964 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002965
2966 final String[] packages = mPackages;
2967 final int N = packages.length;
2968 switch (mOp) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002969 case OP_ADD: {
Joe Onorato36115782010-06-17 13:28:48 -04002970 for (int i=0; i<N; i++) {
2971 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002972 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002973 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002974 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002975
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002976 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2977 if (heuristic != null) {
2978 heuristic.processPackageAdd(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002979 }
Joe Onorato36115782010-06-17 13:28:48 -04002980 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002981 }
Joe Onorato36115782010-06-17 13:28:48 -04002982 case OP_UPDATE:
2983 for (int i=0; i<N; i++) {
2984 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002985 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002986 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002987 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002988 }
2989 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002990 case OP_REMOVE: {
2991 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2992 if (heuristic != null) {
2993 heuristic.processPackageRemoved(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002994 }
Joe Onorato36115782010-06-17 13:28:48 -04002995 for (int i=0; i<N; i++) {
2996 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002997 mIconCache.removeIconsForPkg(packages[i], mUser);
2998 }
2999 // Fall through
Sunny Goyal18bf8e22015-04-08 18:13:46 -07003000 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003001 case OP_UNAVAILABLE:
3002 for (int i=0; i<N; i++) {
3003 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3004 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07003005 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04003006 }
3007 break;
3008 }
3009
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003010 ArrayList<AppInfo> added = null;
3011 ArrayList<AppInfo> modified = null;
3012 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003013
Adam Cohen487f7dd2012-06-28 18:12:10 -07003014 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003015 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003016 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003017 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003018 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003019 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003020 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003021 }
Winson Chung5d55f332012-07-16 20:45:03 -07003022 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003023 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003024 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003025 }
3026
Sunny Goyale0f58d72014-11-10 18:05:31 -08003027 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003028 if (callbacks == null) {
3029 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3030 return;
3031 }
3032
Sunny Goyal4390ace2014-10-13 11:33:11 -07003033 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3034 new HashMap<ComponentName, AppInfo>();
3035
Joe Onorato36115782010-06-17 13:28:48 -04003036 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003037 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003038 for (AppInfo ai : added) {
3039 addedOrUpdatedApps.put(ai.componentName, ai);
3040 }
Joe Onorato36115782010-06-17 13:28:48 -04003041 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003042
Joe Onorato36115782010-06-17 13:28:48 -04003043 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003044 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003045 for (AppInfo ai : modified) {
3046 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003047 }
3048
Joe Onorato36115782010-06-17 13:28:48 -04003049 mHandler.post(new Runnable() {
3050 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003051 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003052 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003053 callbacks.bindAppsUpdated(modifiedFinal);
3054 }
3055 }
3056 });
3057 }
Winson Chung83892cc2013-05-01 16:53:33 -07003058
Sunny Goyal4390ace2014-10-13 11:33:11 -07003059 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003060 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003061 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3062 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3063 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3064
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003065 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003066 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003067 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003068 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3069 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003070 boolean infoUpdated = false;
3071 boolean shortcutUpdated = false;
3072
3073 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003074 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003075 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003076 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3077 si.iconResource.resourceName, mIconCache, context);
3078 if (icon != null) {
3079 si.setIcon(icon);
3080 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003081 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003082 }
3083 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003084
3085 ComponentName cn = si.getTargetComponent();
3086 if (cn != null && packageSet.contains(cn.getPackageName())) {
3087 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3088
3089 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003090 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3091 // Auto install icon
3092 PackageManager pm = context.getPackageManager();
3093 ResolveInfo matched = pm.resolveActivity(
3094 new Intent(Intent.ACTION_MAIN)
3095 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3096 PackageManager.MATCH_DEFAULT_ONLY);
3097 if (matched == null) {
3098 // Try to find the best match activity.
3099 Intent intent = pm.getLaunchIntentForPackage(
3100 cn.getPackageName());
3101 if (intent != null) {
3102 cn = intent.getComponent();
3103 appInfo = addedOrUpdatedApps.get(cn);
3104 }
3105
3106 if ((intent == null) || (appInfo == null)) {
3107 removedShortcuts.add(si);
3108 continue;
3109 }
3110 si.promisedIntent = intent;
3111 }
3112 }
3113
3114 // Restore the shortcut.
3115 si.intent = si.promisedIntent;
3116 si.promisedIntent = null;
3117 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3118 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3119 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
Sunny Goyalfa401a12015-04-10 13:45:42 -07003120 if (appInfo != null) {
3121 si.flags = appInfo.flags;
3122 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003123
3124 infoUpdated = true;
3125 si.updateIcon(mIconCache);
3126 }
3127
3128 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3129 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3130 si.updateIcon(mIconCache);
3131 si.title = appInfo.title.toString();
3132 si.contentDescription = appInfo.contentDescription;
3133 infoUpdated = true;
3134 }
3135
3136 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3137 // Since package was just updated, the target must be available now.
3138 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3139 shortcutUpdated = true;
3140 }
3141 }
3142
3143 if (infoUpdated || shortcutUpdated) {
3144 updatedShortcuts.add(si);
3145 }
3146 if (infoUpdated) {
3147 updateItemInDatabase(context, si);
3148 }
3149 } else if (info instanceof LauncherAppWidgetInfo) {
3150 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3151 if (mUser.equals(widgetInfo.user)
3152 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3153 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3154 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3155 widgets.add(widgetInfo);
3156 updateItemInDatabase(context, widgetInfo);
3157 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003158 }
3159 }
3160 }
3161
Sunny Goyal4390ace2014-10-13 11:33:11 -07003162 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3163 mHandler.post(new Runnable() {
3164
3165 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003166 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003167 if (callbacks == cb && cb != null) {
3168 callbacks.bindShortcutsChanged(
3169 updatedShortcuts, removedShortcuts, mUser);
3170 }
3171 }
3172 });
3173 if (!removedShortcuts.isEmpty()) {
3174 deleteItemsFromDatabase(context, removedShortcuts);
3175 }
3176 }
3177 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003178 mHandler.post(new Runnable() {
3179 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003180 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003181 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003182 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003183 }
3184 }
3185 });
3186 }
3187 }
3188
Winson Chungdf95eb12013-10-16 14:57:07 -07003189 final ArrayList<String> removedPackageNames =
3190 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003191 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003192 // Mark all packages in the broadcast to be removed
3193 removedPackageNames.addAll(Arrays.asList(packages));
3194 } else if (mOp == OP_UPDATE) {
3195 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003196 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003197 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003198 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003199 }
3200 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003201 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003202
Winson Chungdf95eb12013-10-16 14:57:07 -07003203 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003204 final int removeReason;
3205 if (mOp == OP_UNAVAILABLE) {
3206 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3207 } else {
3208 // Remove all the components associated with this package
3209 for (String pn : removedPackageNames) {
3210 deletePackageFromDatabase(context, pn, mUser);
3211 }
3212 // Remove all the specific components
3213 for (AppInfo a : removedApps) {
3214 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3215 deleteItemsFromDatabase(context, infos);
3216 }
3217 removeReason = 0;
3218 }
3219
Winson Chungdf95eb12013-10-16 14:57:07 -07003220 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003221 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003222 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003223 mHandler.post(new Runnable() {
3224 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003225 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003226 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003227 callbacks.bindComponentsRemoved(
3228 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003229 }
3230 }
3231 });
Joe Onoratobe386092009-11-17 17:32:16 -08003232 }
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003233 if (Build.VERSION.SDK_INT < 17) {
3234 loadAndBindWidgetsAndShortcuts(context, callbacks);
3235 }
Adam Cohen4caf2982013-08-20 18:54:31 -07003236 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003237 mHandler.post(new Runnable() {
3238 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003239 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003240 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003241 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003242 }
3243 }
3244 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003245 }
3246 }
3247
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003248 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3249 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003250 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003251 if (sBgWidgetProviders == null || refresh) {
3252 sBgWidgetProviders = new HashMap<>();
3253 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3254 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003255
Robin Lee26ace122015-03-16 19:41:43 +00003256 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3257 for (AppWidgetProviderInfo pInfo : widgets) {
3258 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3259 UserHandleCompat user = wm.getUser(info);
3260 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3261 }
3262
3263 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3264 for (CustomAppWidget widget : customWidgets) {
3265 info = new LauncherAppWidgetProviderInfo(context, widget);
3266 UserHandleCompat user = wm.getUser(info);
3267 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3268 }
Adam Cohen59400422014-03-05 18:07:04 -08003269 }
Adam Cohen59400422014-03-05 18:07:04 -08003270 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3271 }
3272 }
3273
Robin Lee26ace122015-03-16 19:41:43 +00003274 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3275 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003276 synchronized (sBgLock) {
3277 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003278 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003279 }
Robin Lee26ace122015-03-16 19:41:43 +00003280 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003281 }
3282 }
3283
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003284 public void loadAndBindWidgetsAndShortcuts(final Context context, final Callbacks callbacks) {
3285 runOnWorkerThread(new Runnable(){
3286 @Override
3287 public void run() {
3288 final ArrayList<Object> list =
3289 getSortedWidgetsAndShortcuts(context, true /* refresh */);
3290 mHandler.post(new Runnable() {
3291 @Override
3292 public void run() {
3293 Callbacks cb = getCallback();
3294 if (callbacks == cb && cb != null) {
3295 callbacks.bindPackagesUpdated(list);
3296 }
3297 }
3298 });
3299 }
3300 });
3301 }
3302
Winson Chungb745afb2015-03-02 11:51:23 -08003303 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003304 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003305 PackageManager packageManager = context.getPackageManager();
3306 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003307 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003308 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3309 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003310 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003311 return widgetsAndShortcuts;
3312 }
3313
Adam Cohen091440a2015-03-18 14:16:05 -07003314 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003315 UserHandleCompat user) {
3316 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3317 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003318 }
Adam Cohen556f6132014-01-15 15:18:08 -08003319
Kenny Guyed131872014-04-30 03:02:21 +01003320 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3321 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003322 if (cn == null) {
3323 return false;
3324 }
Kenny Guyed131872014-04-30 03:02:21 +01003325 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3326 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003327 return false;
3328 }
Kenny Guyed131872014-04-30 03:02:21 +01003329 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003330 }
3331
Adam Cohena28b78e2014-05-20 17:03:04 -07003332 public static boolean isValidPackage(Context context, String packageName,
3333 UserHandleCompat user) {
3334 if (packageName == null) {
3335 return false;
3336 }
3337 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3338 return launcherApps.isPackageEnabledForProfile(packageName, user);
3339 }
3340
Joe Onorato9c1289c2009-08-17 11:03:03 -04003341 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003342 * Make an ShortcutInfo object for a restored application or shortcut item that points
3343 * to a package that is not yet installed on the system.
3344 */
Sunny Goyal34942622014-08-29 17:20:55 -07003345 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003346 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003347 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003348 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003349 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003350
3351 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3352 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3353 if (!TextUtils.isEmpty(title)) {
3354 info.title = title;
3355 }
3356 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3357 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3358 if (TextUtils.isEmpty(info.title)) {
3359 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3360 }
3361 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3362 } else {
3363 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3364 }
3365
Kenny Guyc2bd8102014-06-30 12:30:31 +01003366 info.contentDescription = mUserManager.getBadgedLabelForUser(
3367 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003368 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003369 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003370 return info;
3371 }
3372
3373 /**
3374 * Make an Intent object for a restored application or shortcut item that points
3375 * to the market page for the item.
3376 */
Adam Cohen091440a2015-03-18 14:16:05 -07003377 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003378 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003379 return getMarketIntent(componentName.getPackageName());
3380 }
3381
3382 static Intent getMarketIntent(String packageName) {
3383 return new Intent(Intent.ACTION_VIEW)
3384 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003385 .scheme("market")
3386 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003387 .appendQueryParameter("id", packageName)
3388 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003389 }
3390
3391 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003392 * Make an ShortcutInfo object for a shortcut that is an application.
3393 *
3394 * If c is not null, then it will be used to fill in missing data like the title and icon.
3395 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003396 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003397 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003398 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003399 if (user == null) {
3400 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003401 return null;
3402 }
3403
Kenny Guyed131872014-04-30 03:02:21 +01003404 ComponentName componentName = intent.getComponent();
3405 if (componentName == null) {
3406 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3407 return null;
3408 }
3409
3410 Intent newIntent = new Intent(intent.getAction(), null);
3411 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3412 newIntent.setComponent(componentName);
3413 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003414 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003415 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3416 return null;
3417 }
3418
3419 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003420 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003421 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3422 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3423 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003424 }
3425
Joe Onorato56d82912010-03-07 14:32:10 -05003426 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003427 if (TextUtils.isEmpty(info.title) && c != null) {
3428 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003429 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003430
Joe Onorato56d82912010-03-07 14:32:10 -05003431 // fall back to the class name of the activity
3432 if (info.title == null) {
3433 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003434 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003435
Joe Onorato9c1289c2009-08-17 11:03:03 -04003436 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003437 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003438 info.contentDescription = mUserManager.getBadgedLabelForUser(
3439 info.title.toString(), info.user);
Sunny Goyalfa401a12015-04-10 13:45:42 -07003440 if (lai != null) {
3441 info.flags = AppInfo.initFlags(lai);
3442 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003443 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003444 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003445
Winson Chung64359a52013-07-08 17:17:08 -07003446 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3447 ItemInfoFilter f) {
3448 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3449 for (ItemInfo i : infos) {
3450 if (i instanceof ShortcutInfo) {
3451 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003452 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003453 if (cn != null && f.filterItem(null, info, cn)) {
3454 filtered.add(info);
3455 }
3456 } else if (i instanceof FolderInfo) {
3457 FolderInfo info = (FolderInfo) i;
3458 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003459 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003460 if (cn != null && f.filterItem(info, s, cn)) {
3461 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003462 }
3463 }
Winson Chung64359a52013-07-08 17:17:08 -07003464 } else if (i instanceof LauncherAppWidgetInfo) {
3465 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3466 ComponentName cn = info.providerName;
3467 if (cn != null && f.filterItem(null, info, cn)) {
3468 filtered.add(info);
3469 }
Winson Chung8a435102012-08-30 17:16:53 -07003470 }
3471 }
Winson Chung64359a52013-07-08 17:17:08 -07003472 return new ArrayList<ItemInfo>(filtered);
3473 }
3474
Adam Cohen091440a2015-03-18 14:16:05 -07003475 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003476 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003477 ItemInfoFilter filter = new ItemInfoFilter() {
3478 @Override
3479 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003480 if (info.user == null) {
3481 return cn.equals(cname);
3482 } else {
3483 return cn.equals(cname) && info.user.equals(user);
3484 }
Winson Chung64359a52013-07-08 17:17:08 -07003485 }
3486 };
3487 return filterItemInfos(sBgItemsIdMap.values(), filter);
3488 }
3489
Sunny Goyal1a745e82014-10-02 15:58:31 -07003490 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003491 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003492 */
Adam Cohen091440a2015-03-18 14:16:05 -07003493 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003494 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3495 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003496
Joe Onorato56d82912010-03-07 14:32:10 -05003497 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003498 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003499 // Non-app shortcuts are only supported for current user.
3500 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003501 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003502
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003503 // TODO: If there's an explicit component and we can't install that, delete it.
3504
Joe Onorato56d82912010-03-07 14:32:10 -05003505 info.title = c.getString(titleIndex);
3506
Joe Onorato9c1289c2009-08-17 11:03:03 -04003507 int iconType = c.getInt(iconTypeIndex);
3508 switch (iconType) {
3509 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3510 String packageName = c.getString(iconPackageIndex);
3511 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003512 info.customIcon = false;
3513 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003514 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003515 // the db
3516 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003517 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003518 }
3519 // the fallback icon
3520 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003521 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003522 info.usingFallbackIcon = true;
3523 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003524 break;
3525 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003526 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003527 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003528 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003529 info.customIcon = false;
3530 info.usingFallbackIcon = true;
3531 } else {
3532 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003533 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003534 break;
3535 default:
Kenny Guyed131872014-04-30 03:02:21 +01003536 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003537 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003538 info.customIcon = false;
3539 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003540 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003541 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003542 return info;
3543 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003544
Sunny Goyal2350bc92014-10-14 16:42:54 -07003545 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003546 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3547 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3548 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3549
Adam Cohend9198822011-11-22 16:42:47 -08003550 if (intent == null) {
3551 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3552 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3553 return null;
3554 }
3555
Joe Onorato0589f0f2010-02-08 13:44:00 -08003556 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003557 boolean customIcon = false;
3558 ShortcutIconResource iconResource = null;
3559
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003560 if (bitmap instanceof Bitmap) {
3561 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003562 customIcon = true;
3563 } else {
3564 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003565 if (extra instanceof ShortcutIconResource) {
3566 iconResource = (ShortcutIconResource) extra;
3567 icon = Utilities.createIconBitmap(iconResource.packageName,
3568 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003569 }
3570 }
3571
Michael Jurkac9d95c52011-08-29 14:03:34 -07003572 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003573
Kenny Guyed131872014-04-30 03:02:21 +01003574 // Only support intents for current user for now. Intents sent from other
3575 // users wouldn't get here without intent forwarding anyway.
3576 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003577 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003578 icon = mIconCache.getDefaultIcon(info.user);
3579 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003580 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003581 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003582
Joe Onorato0589f0f2010-02-08 13:44:00 -08003583 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003584 info.contentDescription = mUserManager.getBadgedLabelForUser(
3585 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003586 info.intent = intent;
3587 info.customIcon = customIcon;
3588 info.iconResource = iconResource;
3589
3590 return info;
3591 }
3592
Joe Onorato9c1289c2009-08-17 11:03:03 -04003593 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003594 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003595 * or make a new one.
3596 */
Adam Cohen091440a2015-03-18 14:16:05 -07003597 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003598 // See if a placeholder was created for us already
3599 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003600 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003601 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003602 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003603 folders.put(id, folderInfo);
3604 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003605 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003606 }
3607
Winson Chung1ed747a2011-05-03 16:18:34 -07003608 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003609 private final AppWidgetManagerCompat mManager;
3610 private final PackageManager mPackageManager;
3611 private final HashMap<Object, String> mLabelCache;
3612 private final Collator mCollator;
3613
Hyunyoung Song3f471442015-04-08 19:01:34 -07003614 public WidgetAndShortcutNameComparator(Context context) {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003615 mManager = AppWidgetManagerCompat.getInstance(context);
3616 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003617 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003618 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003619 }
3620 public final int compare(Object a, Object b) {
3621 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003622 if (mLabelCache.containsKey(a)) {
3623 labelA = mLabelCache.get(a);
3624 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003625 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3626 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003627 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003628 mLabelCache.put(a, labelA);
3629 }
3630 if (mLabelCache.containsKey(b)) {
3631 labelB = mLabelCache.get(b);
3632 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003633 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003634 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003635 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003636 mLabelCache.put(b, labelB);
3637 }
Winson Chung11904872012-09-17 16:58:46 -07003638 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003639 }
3640 };
Joe Onoratobe386092009-11-17 17:32:16 -08003641
Sunny Goyal651077b2014-06-30 14:15:31 -07003642 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3643 return (provider != null) && (provider.provider != null)
3644 && (provider.provider.getPackageName() != null);
3645 }
3646
Joe Onoratobe386092009-11-17 17:32:16 -08003647 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003648 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003649 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3650 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3651 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3652 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003653 if (mLoaderTask != null) {
3654 mLoaderTask.dumpState();
3655 } else {
3656 Log.d(TAG, "mLoaderTask=null");
3657 }
Joe Onoratobe386092009-11-17 17:32:16 -08003658 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003659
3660 public Callbacks getCallback() {
3661 return mCallbacks != null ? mCallbacks.get() : null;
3662 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07003663
3664 /**
3665 * @return {@link FolderInfo} if its already loaded.
3666 */
3667 public FolderInfo findFolderById(Long folderId) {
3668 synchronized (sBgLock) {
3669 return sBgFolders.get(folderId);
3670 }
3671 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003672}