blob: 424f649fb716524ead90381ea9fb74c2d7d97b6b [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
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001869 ShortcutInfo info;
1870 String intentDescription;
1871 LauncherAppWidgetInfo appWidgetInfo;
1872 int container;
1873 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001874 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001875 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001876 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001877
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001878 while (!mStopped && c.moveToNext()) {
1879 try {
1880 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001881 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001882 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001883
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001884 switch (itemType) {
1885 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1886 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001887 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001888 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001889 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001890 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001891 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001892 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001893 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001894 if (user == null) {
1895 // User has been deleted remove the item.
1896 itemsToRemove.add(id);
1897 continue;
1898 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001899 try {
1900 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001901 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001902 if (cn != null && cn.getPackageName() != null) {
1903 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1904 cn.getPackageName(), user);
1905 boolean validComponent = validPkg &&
1906 launcherApps.isActivityEnabledForProfile(cn, user);
1907
1908 if (validComponent) {
1909 if (restored) {
1910 // no special handling necessary for this item
1911 restoredRows.add(id);
1912 restored = false;
1913 }
1914 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001915 intent = null;
1916 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1917 // We allow auto install apps to have their intent
1918 // updated after an install.
1919 intent = manager.getLaunchIntentForPackage(
1920 cn.getPackageName());
1921 if (intent != null) {
1922 ContentValues values = new ContentValues();
1923 values.put(LauncherSettings.Favorites.INTENT,
1924 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001925 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001926 }
1927 }
1928
1929 if (intent == null) {
1930 // The app is installed but the component is no
1931 // longer available.
1932 Launcher.addDumpLog(TAG,
1933 "Invalid component removed: " + cn, true);
1934 itemsToRemove.add(id);
1935 continue;
1936 } else {
1937 // no special handling necessary for this item
1938 restoredRows.add(id);
1939 restored = false;
1940 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001941 } else if (restored) {
1942 // Package is not yet available but might be
1943 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001944 Launcher.addDumpLog(TAG,
1945 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001946
1947 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1948 // Restore has started once.
1949 } else if (installingPkgs.contains(cn.getPackageName())) {
1950 // App restore has started. Update the flag
1951 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1952 ContentValues values = new ContentValues();
1953 values.put(LauncherSettings.Favorites.RESTORED,
1954 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001955 updateItem(id, values);
1956 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1957 // This is a common app. Try to replace this.
1958 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1959 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1960 if (parser.findDefaultApp()) {
1961 // Default app found. Replace it.
1962 intent = parser.parsedIntent;
1963 cn = intent.getComponent();
1964 ContentValues values = parser.parsedValues;
1965 values.put(LauncherSettings.Favorites.RESTORED, 0);
1966 updateItem(id, values);
1967 restored = false;
1968 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001969
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001970 } else if (REMOVE_UNRESTORED_ICONS) {
1971 Launcher.addDumpLog(TAG,
1972 "Unrestored package removed: " + cn, true);
1973 itemsToRemove.add(id);
1974 continue;
1975 }
Sunny Goyal94485362014-09-18 16:13:58 -07001976 } else if (REMOVE_UNRESTORED_ICONS) {
1977 Launcher.addDumpLog(TAG,
1978 "Unrestored package removed: " + cn, true);
1979 itemsToRemove.add(id);
1980 continue;
1981 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001982 } else if (launcherApps.isAppEnabled(
1983 manager, cn.getPackageName(),
1984 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1985 // Package is present but not available.
1986 allowMissingTarget = true;
1987 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1988 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001989 // SdCard is not ready yet. Package might get available,
1990 // once it is ready.
1991 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1992 + " (check again later)", true);
1993 HashSet<String> pkgs = sPendingPackages.get(user);
1994 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001995 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001996 sPendingPackages.put(user, pkgs);
1997 }
1998 pkgs.add(cn.getPackageName());
1999 allowMissingTarget = true;
2000 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002001
2002 } else {
2003 // Do not wait for external media load anymore.
2004 // Log the invalid package, and remove it
2005 Launcher.addDumpLog(TAG,
2006 "Invalid package removed: " + cn, true);
2007 itemsToRemove.add(id);
2008 continue;
Winson Chungee055712013-07-30 14:46:24 -07002009 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002010 } else if (cn == null) {
2011 // For shortcuts with no component, keep them as they are
2012 restoredRows.add(id);
2013 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002014 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002015 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002016 Launcher.addDumpLog(TAG,
2017 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002018 continue;
2019 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002020
Sunny Goyal34b65272015-03-11 16:56:52 -07002021 container = c.getInt(containerIndex);
2022 boolean useLowResIcon = container >= 0 &&
2023 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2024
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002025 if (itemReplaced) {
2026 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002027 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002028 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002029 } else {
2030 // Don't replace items for other profiles.
2031 itemsToRemove.add(id);
2032 continue;
2033 }
2034 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002035 if (user.equals(UserHandleCompat.myUserHandle())) {
2036 Launcher.addDumpLog(TAG,
2037 "constructing info for partially restored package",
2038 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002039 info = getRestoredItemInfo(c, titleIndex, intent,
2040 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002041 intent = getRestoredItemIntent(c, context, intent);
2042 } else {
2043 // Don't restore items for other profiles.
2044 itemsToRemove.add(id);
2045 continue;
2046 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002047 } else if (itemType ==
2048 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002049 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002050 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002051 } else {
2052 info = getShortcutInfo(c, context, iconTypeIndex,
2053 iconPackageIndex, iconResourceIndex, iconIndex,
2054 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002055
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002056 // App shortcuts that used to be automatically added to Launcher
2057 // didn't always have the correct intent flags set, so do that
2058 // here
2059 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002060 intent.getCategories() != null &&
2061 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002062 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002063 intent.addFlags(
2064 Intent.FLAG_ACTIVITY_NEW_TASK |
2065 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2066 }
Michael Jurka96879562012-03-22 05:54:33 -07002067 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002068
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002069 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002070 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002072 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002073 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 info.cellX = c.getInt(cellXIndex);
2075 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002076 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002077 info.spanX = 1;
2078 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002079 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002080 info.isDisabled = disabledState;
2081 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2082 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2083 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002084
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002085 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002086 if (!checkItemPlacement(occupied, info)) {
2087 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002088 break;
2089 }
2090
2091 switch (container) {
2092 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2093 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2094 sBgWorkspaceItems.add(info);
2095 break;
2096 default:
2097 // Item is in a user folder
2098 FolderInfo folderInfo =
2099 findOrMakeFolder(sBgFolders, container);
2100 folderInfo.add(info);
2101 break;
2102 }
2103 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002104 } else {
2105 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002106 }
2107 break;
2108
2109 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2110 id = c.getLong(idIndex);
2111 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2112
2113 folderInfo.title = c.getString(titleIndex);
2114 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002115 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002116 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002117 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 folderInfo.cellX = c.getInt(cellXIndex);
2119 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002120 folderInfo.spanX = 1;
2121 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002122 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002123
Daniel Sandler8802e962010-05-26 16:28:16 -04002124 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002125 if (!checkItemPlacement(occupied, folderInfo)) {
2126 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002127 break;
2128 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002129
Joe Onorato9c1289c2009-08-17 11:03:03 -04002130 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002131 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2132 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2133 sBgWorkspaceItems.add(folderInfo);
2134 break;
Joe Onorato36115782010-06-17 13:28:48 -04002135 }
Joe Onorato17a89222011-02-08 17:26:11 -08002136
Chris Wrenf4d08112014-01-16 18:13:56 -05002137 if (restored) {
2138 // no special handling required for restored folders
2139 restoredRows.add(id);
2140 }
2141
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002142 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2143 sBgFolders.put(folderInfo.id, folderInfo);
2144 break;
2145
2146 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002147 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002148 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002149 boolean customWidget = itemType ==
2150 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2151
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002152 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002153 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002154 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002155 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002156 final ComponentName component =
2157 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002158
Sunny Goyal651077b2014-06-30 14:15:31 -07002159 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002160 final boolean isIdValid = (restoreStatus &
2161 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002162
Sunny Goyalff572272014-07-23 13:58:07 -07002163 final boolean wasProviderReady = (restoreStatus &
2164 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002165
Adam Cohen59400422014-03-05 18:07:04 -08002166 final LauncherAppWidgetProviderInfo provider =
2167 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002168 ComponentName.unflattenFromString(savedProvider),
2169 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002170
2171 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002172 if (!isSafeMode && !customWidget &&
2173 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002174 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002175 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002176
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002177 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002178 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 itemsToRemove.add(id);
2180 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002181 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002182 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2183 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002184
2185 if (!customWidget) {
2186 int[] minSpan =
2187 Launcher.getMinSpanForWidget(context, provider);
2188 appWidgetInfo.minSpanX = minSpan[0];
2189 appWidgetInfo.minSpanY = minSpan[1];
2190 }
Sunny Goyalff572272014-07-23 13:58:07 -07002191
2192 int status = restoreStatus;
2193 if (!wasProviderReady) {
2194 // If provider was not previously ready, update the
2195 // status and UI flag.
2196
2197 // Id would be valid only if the widget restore broadcast was received.
2198 if (isIdValid) {
2199 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2200 } else {
2201 status &= ~LauncherAppWidgetInfo
2202 .FLAG_PROVIDER_NOT_READY;
2203 }
2204 }
2205 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002206 } else {
2207 Log.v(TAG, "Widget restore pending id=" + id
2208 + " appWidgetId=" + appWidgetId
2209 + " status =" + restoreStatus);
2210 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002211 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002212 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002213
2214 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2215 // Restore has started once.
2216 } else if (installingPkgs.contains(component.getPackageName())) {
2217 // App restore has started. Update the flag
2218 appWidgetInfo.restoreStatus |=
2219 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002220 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002221 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002222 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002223 itemsToRemove.add(id);
2224 continue;
2225 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002226 }
Sunny Goyalff572272014-07-23 13:58:07 -07002227
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002228 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002229 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002230 appWidgetInfo.cellX = c.getInt(cellXIndex);
2231 appWidgetInfo.cellY = c.getInt(cellYIndex);
2232 appWidgetInfo.spanX = c.getInt(spanXIndex);
2233 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002234
Adam Cohen59400422014-03-05 18:07:04 -08002235 if (!customWidget) {
2236 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2237 appWidgetInfo.minSpanX = minSpan[0];
2238 appWidgetInfo.minSpanY = minSpan[1];
2239 }
2240
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002241 container = c.getInt(containerIndex);
2242 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2243 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2244 Log.e(TAG, "Widget found where container != " +
2245 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2246 continue;
2247 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002248
Adam Cohene25af792013-06-06 23:08:25 -07002249 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002250 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002251 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2252 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002253 break;
2254 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002255
Adam Cohen59400422014-03-05 18:07:04 -08002256 if (!customWidget) {
2257 String providerName =
2258 appWidgetInfo.providerName.flattenToString();
2259 if (!providerName.equals(savedProvider) ||
2260 (appWidgetInfo.restoreStatus != restoreStatus)) {
2261 ContentValues values = new ContentValues();
2262 values.put(
2263 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2264 providerName);
2265 values.put(LauncherSettings.Favorites.RESTORED,
2266 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002267 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002268 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002269 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002270 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2271 sBgAppWidgets.add(appWidgetInfo);
2272 }
Joe Onorato36115782010-06-17 13:28:48 -04002273 break;
2274 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002275 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002276 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002277 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002278 }
2279 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002280 if (c != null) {
2281 c.close();
2282 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002283 }
2284
Winson Chungba9c37f2013-08-30 14:11:37 -07002285 // Break early if we've stopped loading
2286 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002287 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002288 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002289 }
2290
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002291 if (itemsToRemove.size() > 0) {
2292 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002293 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002294 // Remove dead items
2295 for (long id : itemsToRemove) {
2296 if (DEBUG_LOADERS) {
2297 Log.d(TAG, "Removed id = " + id);
2298 }
2299 // Don't notify content observers
2300 try {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002301 client.delete(LauncherSettings.Favorites.getContentUri(id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002302 } catch (RemoteException e) {
2303 Log.w(TAG, "Could not remove id = " + id);
2304 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002305 }
2306 }
2307
Chris Wrenf4d08112014-01-16 18:13:56 -05002308 if (restoredRows.size() > 0) {
2309 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002310 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002311 // Update restored items that no longer require special handling
2312 try {
2313 StringBuilder selectionBuilder = new StringBuilder();
2314 selectionBuilder.append(LauncherSettings.Favorites._ID);
2315 selectionBuilder.append(" IN (");
2316 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2317 selectionBuilder.append(")");
2318 ContentValues values = new ContentValues();
2319 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002320 updater.update(LauncherSettings.Favorites.CONTENT_URI,
Chris Wrenf4d08112014-01-16 18:13:56 -05002321 values, selectionBuilder.toString(), null);
2322 } catch (RemoteException e) {
2323 Log.w(TAG, "Could not update restored rows");
2324 }
2325 }
2326
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002327 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2328 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002329 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002330 null, sWorker);
2331 }
2332
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002333 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2334 // Log to disk
2335 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2336 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002337
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002338 // Remove any empty screens
2339 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2340 for (ItemInfo item: sBgItemsIdMap.values()) {
2341 long screenId = item.screenId;
2342 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2343 unusedScreens.contains(screenId)) {
2344 unusedScreens.remove(screenId);
2345 }
2346 }
2347
2348 // If there are any empty screens remove them, and update.
2349 if (unusedScreens.size() != 0) {
2350 // Log to disk
2351 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2352 TextUtils.join(", ", unusedScreens), true);
2353
2354 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002356 }
2357
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002358 if (DEBUG_LOADERS) {
2359 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2360 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002361 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002362 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002363 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002364
Daniel Sandler566da102013-06-25 23:43:45 -04002365 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002366 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002367 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002368 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002369 line += " | ";
2370 }
Winson Chung892c74d2013-08-22 16:15:50 -07002371 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002372 ItemInfo[][] screen = occupied.get(screenId);
2373 if (x < screen.length && y < screen[x].length) {
2374 line += (screen[x][y] != null) ? "#" : ".";
2375 } else {
2376 line += "!";
2377 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002378 }
Joe Onorato36115782010-06-17 13:28:48 -04002379 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002380 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002381 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002382 }
Joe Onorato36115782010-06-17 13:28:48 -04002383 }
Adam Cohene25af792013-06-06 23:08:25 -07002384 }
2385
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002386 /**
2387 * Partially updates the item without any notification. Must be called on the worker thread.
2388 */
2389 private void updateItem(long itemId, ContentValues update) {
2390 mContext.getContentResolver().update(
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002391 LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002392 update,
2393 BaseColumns._ID + "= ?",
2394 new String[]{Long.toString(itemId)});
2395 }
2396
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002397 /** Filters the set of items who are directly or indirectly (via another container) on the
2398 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002399 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002400 ArrayList<ItemInfo> allWorkspaceItems,
2401 ArrayList<ItemInfo> currentScreenItems,
2402 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002403 // Purge any null ItemInfos
2404 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2405 while (iter.hasNext()) {
2406 ItemInfo i = iter.next();
2407 if (i == null) {
2408 iter.remove();
2409 }
2410 }
2411
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002412 // Order the set of items by their containers first, this allows use to walk through the
2413 // list sequentially, build up a list of containers that are in the specified screen,
2414 // as well as all items in those containers.
2415 Set<Long> itemsOnScreen = new HashSet<Long>();
2416 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2417 @Override
2418 public int compare(ItemInfo lhs, ItemInfo rhs) {
2419 return (int) (lhs.container - rhs.container);
2420 }
2421 });
2422 for (ItemInfo info : allWorkspaceItems) {
2423 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002424 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002425 currentScreenItems.add(info);
2426 itemsOnScreen.add(info.id);
2427 } else {
2428 otherScreenItems.add(info);
2429 }
2430 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2431 currentScreenItems.add(info);
2432 itemsOnScreen.add(info.id);
2433 } else {
2434 if (itemsOnScreen.contains(info.container)) {
2435 currentScreenItems.add(info);
2436 itemsOnScreen.add(info.id);
2437 } else {
2438 otherScreenItems.add(info);
2439 }
2440 }
2441 }
2442 }
2443
2444 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002445 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002446 ArrayList<LauncherAppWidgetInfo> appWidgets,
2447 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2448 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002449
2450 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002451 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002453 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002454 currentScreenWidgets.add(widget);
2455 } else {
2456 otherScreenWidgets.add(widget);
2457 }
2458 }
2459 }
2460
2461 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002462 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002463 HashMap<Long, ItemInfo> itemsIdMap,
2464 HashMap<Long, FolderInfo> folders,
2465 HashMap<Long, FolderInfo> currentScreenFolders,
2466 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002467
2468 for (long id : folders.keySet()) {
2469 ItemInfo info = itemsIdMap.get(id);
2470 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002471 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002472 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002473 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002474 currentScreenFolders.put(id, folder);
2475 } else {
2476 otherScreenFolders.put(id, folder);
2477 }
2478 }
2479 }
2480
2481 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2482 * right) */
2483 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002484 final LauncherAppState app = LauncherAppState.getInstance();
2485 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002486 // XXX: review this
2487 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002488 @Override
2489 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002490 int cellCountX = (int) grid.numColumns;
2491 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002492 int screenOffset = cellCountX * cellCountY;
2493 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002494 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002495 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002496 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002497 rhs.cellY * cellCountX + rhs.cellX);
2498 return (int) (lr - rr);
2499 }
2500 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002501 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002502
Adam Cohendcd297f2013-06-18 13:13:40 -07002503 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2504 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002505 final Runnable r = new Runnable() {
2506 @Override
2507 public void run() {
2508 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2509 if (callbacks != null) {
2510 callbacks.bindScreens(orderedScreens);
2511 }
2512 }
2513 };
2514 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2515 }
2516
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002517 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2518 final ArrayList<ItemInfo> workspaceItems,
2519 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2520 final HashMap<Long, FolderInfo> folders,
2521 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002522
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002523 final boolean postOnMainThread = (deferredBindRunnables != null);
2524
2525 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002526 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002527 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002528 final int start = i;
2529 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 final Runnable r = new Runnable() {
2531 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002532 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002533 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002534 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002535 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2536 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002537 }
2538 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002539 };
2540 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002541 synchronized (deferredBindRunnables) {
2542 deferredBindRunnables.add(r);
2543 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002544 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002545 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002546 }
Joe Onorato36115782010-06-17 13:28:48 -04002547 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002548
2549 // Bind the folders
2550 if (!folders.isEmpty()) {
2551 final Runnable r = new Runnable() {
2552 public void run() {
2553 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2554 if (callbacks != null) {
2555 callbacks.bindFolders(folders);
2556 }
2557 }
2558 };
2559 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002560 synchronized (deferredBindRunnables) {
2561 deferredBindRunnables.add(r);
2562 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002563 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002564 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002565 }
2566 }
2567
2568 // Bind the widgets, one at a time
2569 N = appWidgets.size();
2570 for (int i = 0; i < N; i++) {
2571 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2572 final Runnable r = new Runnable() {
2573 public void run() {
2574 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2575 if (callbacks != null) {
2576 callbacks.bindAppWidget(widget);
2577 }
2578 }
2579 };
2580 if (postOnMainThread) {
2581 deferredBindRunnables.add(r);
2582 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002583 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002584 }
2585 }
2586 }
2587
2588 /**
2589 * Binds all loaded data to actual views on the main thread.
2590 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002591 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002592 final long t = SystemClock.uptimeMillis();
2593 Runnable r;
2594
2595 // Don't use these two variables in any of the callback runnables.
2596 // Otherwise we hold a reference to them.
2597 final Callbacks oldCallbacks = mCallbacks.get();
2598 if (oldCallbacks == null) {
2599 // This launcher has exited and nobody bothered to tell us. Just bail.
2600 Log.w(TAG, "LoaderTask running with no launcher");
2601 return;
2602 }
2603
Winson Chung9b9fb962013-11-15 15:39:34 -08002604 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002605 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2606 ArrayList<LauncherAppWidgetInfo> appWidgets =
2607 new ArrayList<LauncherAppWidgetInfo>();
2608 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2609 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002610 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002611 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002612 workspaceItems.addAll(sBgWorkspaceItems);
2613 appWidgets.addAll(sBgAppWidgets);
2614 folders.putAll(sBgFolders);
2615 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002616 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002617 }
2618
Derek Prothro7aff3992013-12-10 14:00:37 -05002619 final boolean isLoadingSynchronously =
2620 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002621 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002622 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002623 if (currScreen >= orderedScreenIds.size()) {
2624 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002625 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002626 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002627 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002628 final long currentScreenId = currentScreen < 0
2629 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002630
2631 // Load all the items that are on the current page first (and in the process, unbind
2632 // all the existing workspace items before we call startBinding() below.
2633 unbindWorkspaceItemsOnMainThread();
2634
2635 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002636 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2637 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2638 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2639 new ArrayList<LauncherAppWidgetInfo>();
2640 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2641 new ArrayList<LauncherAppWidgetInfo>();
2642 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2643 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2644
Winson Chung9b9fb962013-11-15 15:39:34 -08002645 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002646 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002647 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002648 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002649 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002650 otherFolders);
2651 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2652 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2653
2654 // Tell the workspace that we're about to start binding items
2655 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002656 public void run() {
2657 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2658 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002659 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002660 }
2661 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002662 };
Winson Chung81b52252012-08-27 15:34:29 -07002663 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002664
Adam Cohendcd297f2013-06-18 13:13:40 -07002665 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2666
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667 // Load items on the current page
2668 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2669 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002670 if (isLoadingSynchronously) {
2671 r = new Runnable() {
2672 public void run() {
2673 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002674 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002675 callbacks.onPageBoundSynchronously(currentScreen);
2676 }
2677 }
2678 };
Winson Chung81b52252012-08-27 15:34:29 -07002679 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002680 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002681
Winson Chung4a2afa32012-07-19 14:53:05 -07002682 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2683 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002684 synchronized (mDeferredBindRunnables) {
2685 mDeferredBindRunnables.clear();
2686 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002687 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002688 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002689
2690 // Tell the workspace that we're done binding items
2691 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002692 public void run() {
2693 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2694 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002695 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002696 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002697
Winson Chung98e030b2012-05-07 16:01:11 -07002698 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002699 if (DEBUG_LOADERS) {
2700 Log.d(TAG, "bound workspace in "
2701 + (SystemClock.uptimeMillis()-t) + "ms");
2702 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002703
2704 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002705 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002706 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002707 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002708 synchronized (mDeferredBindRunnables) {
2709 mDeferredBindRunnables.add(r);
2710 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002711 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002712 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002713 }
Joe Onorato36115782010-06-17 13:28:48 -04002714 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002715
Joe Onorato36115782010-06-17 13:28:48 -04002716 private void loadAndBindAllApps() {
2717 if (DEBUG_LOADERS) {
2718 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2719 }
2720 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002721 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002722 synchronized (LoaderTask.this) {
2723 if (mStopped) {
2724 return;
2725 }
2726 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002727 }
Joe Onorato36115782010-06-17 13:28:48 -04002728 } else {
2729 onlyBindAllApps();
2730 }
2731 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002732
Joe Onorato36115782010-06-17 13:28:48 -04002733 private void onlyBindAllApps() {
2734 final Callbacks oldCallbacks = mCallbacks.get();
2735 if (oldCallbacks == null) {
2736 // This launcher has exited and nobody bothered to tell us. Just bail.
2737 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2738 return;
2739 }
2740
2741 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002742 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002743 final ArrayList<AppInfo> list
2744 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002745 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002746 public void run() {
2747 final long t = SystemClock.uptimeMillis();
2748 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2749 if (callbacks != null) {
2750 callbacks.bindAllApplications(list);
2751 }
2752 if (DEBUG_LOADERS) {
2753 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2754 + (SystemClock.uptimeMillis()-t) + "ms");
2755 }
2756 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002757 };
2758 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002759 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002760 r.run();
2761 } else {
2762 mHandler.post(r);
2763 }
Joe Onorato36115782010-06-17 13:28:48 -04002764 }
2765
Winson Chung64359a52013-07-08 17:17:08 -07002766 private void loadAllApps() {
2767 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002768
Joe Onorato36115782010-06-17 13:28:48 -04002769 final Callbacks oldCallbacks = mCallbacks.get();
2770 if (oldCallbacks == null) {
2771 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002772 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002773 return;
2774 }
2775
2776 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2777 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2778
Kenny Guyed131872014-04-30 03:02:21 +01002779 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2780
Winson Chung64359a52013-07-08 17:17:08 -07002781 // Clear the list of apps
2782 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002783 SharedPreferences prefs = mContext.getSharedPreferences(
2784 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002785 for (UserHandleCompat user : profiles) {
2786 // Query for the set of apps
2787 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2788 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2789 if (DEBUG_LOADERS) {
2790 Log.d(TAG, "getActivityList took "
2791 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2792 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2793 }
2794 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002795 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002796 if (apps == null || apps.isEmpty()) {
2797 return;
2798 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002799
2800 // Update icon cache
2801 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2802
2803 // If any package icon has changed (app was updated while launcher was dead),
2804 // update the corresponding shortcuts.
2805 if (!updatedPackages.isEmpty()) {
2806 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2807 synchronized (sBgLock) {
2808 for (ItemInfo info : sBgItemsIdMap.values()) {
2809 if (info instanceof ShortcutInfo && user.equals(info.user)
2810 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2811 ShortcutInfo si = (ShortcutInfo) info;
2812 ComponentName cn = si.getTargetComponent();
2813 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2814 si.updateIcon(mIconCache);
2815 updates.add(si);
2816 }
2817 }
2818 }
2819 }
2820
2821 if (!updates.isEmpty()) {
2822 final UserHandleCompat userFinal = user;
2823 mHandler.post(new Runnable() {
2824
2825 public void run() {
2826 Callbacks cb = getCallback();
2827 if (cb != null) {
2828 cb.bindShortcutsChanged(
2829 updates, new ArrayList<ShortcutInfo>(), userFinal);
2830 }
2831 }
2832 });
2833 }
Kenny Guyed131872014-04-30 03:02:21 +01002834 }
Joe Onorato36115782010-06-17 13:28:48 -04002835
Kenny Guyed131872014-04-30 03:02:21 +01002836 // Create the ApplicationInfos
2837 for (int i = 0; i < apps.size(); i++) {
2838 LauncherActivityInfoCompat app = apps.get(i);
2839 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002840 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002841 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002842
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002843 if (!user.equals(UserHandleCompat.myUserHandle())) {
2844 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
2845 if (heuristic != null) {
2846 heuristic.processUserApps(apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002847 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002848 }
Winson Chung64359a52013-07-08 17:17:08 -07002849 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002850 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002851 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2852 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002853
2854 // Post callback on main thread
2855 mHandler.post(new Runnable() {
2856 public void run() {
2857 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002858 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002859 if (callbacks != null) {
2860 callbacks.bindAllApplications(added);
2861 if (DEBUG_LOADERS) {
2862 Log.d(TAG, "bound " + added.size() + " apps in "
2863 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2864 }
2865 } else {
2866 Log.i(TAG, "not binding apps: no Launcher activity");
2867 }
2868 }
2869 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002870 // Cleanup any data stored for a deleted user.
2871 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Winson Chung64359a52013-07-08 17:17:08 -07002872
Joe Onorato36115782010-06-17 13:28:48 -04002873 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002874 Log.d(TAG, "Icons processed in "
2875 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002876 }
2877 }
2878
2879 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002880 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002881 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2882 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2883 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2884 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2885 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2886 }
Joe Onorato36115782010-06-17 13:28:48 -04002887 }
2888 }
2889
2890 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002891 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002892 }
2893
Adam Cohen091440a2015-03-18 14:16:05 -07002894 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002895
2896 @Override
2897 public void onReceive(Context context, Intent intent) {
2898 synchronized (sBgLock) {
2899 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2900 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002901 final PackageManager manager = context.getPackageManager();
2902 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2903 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002904 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2905 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002906 packagesRemoved.clear();
2907 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002908 for (String pkg : entry.getValue()) {
2909 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002910 boolean packageOnSdcard = launcherApps.isAppEnabled(
2911 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2912 if (packageOnSdcard) {
2913 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2914 packagesUnavailable.add(pkg);
2915 } else {
2916 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2917 packagesRemoved.add(pkg);
2918 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002919 }
2920 }
2921 if (!packagesRemoved.isEmpty()) {
2922 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2923 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2924 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002925 if (!packagesUnavailable.isEmpty()) {
2926 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2927 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2928 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002929 }
Sunny Goyal34942622014-08-29 17:20:55 -07002930 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002931 }
2932 }
2933 }
2934
Joe Onorato36115782010-06-17 13:28:48 -04002935 private class PackageUpdatedTask implements Runnable {
2936 int mOp;
2937 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002938 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002939
2940 public static final int OP_NONE = 0;
2941 public static final int OP_ADD = 1;
2942 public static final int OP_UPDATE = 2;
2943 public static final int OP_REMOVE = 3; // uninstlled
2944 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2945
2946
Kenny Guyed131872014-04-30 03:02:21 +01002947 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002948 mOp = op;
2949 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002950 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002951 }
2952
2953 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002954 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002955
2956 final String[] packages = mPackages;
2957 final int N = packages.length;
2958 switch (mOp) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002959 case OP_ADD: {
Joe Onorato36115782010-06-17 13:28:48 -04002960 for (int i=0; i<N; i++) {
2961 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002962 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002963 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002964 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002965
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002966 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2967 if (heuristic != null) {
2968 heuristic.processPackageAdd(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002969 }
Joe Onorato36115782010-06-17 13:28:48 -04002970 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002971 }
Joe Onorato36115782010-06-17 13:28:48 -04002972 case OP_UPDATE:
2973 for (int i=0; i<N; i++) {
2974 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002975 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002976 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002977 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002978 }
2979 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002980 case OP_REMOVE: {
2981 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2982 if (heuristic != null) {
2983 heuristic.processPackageRemoved(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002984 }
Joe Onorato36115782010-06-17 13:28:48 -04002985 for (int i=0; i<N; i++) {
2986 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002987 mIconCache.removeIconsForPkg(packages[i], mUser);
2988 }
2989 // Fall through
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002990 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002991 case OP_UNAVAILABLE:
2992 for (int i=0; i<N; i++) {
2993 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
2994 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002995 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002996 }
2997 break;
2998 }
2999
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003000 ArrayList<AppInfo> added = null;
3001 ArrayList<AppInfo> modified = null;
3002 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003003
Adam Cohen487f7dd2012-06-28 18:12:10 -07003004 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003005 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003006 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003007 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003008 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003009 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003010 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003011 }
Winson Chung5d55f332012-07-16 20:45:03 -07003012 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003013 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003014 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003015 }
3016
Sunny Goyale0f58d72014-11-10 18:05:31 -08003017 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003018 if (callbacks == null) {
3019 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3020 return;
3021 }
3022
Sunny Goyal4390ace2014-10-13 11:33:11 -07003023 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3024 new HashMap<ComponentName, AppInfo>();
3025
Joe Onorato36115782010-06-17 13:28:48 -04003026 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003027 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003028 for (AppInfo ai : added) {
3029 addedOrUpdatedApps.put(ai.componentName, ai);
3030 }
Joe Onorato36115782010-06-17 13:28:48 -04003031 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003032
Joe Onorato36115782010-06-17 13:28:48 -04003033 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003034 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003035 for (AppInfo ai : modified) {
3036 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003037 }
3038
Joe Onorato36115782010-06-17 13:28:48 -04003039 mHandler.post(new Runnable() {
3040 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003041 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003042 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003043 callbacks.bindAppsUpdated(modifiedFinal);
3044 }
3045 }
3046 });
3047 }
Winson Chung83892cc2013-05-01 16:53:33 -07003048
Sunny Goyal4390ace2014-10-13 11:33:11 -07003049 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003050 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003051 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3052 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3053 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3054
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003055 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003056 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003057 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003058 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3059 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003060 boolean infoUpdated = false;
3061 boolean shortcutUpdated = false;
3062
3063 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003064 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003065 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003066 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3067 si.iconResource.resourceName, mIconCache, context);
3068 if (icon != null) {
3069 si.setIcon(icon);
3070 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003071 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003072 }
3073 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003074
3075 ComponentName cn = si.getTargetComponent();
3076 if (cn != null && packageSet.contains(cn.getPackageName())) {
3077 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3078
3079 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003080 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3081 // Auto install icon
3082 PackageManager pm = context.getPackageManager();
3083 ResolveInfo matched = pm.resolveActivity(
3084 new Intent(Intent.ACTION_MAIN)
3085 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3086 PackageManager.MATCH_DEFAULT_ONLY);
3087 if (matched == null) {
3088 // Try to find the best match activity.
3089 Intent intent = pm.getLaunchIntentForPackage(
3090 cn.getPackageName());
3091 if (intent != null) {
3092 cn = intent.getComponent();
3093 appInfo = addedOrUpdatedApps.get(cn);
3094 }
3095
3096 if ((intent == null) || (appInfo == null)) {
3097 removedShortcuts.add(si);
3098 continue;
3099 }
3100 si.promisedIntent = intent;
3101 }
3102 }
3103
3104 // Restore the shortcut.
3105 si.intent = si.promisedIntent;
3106 si.promisedIntent = null;
3107 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3108 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3109 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
Sunny Goyalfa401a12015-04-10 13:45:42 -07003110 if (appInfo != null) {
3111 si.flags = appInfo.flags;
3112 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003113
3114 infoUpdated = true;
3115 si.updateIcon(mIconCache);
3116 }
3117
3118 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3119 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3120 si.updateIcon(mIconCache);
3121 si.title = appInfo.title.toString();
3122 si.contentDescription = appInfo.contentDescription;
3123 infoUpdated = true;
3124 }
3125
3126 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3127 // Since package was just updated, the target must be available now.
3128 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3129 shortcutUpdated = true;
3130 }
3131 }
3132
3133 if (infoUpdated || shortcutUpdated) {
3134 updatedShortcuts.add(si);
3135 }
3136 if (infoUpdated) {
3137 updateItemInDatabase(context, si);
3138 }
3139 } else if (info instanceof LauncherAppWidgetInfo) {
3140 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3141 if (mUser.equals(widgetInfo.user)
3142 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3143 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3144 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3145 widgets.add(widgetInfo);
3146 updateItemInDatabase(context, widgetInfo);
3147 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003148 }
3149 }
3150 }
3151
Sunny Goyal4390ace2014-10-13 11:33:11 -07003152 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3153 mHandler.post(new Runnable() {
3154
3155 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003156 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003157 if (callbacks == cb && cb != null) {
3158 callbacks.bindShortcutsChanged(
3159 updatedShortcuts, removedShortcuts, mUser);
3160 }
3161 }
3162 });
3163 if (!removedShortcuts.isEmpty()) {
3164 deleteItemsFromDatabase(context, removedShortcuts);
3165 }
3166 }
3167 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003168 mHandler.post(new Runnable() {
3169 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003170 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003171 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003172 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003173 }
3174 }
3175 });
3176 }
3177 }
3178
Winson Chungdf95eb12013-10-16 14:57:07 -07003179 final ArrayList<String> removedPackageNames =
3180 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003181 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003182 // Mark all packages in the broadcast to be removed
3183 removedPackageNames.addAll(Arrays.asList(packages));
3184 } else if (mOp == OP_UPDATE) {
3185 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003186 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003187 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003188 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003189 }
3190 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003191 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003192
Winson Chungdf95eb12013-10-16 14:57:07 -07003193 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003194 final int removeReason;
3195 if (mOp == OP_UNAVAILABLE) {
3196 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3197 } else {
3198 // Remove all the components associated with this package
3199 for (String pn : removedPackageNames) {
3200 deletePackageFromDatabase(context, pn, mUser);
3201 }
3202 // Remove all the specific components
3203 for (AppInfo a : removedApps) {
3204 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3205 deleteItemsFromDatabase(context, infos);
3206 }
3207 removeReason = 0;
3208 }
3209
Winson Chungdf95eb12013-10-16 14:57:07 -07003210 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003211 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003212 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003213 mHandler.post(new Runnable() {
3214 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003215 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003216 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003217 callbacks.bindComponentsRemoved(
3218 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003219 }
3220 }
3221 });
Joe Onoratobe386092009-11-17 17:32:16 -08003222 }
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003223 if (Build.VERSION.SDK_INT < 17) {
3224 loadAndBindWidgetsAndShortcuts(context, callbacks);
3225 }
Adam Cohen4caf2982013-08-20 18:54:31 -07003226 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003227 mHandler.post(new Runnable() {
3228 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003229 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003230 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003231 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003232 }
3233 }
3234 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003235 }
3236 }
3237
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003238 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3239 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003240 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003241 if (sBgWidgetProviders == null || refresh) {
3242 sBgWidgetProviders = new HashMap<>();
3243 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3244 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003245
Robin Lee26ace122015-03-16 19:41:43 +00003246 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3247 for (AppWidgetProviderInfo pInfo : widgets) {
3248 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3249 UserHandleCompat user = wm.getUser(info);
3250 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3251 }
3252
3253 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3254 for (CustomAppWidget widget : customWidgets) {
3255 info = new LauncherAppWidgetProviderInfo(context, widget);
3256 UserHandleCompat user = wm.getUser(info);
3257 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3258 }
Adam Cohen59400422014-03-05 18:07:04 -08003259 }
Adam Cohen59400422014-03-05 18:07:04 -08003260 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3261 }
3262 }
3263
Robin Lee26ace122015-03-16 19:41:43 +00003264 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3265 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003266 synchronized (sBgLock) {
3267 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003268 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003269 }
Robin Lee26ace122015-03-16 19:41:43 +00003270 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003271 }
3272 }
3273
Hyunyoung Songd4af1482015-04-20 20:40:03 -07003274 public void loadAndBindWidgetsAndShortcuts(final Context context, final Callbacks callbacks) {
3275 runOnWorkerThread(new Runnable(){
3276 @Override
3277 public void run() {
3278 final ArrayList<Object> list =
3279 getSortedWidgetsAndShortcuts(context, true /* refresh */);
3280 mHandler.post(new Runnable() {
3281 @Override
3282 public void run() {
3283 Callbacks cb = getCallback();
3284 if (callbacks == cb && cb != null) {
3285 callbacks.bindPackagesUpdated(list);
3286 }
3287 }
3288 });
3289 }
3290 });
3291 }
3292
Winson Chungb745afb2015-03-02 11:51:23 -08003293 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003294 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003295 PackageManager packageManager = context.getPackageManager();
3296 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003297 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003298 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3299 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003300 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003301 return widgetsAndShortcuts;
3302 }
3303
Adam Cohen091440a2015-03-18 14:16:05 -07003304 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003305 UserHandleCompat user) {
3306 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3307 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003308 }
Adam Cohen556f6132014-01-15 15:18:08 -08003309
Kenny Guyed131872014-04-30 03:02:21 +01003310 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3311 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003312 if (cn == null) {
3313 return false;
3314 }
Kenny Guyed131872014-04-30 03:02:21 +01003315 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3316 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003317 return false;
3318 }
Kenny Guyed131872014-04-30 03:02:21 +01003319 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003320 }
3321
Adam Cohena28b78e2014-05-20 17:03:04 -07003322 public static boolean isValidPackage(Context context, String packageName,
3323 UserHandleCompat user) {
3324 if (packageName == null) {
3325 return false;
3326 }
3327 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3328 return launcherApps.isPackageEnabledForProfile(packageName, user);
3329 }
3330
Joe Onorato9c1289c2009-08-17 11:03:03 -04003331 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003332 * Make an ShortcutInfo object for a restored application or shortcut item that points
3333 * to a package that is not yet installed on the system.
3334 */
Sunny Goyal34942622014-08-29 17:20:55 -07003335 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003336 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003337 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003338 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003339 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003340
3341 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3342 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3343 if (!TextUtils.isEmpty(title)) {
3344 info.title = title;
3345 }
3346 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3347 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3348 if (TextUtils.isEmpty(info.title)) {
3349 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3350 }
3351 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3352 } else {
3353 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3354 }
3355
Kenny Guyc2bd8102014-06-30 12:30:31 +01003356 info.contentDescription = mUserManager.getBadgedLabelForUser(
3357 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003358 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003359 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003360 return info;
3361 }
3362
3363 /**
3364 * Make an Intent object for a restored application or shortcut item that points
3365 * to the market page for the item.
3366 */
Adam Cohen091440a2015-03-18 14:16:05 -07003367 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003368 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003369 return getMarketIntent(componentName.getPackageName());
3370 }
3371
3372 static Intent getMarketIntent(String packageName) {
3373 return new Intent(Intent.ACTION_VIEW)
3374 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003375 .scheme("market")
3376 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003377 .appendQueryParameter("id", packageName)
3378 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003379 }
3380
3381 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003382 * Make an ShortcutInfo object for a shortcut that is an application.
3383 *
3384 * If c is not null, then it will be used to fill in missing data like the title and icon.
3385 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003386 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003387 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003388 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003389 if (user == null) {
3390 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003391 return null;
3392 }
3393
Kenny Guyed131872014-04-30 03:02:21 +01003394 ComponentName componentName = intent.getComponent();
3395 if (componentName == null) {
3396 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3397 return null;
3398 }
3399
3400 Intent newIntent = new Intent(intent.getAction(), null);
3401 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3402 newIntent.setComponent(componentName);
3403 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003404 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003405 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3406 return null;
3407 }
3408
3409 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003410 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003411 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3412 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3413 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003414 }
3415
Joe Onorato56d82912010-03-07 14:32:10 -05003416 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003417 if (TextUtils.isEmpty(info.title) && c != null) {
3418 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003419 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003420
Joe Onorato56d82912010-03-07 14:32:10 -05003421 // fall back to the class name of the activity
3422 if (info.title == null) {
3423 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003424 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003425
Joe Onorato9c1289c2009-08-17 11:03:03 -04003426 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003427 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003428 info.contentDescription = mUserManager.getBadgedLabelForUser(
3429 info.title.toString(), info.user);
Sunny Goyalfa401a12015-04-10 13:45:42 -07003430 if (lai != null) {
3431 info.flags = AppInfo.initFlags(lai);
3432 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003433 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003434 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003435
Winson Chung64359a52013-07-08 17:17:08 -07003436 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3437 ItemInfoFilter f) {
3438 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3439 for (ItemInfo i : infos) {
3440 if (i instanceof ShortcutInfo) {
3441 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003442 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003443 if (cn != null && f.filterItem(null, info, cn)) {
3444 filtered.add(info);
3445 }
3446 } else if (i instanceof FolderInfo) {
3447 FolderInfo info = (FolderInfo) i;
3448 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003449 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003450 if (cn != null && f.filterItem(info, s, cn)) {
3451 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003452 }
3453 }
Winson Chung64359a52013-07-08 17:17:08 -07003454 } else if (i instanceof LauncherAppWidgetInfo) {
3455 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3456 ComponentName cn = info.providerName;
3457 if (cn != null && f.filterItem(null, info, cn)) {
3458 filtered.add(info);
3459 }
Winson Chung8a435102012-08-30 17:16:53 -07003460 }
3461 }
Winson Chung64359a52013-07-08 17:17:08 -07003462 return new ArrayList<ItemInfo>(filtered);
3463 }
3464
Adam Cohen091440a2015-03-18 14:16:05 -07003465 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003466 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003467 ItemInfoFilter filter = new ItemInfoFilter() {
3468 @Override
3469 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003470 if (info.user == null) {
3471 return cn.equals(cname);
3472 } else {
3473 return cn.equals(cname) && info.user.equals(user);
3474 }
Winson Chung64359a52013-07-08 17:17:08 -07003475 }
3476 };
3477 return filterItemInfos(sBgItemsIdMap.values(), filter);
3478 }
3479
Sunny Goyal1a745e82014-10-02 15:58:31 -07003480 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003481 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003482 */
Adam Cohen091440a2015-03-18 14:16:05 -07003483 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003484 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3485 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003486
Joe Onorato56d82912010-03-07 14:32:10 -05003487 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003488 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003489 // Non-app shortcuts are only supported for current user.
3490 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003491 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003492
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003493 // TODO: If there's an explicit component and we can't install that, delete it.
3494
Joe Onorato56d82912010-03-07 14:32:10 -05003495 info.title = c.getString(titleIndex);
3496
Joe Onorato9c1289c2009-08-17 11:03:03 -04003497 int iconType = c.getInt(iconTypeIndex);
3498 switch (iconType) {
3499 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3500 String packageName = c.getString(iconPackageIndex);
3501 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003502 info.customIcon = false;
3503 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003504 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003505 // the db
3506 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003507 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003508 }
3509 // the fallback icon
3510 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003511 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003512 info.usingFallbackIcon = true;
3513 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003514 break;
3515 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003516 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003517 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003518 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003519 info.customIcon = false;
3520 info.usingFallbackIcon = true;
3521 } else {
3522 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003523 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003524 break;
3525 default:
Kenny Guyed131872014-04-30 03:02:21 +01003526 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003527 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003528 info.customIcon = false;
3529 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003530 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003531 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003532 return info;
3533 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003534
Sunny Goyal2350bc92014-10-14 16:42:54 -07003535 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003536 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3537 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3538 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3539
Adam Cohend9198822011-11-22 16:42:47 -08003540 if (intent == null) {
3541 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3542 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3543 return null;
3544 }
3545
Joe Onorato0589f0f2010-02-08 13:44:00 -08003546 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003547 boolean customIcon = false;
3548 ShortcutIconResource iconResource = null;
3549
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003550 if (bitmap instanceof Bitmap) {
3551 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003552 customIcon = true;
3553 } else {
3554 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003555 if (extra instanceof ShortcutIconResource) {
3556 iconResource = (ShortcutIconResource) extra;
3557 icon = Utilities.createIconBitmap(iconResource.packageName,
3558 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003559 }
3560 }
3561
Michael Jurkac9d95c52011-08-29 14:03:34 -07003562 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003563
Kenny Guyed131872014-04-30 03:02:21 +01003564 // Only support intents for current user for now. Intents sent from other
3565 // users wouldn't get here without intent forwarding anyway.
3566 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003567 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003568 icon = mIconCache.getDefaultIcon(info.user);
3569 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003570 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003571 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003572
Joe Onorato0589f0f2010-02-08 13:44:00 -08003573 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003574 info.contentDescription = mUserManager.getBadgedLabelForUser(
3575 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003576 info.intent = intent;
3577 info.customIcon = customIcon;
3578 info.iconResource = iconResource;
3579
3580 return info;
3581 }
3582
Joe Onorato9c1289c2009-08-17 11:03:03 -04003583 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003584 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003585 * or make a new one.
3586 */
Adam Cohen091440a2015-03-18 14:16:05 -07003587 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003588 // See if a placeholder was created for us already
3589 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003590 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003591 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003592 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003593 folders.put(id, folderInfo);
3594 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003595 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003596 }
3597
Winson Chung1ed747a2011-05-03 16:18:34 -07003598 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003599 private final AppWidgetManagerCompat mManager;
3600 private final PackageManager mPackageManager;
3601 private final HashMap<Object, String> mLabelCache;
3602 private final Collator mCollator;
3603
Hyunyoung Song3f471442015-04-08 19:01:34 -07003604 public WidgetAndShortcutNameComparator(Context context) {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003605 mManager = AppWidgetManagerCompat.getInstance(context);
3606 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003607 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003608 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003609 }
3610 public final int compare(Object a, Object b) {
3611 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003612 if (mLabelCache.containsKey(a)) {
3613 labelA = mLabelCache.get(a);
3614 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003615 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3616 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003617 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003618 mLabelCache.put(a, labelA);
3619 }
3620 if (mLabelCache.containsKey(b)) {
3621 labelB = mLabelCache.get(b);
3622 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003623 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003624 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003625 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003626 mLabelCache.put(b, labelB);
3627 }
Winson Chung11904872012-09-17 16:58:46 -07003628 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003629 }
3630 };
Joe Onoratobe386092009-11-17 17:32:16 -08003631
Sunny Goyal651077b2014-06-30 14:15:31 -07003632 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3633 return (provider != null) && (provider.provider != null)
3634 && (provider.provider.getPackageName() != null);
3635 }
3636
Joe Onoratobe386092009-11-17 17:32:16 -08003637 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003638 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003639 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3640 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3641 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3642 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003643 if (mLoaderTask != null) {
3644 mLoaderTask.dumpState();
3645 } else {
3646 Log.d(TAG, "mLoaderTask=null");
3647 }
Joe Onoratobe386092009-11-17 17:32:16 -08003648 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003649
3650 public Callbacks getCallback() {
3651 return mCallbacks != null ? mCallbacks.get() : null;
3652 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07003653
3654 /**
3655 * @return {@link FolderInfo} if its already loaded.
3656 */
3657 public FolderInfo findFolderById(Long folderId) {
3658 synchronized (sBgLock) {
3659 return sBgFolders.get(folderId);
3660 }
3661 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003662}