blob: 37f1ea86e21ba7921150504b5cc577749c23cab1 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Narayan Kamathcb1a4772011-06-28 13:46:59 +010019import android.app.SearchManager;
Romain Guy629de3e2010-01-13 12:20:59 -080020import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070021import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.ContentProviderClient;
24import android.content.ContentProviderOperation;
25import android.content.ContentResolver;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
Joe Onorato0589f0f2010-02-08 13:44:00 -080029import android.content.Intent.ShortcutIconResource;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070030import android.content.IntentFilter;
31import android.content.SharedPreferences;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.content.pm.PackageManager;
Jason Monkbbe1e242014-05-16 17:37:34 -040033import android.content.pm.ProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.pm.ResolveInfo;
Reena Lee93f824a2011-09-23 17:20:28 -070035import android.content.res.Configuration;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.content.res.Resources;
37import android.database.Cursor;
38import android.graphics.Bitmap;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.graphics.Rect;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.net.Uri;
Joe Onorato17a89222011-02-08 17:26:11 -080041import android.os.Environment;
Joe Onorato36115782010-06-17 13:28:48 -040042import android.os.Handler;
43import android.os.HandlerThread;
Joe Onorato0589f0f2010-02-08 13:44:00 -080044import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.os.Process;
Winson Chungaafa03c2010-06-11 17:34:16 -070046import android.os.RemoteException;
Joe Onorato9c1289c2009-08-17 11:03:03 -040047import android.os.SystemClock;
Chris Wrenc3919c02013-09-18 09:48:33 -040048import android.provider.BaseColumns;
Winson Chunga90303b2013-11-15 13:05:06 -080049import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070050import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080051import android.util.LongSparseArray;
Winson Chungc9168342013-06-26 14:54:55 -070052import android.util.Pair;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.LauncherActivityInfoCompat;
56import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070057import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070058import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserHandleCompat;
60import com.android.launcher3.compat.UserManagerCompat;
Robin Lee26ace122015-03-16 19:41:43 +000061import com.android.launcher3.util.ComponentKey;
Sunny Goyal18bf8e22015-04-08 18:13:46 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Adam Cohen091440a2015-03-18 14:16:05 -070063import com.android.launcher3.util.Thunk;
Romain Guyedcce092010-03-04 13:03:17 -080064
Michael Jurkac2f801e2011-07-12 14:19:46 -070065import java.lang.ref.WeakReference;
66import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070067import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070068import java.text.Collator;
69import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070070import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070071import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070072import java.util.Collections;
73import java.util.Comparator;
74import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070075import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070076import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070077import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070078import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070079import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070080
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081/**
82 * Maintains in-memory state of the Launcher. It is expected that there should be only one
83 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070084 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 */
Kenny Guyed131872014-04-30 03:02:21 +010086public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010087 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080088 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040089 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070090 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Chris Wrenb358f812014-04-16 13:37:00 -040091
Joe Onorato9c1289c2009-08-17 11:03:03 -040092 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070093
Dan Sandlerd5024042014-01-09 15:01:33 -050094 public static final int LOADER_FLAG_NONE = 0;
95 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
96 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
97
Joe Onorato36115782010-06-17 13:28:48 -040098 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050099 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800100
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800102 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400103
Adam Cohen091440a2015-03-18 14:16:05 -0700104 @Thunk final LauncherAppState mApp;
105 @Thunk final Object mLock = new Object();
106 @Thunk DeferredHandler mHandler = new DeferredHandler();
107 @Thunk LoaderTask mLoaderTask;
108 @Thunk boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Winson Chung81b52252012-08-27 15:34:29 -0700110 // Specific runnable types that are run on the main thread deferred handler, this allows us to
111 // clear all queued binding runnables when the Launcher activity is destroyed.
112 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
113 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
114
Jason Monkbbe1e242014-05-16 17:37:34 -0400115 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700116
Adam Cohen091440a2015-03-18 14:16:05 -0700117 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700118 static {
119 sWorkerThread.start();
120 }
Adam Cohen091440a2015-03-18 14:16:05 -0700121 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700122
Joe Onoratocc67f472010-06-08 10:54:30 -0700123 // We start off with everything not loaded. After that, we assume that
124 // our monitoring of the package manager provides all updates and we never
125 // need to do a requery. These are only ever touched from the loader thread.
Adam Cohen091440a2015-03-18 14:16:05 -0700126 @Thunk boolean mWorkspaceLoaded;
127 @Thunk boolean mAllAppsLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700128
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700129 // When we are loading pages synchronously, we can't just post the binding of items on the side
130 // pages as this delays the rotation process. Instead, we wait for a callback from the first
131 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
132 // a normal load, we also clear this set of Runnables.
133 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
134
Adam Cohen091440a2015-03-18 14:16:05 -0700135 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700137 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700138 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800139
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700140 // The lock that must be acquired before referencing any static bg data structures. Unlike
141 // other locks, this one can generally be held long-term because we never expect any of these
142 // static data structures to be referenced outside of the worker thread except on the first
143 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700144 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700145
Adam Cohen487f7dd2012-06-28 18:12:10 -0700146 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700147 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700148 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700149
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
151 // created by LauncherModel that are directly on the home screen (however, no widgets or
152 // shortcuts within folders).
153 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700154
Adam Cohen487f7dd2012-06-28 18:12:10 -0700155 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
156 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700157 new ArrayList<LauncherAppWidgetInfo>();
158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
160 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700161
Adam Cohendcd297f2013-06-18 13:13:40 -0700162 // sBgWorkspaceScreens is the ordered set of workspace screens.
163 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
164
Adam Cohen59400422014-03-05 18:07:04 -0800165 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000166 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800167
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700168 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700169 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
170 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700171
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700172 // </ only access in worker thread >
173
Adam Cohen091440a2015-03-18 14:16:05 -0700174 @Thunk IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800175
Reena Lee99a73f32011-10-24 17:27:37 -0700176 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700177
Adam Cohen091440a2015-03-18 14:16:05 -0700178 @Thunk final LauncherAppsCompat mLauncherApps;
179 @Thunk final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100180
Joe Onorato9c1289c2009-08-17 11:03:03 -0400181 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700182 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public int getCurrentWorkspaceScreen();
184 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700185 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
186 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700187 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700188 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500189 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800190 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400191 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200192 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700193 public void bindAppsAdded(ArrayList<Long> newScreens,
194 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700195 ArrayList<ItemInfo> addAnimated,
196 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200197 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700198 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
199 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
200 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700201 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700202 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700203 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700204 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200205 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100206 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700207 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700208 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700209 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800210 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
211 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400212 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
Winson Chung64359a52013-07-08 17:17:08 -0700214 public interface ItemInfoFilter {
215 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
216 }
217
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800218 public interface ScreenPosProvider {
219 int getScreenIndex(ArrayList<Long> screenIDs);
220 }
221
Bjorn Bringert1307f632013-10-03 22:31:03 +0100222 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800223 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400224
Winson Chungee055712013-07-30 14:46:24 -0700225 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700226 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400227 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
228 // resource string.
229 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
230 ProviderInfo providerInfo =
231 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
232 ProviderInfo redirectProvider =
233 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700234
235 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400236 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700237
238 if (mOldContentProviderExists) {
239 Log.d(TAG, "Old launcher provider exists.");
240 } else {
241 Log.d(TAG, "Old launcher provider does not exist.");
242 }
243
Daniel Sandlere4f98912013-06-25 15:13:26 -0400244 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100245 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800246 mIconCache = iconCache;
247
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400248 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700249 Configuration config = res.getConfiguration();
250 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100251 mLauncherApps = LauncherAppsCompat.getInstance(context);
252 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800253 }
254
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700255 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
256 * posted on the main thread handler. */
Adam Cohen091440a2015-03-18 14:16:05 -0700257 @Thunk void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700258 runOnMainThread(r, 0);
259 }
Adam Cohen091440a2015-03-18 14:16:05 -0700260 @Thunk void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700261 if (sWorkerThread.getThreadId() == Process.myTid()) {
262 // If we are on the worker thread, post onto the main handler
263 mHandler.post(r);
264 } else {
265 r.run();
266 }
267 }
268
269 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
270 * posted on the worker thread handler. */
271 private static void runOnWorkerThread(Runnable r) {
272 if (sWorkerThread.getThreadId() == Process.myTid()) {
273 r.run();
274 } else {
275 // If we are not on the worker thread, then post to the worker handler
276 sWorker.post(r);
277 }
278 }
279
Winson Chunge43a1e72014-01-15 10:33:02 -0800280 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
281 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800282 }
283
Sunny Goyale755d462014-07-22 13:48:29 -0700284 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500285 // Process the updated package state
286 Runnable r = new Runnable() {
287 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800288 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500289 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700290 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500291 }
292 }
293 };
294 mHandler.post(r);
295 }
296
Sunny Goyala22666f2014-09-18 13:25:15 -0700297 public void updatePackageBadge(final String packageName) {
298 // Process the updated package badge
299 Runnable r = new Runnable() {
300 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800301 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700302 if (callbacks != null) {
303 callbacks.updatePackageBadge(packageName);
304 }
305 }
306 };
307 mHandler.post(r);
308 }
309
Adam Cohen76a47a12014-02-05 11:47:43 -0800310 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800311 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800312
313 if (allAppsApps == null) {
314 throw new RuntimeException("allAppsApps must not be null");
315 }
316 if (allAppsApps.isEmpty()) {
317 return;
318 }
319
320 // Process the newly added applications and add them to the database first
321 Runnable r = new Runnable() {
322 public void run() {
323 runOnMainThread(new Runnable() {
324 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800325 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800326 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500327 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800328 }
329 }
330 });
331 }
332 };
333 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700334 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800335
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700336 public void addAndBindAddedWorkspaceItems(final Context context,
Adam Cohen76a47a12014-02-05 11:47:43 -0800337 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700338 addAndBindAddedWorkspaceItems(context, workspaceApps,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800339 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800340
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800341 @Override
342 public int getScreenIndex(ArrayList<Long> screenIDs) {
343 return screenIDs.isEmpty() ? 0 : 1;
344 }
345 }, 1, false);
346 }
347
348 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
349 int[] xy, int spanX, int spanY) {
350 LauncherAppState app = LauncherAppState.getInstance();
351 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
352 final int xCount = (int) grid.numColumns;
353 final int yCount = (int) grid.numRows;
354 boolean[][] occupied = new boolean[xCount][yCount];
355 if (occupiedPos != null) {
356 for (Rect r : occupiedPos) {
357 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
358 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
359 occupied[x][y] = true;
360 }
361 }
362 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800363 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800364 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
365 }
366
367 /**
368 * Find a position on the screen for the given size or adds a new screen.
369 * @return screenId and the coordinates for the item.
370 */
Adam Cohen091440a2015-03-18 14:16:05 -0700371 @Thunk static Pair<Long, int[]> findSpaceForItem(
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800372 Context context,
373 ScreenPosProvider preferredScreen,
374 int fallbackStartScreen,
375 ArrayList<Long> workspaceScreens,
376 ArrayList<Long> addedWorkspaceScreensFinal,
377 int spanX, int spanY) {
378 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
379 // loadWorkspace() may not have been called.
380 final ContentResolver cr = context.getContentResolver();
381 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
382 new String[] {
383 LauncherSettings.Favorites.SCREEN,
384 LauncherSettings.Favorites.CELLX,
385 LauncherSettings.Favorites.CELLY,
386 LauncherSettings.Favorites.SPANX,
387 LauncherSettings.Favorites.SPANY,
388 LauncherSettings.Favorites.CONTAINER
389 },
390 "container=?",
391 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
392 null);
393
394 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
395 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
396 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
397 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
398 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
399 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
400 try {
401 while (c.moveToNext()) {
402 Rect rect = new Rect();
403 rect.left = c.getInt(cellXIndex);
404 rect.top = c.getInt(cellYIndex);
405 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
406 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
407
408 long screenId = c.getInt(screenIndex);
409 ArrayList<Rect> items = screenItems.get(screenId);
410 if (items == null) {
411 items = new ArrayList<Rect>();
412 screenItems.put(screenId, items);
413 }
414 items.add(rect);
415 }
416 } catch (Exception e) {
417 screenItems.clear();
418 } finally {
419 c.close();
420 }
421
422 // Find appropriate space for the item.
423 long screenId = 0;
424 int[] cordinates = new int[2];
425 boolean found = false;
426
427 int screenCount = workspaceScreens.size();
428 // First check the preferred screen.
429 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
430 if (preferredScreenIndex < screenCount) {
431 screenId = workspaceScreens.get(preferredScreenIndex);
432 found = findNextAvailableIconSpaceInScreen(
433 screenItems.get(screenId), cordinates, spanX, spanY);
434 }
435
436 if (!found) {
437 // Search on any of the screens.
438 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
439 screenId = workspaceScreens.get(screen);
440 if (findNextAvailableIconSpaceInScreen(
441 screenItems.get(screenId), cordinates, spanX, spanY)) {
442 // We found a space for it
443 found = true;
444 break;
445 }
446 }
447 }
448
449 if (!found) {
450 // Still no position found. Add a new screen to the end.
451 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
452
453 // Save the screen id for binding in the workspace
454 workspaceScreens.add(screenId);
455 addedWorkspaceScreensFinal.add(screenId);
456
457 // If we still can't find an empty space, then God help us all!!!
458 if (!findNextAvailableIconSpaceInScreen(
459 screenItems.get(screenId), cordinates, spanX, spanY)) {
460 throw new RuntimeException("Can't find space to add the item");
461 }
462 }
463 return Pair.create(screenId, cordinates);
464 }
465
466 /**
467 * Adds the provided items to the workspace.
468 * @param preferredScreen the screen where we should try to add the app first
469 * @param fallbackStartScreen the screen to start search for empty space if
470 * preferredScreen is not available.
471 */
472 public void addAndBindPendingItem(
473 final Context context,
474 final PendingAddItemInfo addInfo,
475 final ScreenPosProvider preferredScreen,
476 final int fallbackStartScreen) {
477 final Callbacks callbacks = getCallback();
478 // Process the newly added applications and add them to the database first
479 Runnable r = new Runnable() {
480 public void run() {
481 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800482 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800483
484 // Find appropriate space for the item.
485 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
486 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
487 addInfo.spanX,
488 addInfo.spanY);
489 final long screenId = coords.first;
490 final int[] cordinates = coords.second;
491
492 // Update the workspace screens
493 updateWorkspaceScreenOrder(context, workspaceScreens);
494 runOnMainThread(new Runnable() {
495 public void run() {
496 Callbacks cb = getCallback();
497 if (callbacks == cb && cb != null) {
498 cb.bindAddScreens(addedWorkspaceScreensFinal);
499 cb.bindAddPendingItem(addInfo,
500 LauncherSettings.Favorites.CONTAINER_DESKTOP,
501 screenId, cordinates, addInfo.spanX, addInfo.spanY);
502 }
503 }
504 });
505 }
506 };
507 runOnWorkerThread(r);
508 }
509
510 /**
511 * Adds the provided items to the workspace.
512 * @param preferredScreen the screen where we should try to add the app first
513 * @param fallbackStartScreen the screen to start search for empty space if
514 * preferredScreen is not available.
515 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700516 public void addAndBindAddedWorkspaceItems(final Context context,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800517 final ArrayList<ItemInfo> workspaceApps,
518 final ScreenPosProvider preferredScreen,
519 final int fallbackStartScreen,
520 final boolean allowDuplicate) {
521 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800522 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700523 return;
Winson Chung997a9232013-07-24 15:33:46 -0700524 }
Winson Chung64359a52013-07-08 17:17:08 -0700525 // Process the newly added applications and add them to the database first
526 Runnable r = new Runnable() {
527 public void run() {
528 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
529 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
530
Winson Chung76828c82013-08-19 15:43:29 -0700531 // Get the list of workspace screens. We need to append to this list and
532 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
533 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800534 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700535 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800536 for (ItemInfo item : workspaceApps) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700537 if (!allowDuplicate && item instanceof ShortcutInfo) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800538 // Short-circuit this logic if the icon exists somewhere on the workspace
539 if (shortcutExists(context, item.title.toString(),
540 item.getIntent(), item.user)) {
541 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700542 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800543 }
Winson Chung76828c82013-08-19 15:43:29 -0700544
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800545 // Find appropriate space for the item.
546 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
547 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
548 1, 1);
549 long screenId = coords.first;
550 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700551
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700552 ItemInfo itemInfo;
553 if (item instanceof ShortcutInfo || item instanceof FolderInfo) {
554 itemInfo = item;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800555 } else if (item instanceof AppInfo) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700556 itemInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700557 } else {
558 throw new RuntimeException("Unexpected info type");
559 }
Winson Chung94d67682013-09-25 16:29:40 -0700560
Winson Chung64359a52013-07-08 17:17:08 -0700561 // Add the shortcut to the db
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700562 addItemToDatabase(context, itemInfo,
Winson Chung64359a52013-07-08 17:17:08 -0700563 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700564 screenId, cordinates[0], cordinates[1]);
Winson Chung64359a52013-07-08 17:17:08 -0700565 // Save the ShortcutInfo for binding in the workspace
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700566 addedShortcutsFinal.add(itemInfo);
Winson Chung64359a52013-07-08 17:17:08 -0700567 }
568 }
569
Winson Chung76828c82013-08-19 15:43:29 -0700570 // Update the workspace screens
571 updateWorkspaceScreenOrder(context, workspaceScreens);
572
Adam Cohen76a47a12014-02-05 11:47:43 -0800573 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700574 runOnMainThread(new Runnable() {
575 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800576 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700577 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700578 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
579 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700580 if (!addedShortcutsFinal.isEmpty()) {
581 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
582 long lastScreenId = info.screenId;
583 for (ItemInfo i : addedShortcutsFinal) {
584 if (i.screenId == lastScreenId) {
585 addAnimated.add(i);
586 } else {
587 addNotAnimated.add(i);
588 }
Winson Chung997a9232013-07-24 15:33:46 -0700589 }
590 }
Winson Chungd64d1762013-08-20 14:37:16 -0700591 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800592 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700593 }
Winson Chung64359a52013-07-08 17:17:08 -0700594 }
Winson Chung997a9232013-07-24 15:33:46 -0700595 });
596 }
Winson Chung64359a52013-07-08 17:17:08 -0700597 }
598 };
599 runOnWorkerThread(r);
600 }
601
Winson Chung81b52252012-08-27 15:34:29 -0700602 public void unbindItemInfosAndClearQueuedBindRunnables() {
603 if (sWorkerThread.getThreadId() == Process.myTid()) {
604 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
605 "main thread");
606 }
607
608 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400609 synchronized (mDeferredBindRunnables) {
610 mDeferredBindRunnables.clear();
611 }
Winson Chung81b52252012-08-27 15:34:29 -0700612 // Remove any queued bind runnables
613 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
614 // Unbind all the workspace items
615 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700616 }
617
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700618 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700619 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700620 // Ensure that we don't use the same workspace items data structure on the main thread
621 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700622 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
623 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700624 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700625 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
626 tmpAppWidgets.addAll(sBgAppWidgets);
627 }
628 Runnable r = new Runnable() {
629 @Override
630 public void run() {
631 for (ItemInfo item : tmpWorkspaceItems) {
632 item.unbind();
633 }
634 for (ItemInfo item : tmpAppWidgets) {
635 item.unbind();
636 }
637 }
638 };
639 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700640 }
641
Joe Onorato9c1289c2009-08-17 11:03:03 -0400642 /**
643 * Adds an item to the DB if it was not created previously, or move it to a new
644 * <container, screen, cellX, cellY>
645 */
646 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700647 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400648 if (item.container == ItemInfo.NO_ID) {
649 // From all apps
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700650 addItemToDatabase(context, item, container, screenId, cellX, cellY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400651 } else {
652 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700653 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654 }
655 }
656
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700657 static void checkItemInfoLocked(
658 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
659 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
660 if (modelItem != null && item != modelItem) {
661 // check all the data is consistent
662 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
663 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
664 ShortcutInfo shortcut = (ShortcutInfo) item;
665 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
666 modelShortcut.intent.filterEquals(shortcut.intent) &&
667 modelShortcut.id == shortcut.id &&
668 modelShortcut.itemType == shortcut.itemType &&
669 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700670 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700671 modelShortcut.cellX == shortcut.cellX &&
672 modelShortcut.cellY == shortcut.cellY &&
673 modelShortcut.spanX == shortcut.spanX &&
674 modelShortcut.spanY == shortcut.spanY &&
675 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
676 (modelShortcut.dropPos != null &&
677 shortcut.dropPos != null &&
678 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
679 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
680 // For all intents and purposes, this is the same object
681 return;
682 }
683 }
684
685 // the modelItem needs to match up perfectly with item if our model is
686 // to be consistent with the database-- for now, just require
687 // modelItem == item or the equality check above
688 String msg = "item: " + ((item != null) ? item.toString() : "null") +
689 "modelItem: " +
690 ((modelItem != null) ? modelItem.toString() : "null") +
691 "Error: ItemInfo passed to checkItemInfo doesn't match original";
692 RuntimeException e = new RuntimeException(msg);
693 if (stackTrace != null) {
694 e.setStackTrace(stackTrace);
695 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800696 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700697 }
698 }
699
Michael Jurka816474f2012-06-25 14:49:02 -0700700 static void checkItemInfo(final ItemInfo item) {
701 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
702 final long itemId = item.id;
703 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700704 public void run() {
705 synchronized (sBgLock) {
706 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700707 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700708 }
709 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700710 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700711 }
712
Michael Jurkac9d95c52011-08-29 14:03:34 -0700713 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
714 final ItemInfo item, final String callingFunction) {
715 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700716 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700717 final ContentResolver cr = context.getContentResolver();
718
Adam Cohen487f7dd2012-06-28 18:12:10 -0700719 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700720 Runnable r = new Runnable() {
721 public void run() {
722 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700723 updateItemArrays(item, itemId, stackTrace);
724 }
725 };
726 runOnWorkerThread(r);
727 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700728
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700729 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
730 final ArrayList<ItemInfo> items, final String callingFunction) {
731 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700732
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700733 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
734 Runnable r = new Runnable() {
735 public void run() {
736 ArrayList<ContentProviderOperation> ops =
737 new ArrayList<ContentProviderOperation>();
738 int count = items.size();
739 for (int i = 0; i < count; i++) {
740 ItemInfo item = items.get(i);
741 final long itemId = item.id;
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700742 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700743 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700744
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700745 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
746 updateItemArrays(item, itemId, stackTrace);
747
748 }
749 try {
750 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
751 } catch (Exception e) {
752 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700753 }
754 }
755 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700756 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700758
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700759 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
760 // Lock on mBgLock *after* the db operation
761 synchronized (sBgLock) {
762 checkItemInfoLocked(itemId, item, stackTrace);
763
764 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
765 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
766 // Item is in a folder, make sure this folder exists
767 if (!sBgFolders.containsKey(item.container)) {
768 // An items container is being set to a that of an item which is not in
769 // the list of Folders.
770 String msg = "item: " + item + " container being set to: " +
771 item.container + ", not in the list of folders";
772 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700773 }
774 }
775
776 // Items are added/removed from the corresponding FolderInfo elsewhere, such
777 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
778 // that are on the desktop, as appropriate
779 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800780 if (modelItem != null &&
781 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
782 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700783 switch (modelItem.itemType) {
784 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
785 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
786 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
787 if (!sBgWorkspaceItems.contains(modelItem)) {
788 sBgWorkspaceItems.add(modelItem);
789 }
790 break;
791 default:
792 break;
793 }
794 } else {
795 sBgWorkspaceItems.remove(modelItem);
796 }
797 }
798 }
799
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800800 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400801 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700802 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700803 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700804 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400805 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400806 item.cellX = cellX;
807 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700808
Winson Chung3d503fb2011-07-13 17:25:49 -0700809 // We store hotseat items in canonical form which is this orientation invariant position
810 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700811 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700812 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700813 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700814 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700816 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400817
818 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400819 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700820 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
821 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800822 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700823 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400824
Michael Jurkac9d95c52011-08-29 14:03:34 -0700825 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700826 }
827
828 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700829 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
830 * cellX, cellY have already been updated on the ItemInfos.
831 */
832 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
833 final long container, final int screen) {
834
835 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
836 int count = items.size();
837
838 for (int i = 0; i < count; i++) {
839 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700840 item.container = container;
841
842 // We store hotseat items in canonical form which is this orientation invariant position
843 // in the hotseat
844 if (context instanceof Launcher && screen < 0 &&
845 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700846 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700847 item.cellY);
848 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700849 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700850 }
851
852 final ContentValues values = new ContentValues();
853 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
854 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
855 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800856 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700857 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700858
859 contentValues.add(values);
860 }
861 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
862 }
863
864 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700865 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800866 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700867 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700868 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700869 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800870 item.cellX = cellX;
871 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700872 item.spanX = spanX;
873 item.spanY = spanY;
874
875 // We store hotseat items in canonical form which is this orientation invariant position
876 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700877 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700878 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700879 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700880 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700881 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700882 }
Adam Cohend4844c32011-02-18 19:25:06 -0800883
Adam Cohend4844c32011-02-18 19:25:06 -0800884 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800885 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700886 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
887 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800888 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700889 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
890 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700891 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800892
Michael Jurka816474f2012-06-25 14:49:02 -0700893 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700894 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700895
896 /**
897 * Update an item to the database in a specified container.
898 */
899 static void updateItemInDatabase(Context context, final ItemInfo item) {
900 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100901 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700902 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800903 }
904
905 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400906 * Returns true if the shortcuts already exists in the database.
907 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800908 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800909 static boolean shortcutExists(Context context, String title, Intent intent,
910 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400911 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700912 final Intent intentWithPkg, intentWithoutPkg;
913
914 if (intent.getComponent() != null) {
915 // If component is not null, an intent with null package will produce
916 // the same result and should also be a match.
917 if (intent.getPackage() != null) {
918 intentWithPkg = intent;
919 intentWithoutPkg = new Intent(intent).setPackage(null);
920 } else {
921 intentWithPkg = new Intent(intent).setPackage(
922 intent.getComponent().getPackageName());
923 intentWithoutPkg = intent;
924 }
925 } else {
926 intentWithPkg = intent;
927 intentWithoutPkg = intent;
928 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800929 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
930 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400931 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800932 new String[] { "title", "intent", "profileId" },
933 "title=? and (intent=? or intent=?) and profileId=?",
934 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
935 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400936 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800937 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400938 } finally {
939 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800940 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700941 }
942
Joe Onorato9c1289c2009-08-17 11:03:03 -0400943 /**
944 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
945 */
946 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
947 final ContentResolver cr = context.getContentResolver();
948 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
949 "_id=? and (itemType=? or itemType=?)",
950 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700951 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700952
Joe Onorato9c1289c2009-08-17 11:03:03 -0400953 try {
954 if (c.moveToFirst()) {
955 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
956 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
957 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
958 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
959 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
960 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700961 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800962
Joe Onorato9c1289c2009-08-17 11:03:03 -0400963 FolderInfo folderInfo = null;
964 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700965 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
966 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700968 }
969
Joe Onorato9c1289c2009-08-17 11:03:03 -0400970 folderInfo.title = c.getString(titleIndex);
971 folderInfo.id = id;
972 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700973 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700974 folderInfo.cellX = c.getInt(cellXIndex);
975 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700976 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400977
978 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700979 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980 } finally {
981 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700982 }
983
984 return null;
985 }
986
Joe Onorato9c1289c2009-08-17 11:03:03 -0400987 /**
988 * Add an item to the database in a specified container. Sets the container, screen, cellX and
989 * cellY fields of the item. Also assigns an ID to the item.
990 */
Sunny Goyal18bf8e22015-04-08 18:13:46 -0700991 public static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700992 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400993 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400994 item.cellX = cellX;
995 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -0700996 // We store hotseat items in canonical form which is this orientation invariant position
997 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700998 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700999 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001000 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001001 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001003 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001004
1005 final ContentValues values = new ContentValues();
1006 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001007 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008
Michael Jurka414300a2013-08-27 15:42:35 +02001009 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001010 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001011
Jason Monk8e19cf22014-03-20 15:06:57 -04001012 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001013 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001014 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001015 cr.insert(LauncherSettings.Favorites.CONTENT_URI, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001016
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001017 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001018 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001019 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001020 sBgItemsIdMap.put(item.id, item);
1021 switch (item.itemType) {
1022 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1023 sBgFolders.put(item.id, (FolderInfo) item);
1024 // Fall through
1025 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1026 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1027 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1028 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1029 sBgWorkspaceItems.add(item);
1030 } else {
1031 if (!sBgFolders.containsKey(item.container)) {
1032 // Adding an item to a folder that doesn't exist.
1033 String msg = "adding item: " + item + " to a folder that " +
1034 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001035 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001036 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001037 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001038 break;
1039 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1040 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1041 break;
1042 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001043 }
1044 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001045 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001046 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001047 }
1048
Joe Onorato9c1289c2009-08-17 11:03:03 -04001049 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001050 * Creates a new unique child id, for a given cell span across all layouts.
1051 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001052 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001053 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001054 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001055 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001056 }
1057
Sunny Goyal34942622014-08-29 17:20:55 -07001058 private static ArrayList<ItemInfo> getItemsByPackageName(
1059 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001060 ItemInfoFilter filter = new ItemInfoFilter() {
1061 @Override
1062 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1063 return cn.getPackageName().equals(pn) && info.user.equals(user);
1064 }
1065 };
Sunny Goyal34942622014-08-29 17:20:55 -07001066 return filterItemInfos(sBgItemsIdMap.values(), filter);
1067 }
1068
1069 /**
1070 * Removes all the items from the database corresponding to the specified package.
1071 */
1072 static void deletePackageFromDatabase(Context context, final String pn,
1073 final UserHandleCompat user) {
1074 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001075 }
1076
1077 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001078 * Removes the specified item from the database
1079 * @param context
1080 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001081 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001082 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001083 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1084 items.add(item);
1085 deleteItemsFromDatabase(context, items);
1086 }
1087
1088 /**
1089 * Removes the specified items from the database
1090 * @param context
1091 * @param item
1092 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001093 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001094 final ContentResolver cr = context.getContentResolver();
Michael Jurka83df1882011-08-31 20:59:26 -07001095 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001096 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001097 for (ItemInfo item : items) {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001098 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id);
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001099 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001100
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001101 // Lock on mBgLock *after* the db operation
1102 synchronized (sBgLock) {
1103 switch (item.itemType) {
1104 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1105 sBgFolders.remove(item.id);
1106 for (ItemInfo info: sBgItemsIdMap.values()) {
1107 if (info.container == item.id) {
1108 // We are deleting a folder which still contains items that
1109 // think they are contained by that folder.
1110 String msg = "deleting a folder (" + item + ") which still " +
1111 "contains items (" + info + ")";
1112 Log.e(TAG, msg);
1113 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001114 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001115 sBgWorkspaceItems.remove(item);
1116 break;
1117 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1118 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1119 sBgWorkspaceItems.remove(item);
1120 break;
1121 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1122 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1123 break;
1124 }
1125 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001126 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001127 }
1128 }
Michael Jurka83df1882011-08-31 20:59:26 -07001129 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001130 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001131 }
1132
1133 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001134 * Update the order of the workspace screens in the database. The array list contains
1135 * a list of screen ids in the order that they should appear.
1136 */
Winson Chungc9168342013-06-26 14:54:55 -07001137 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001138 // Log to disk
1139 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1140 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1141
Winson Chung64359a52013-07-08 17:17:08 -07001142 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001143 final ContentResolver cr = context.getContentResolver();
1144 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1145
1146 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001147 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001148 while (iter.hasNext()) {
1149 long id = iter.next();
1150 if (id < 0) {
1151 iter.remove();
1152 }
1153 }
1154
1155 Runnable r = new Runnable() {
1156 @Override
1157 public void run() {
Yura085c8532014-02-11 15:15:29 +00001158 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001159 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001160 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001161 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001162 for (int i = 0; i < count; i++) {
1163 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001164 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001165 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1166 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001167 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 }
Yura085c8532014-02-11 15:15:29 +00001169
1170 try {
1171 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1172 } catch (Exception ex) {
1173 throw new RuntimeException(ex);
1174 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001175
Winson Chungba9c37f2013-08-30 14:11:37 -07001176 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001177 sBgWorkspaceScreens.clear();
1178 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001179 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001180 }
1181 };
1182 runOnWorkerThread(r);
1183 }
1184
1185 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001186 * Remove the contents of the specified folder from the database
1187 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001188 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001189 final ContentResolver cr = context.getContentResolver();
1190
Michael Jurkac9d95c52011-08-29 14:03:34 -07001191 Runnable r = new Runnable() {
1192 public void run() {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001193 cr.delete(LauncherSettings.Favorites.getContentUri(info.id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001194 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001195 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001196 sBgItemsIdMap.remove(info.id);
1197 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001198 sBgWorkspaceItems.remove(info);
1199 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001200
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001201 cr.delete(LauncherSettings.Favorites.CONTENT_URI,
Michael Jurkac9d95c52011-08-29 14:03:34 -07001202 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001203 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001204 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001205 for (ItemInfo childInfo : info.contents) {
1206 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001207 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001208 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001209 }
1210 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001212 }
1213
1214 /**
1215 * Set this as the current Launcher activity object for the loader.
1216 */
1217 public void initialize(Callbacks callbacks) {
1218 synchronized (mLock) {
1219 mCallbacks = new WeakReference<Callbacks>(callbacks);
1220 }
1221 }
1222
Kenny Guyed131872014-04-30 03:02:21 +01001223 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001224 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001225 int op = PackageUpdatedTask.OP_UPDATE;
1226 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1227 user));
1228 }
1229
1230 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001231 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001232 int op = PackageUpdatedTask.OP_REMOVE;
1233 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1234 user));
1235 }
1236
1237 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001238 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001239 int op = PackageUpdatedTask.OP_ADD;
1240 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1241 user));
1242 }
1243
1244 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001245 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001246 boolean replacing) {
1247 if (!replacing) {
1248 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1249 user));
1250 if (mAppsCanBeOnRemoveableStorage) {
1251 // Only rebind if we support removable storage. It catches the
1252 // case where
1253 // apps on the external sd card need to be reloaded
1254 startLoaderFromBackground();
1255 }
1256 } else {
1257 // If we are replacing then just update the packages in the list
1258 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1259 packageNames, user));
1260 }
1261 }
1262
1263 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001264 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001265 boolean replacing) {
1266 if (!replacing) {
1267 enqueuePackageUpdated(new PackageUpdatedTask(
1268 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1269 user));
1270 }
Kenny Guyed131872014-04-30 03:02:21 +01001271 }
1272
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001273 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001274 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1275 * ACTION_PACKAGE_CHANGED.
1276 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001277 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001278 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001279 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001280
Joe Onorato36115782010-06-17 13:28:48 -04001281 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001282 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001283 // If we have changed locale we need to clear out the labels in all apps/workspace.
1284 forceReload();
1285 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1286 // Check if configuration change was an mcc/mnc change which would affect app resources
1287 // and we would need to clear out the labels in all apps/workspace. Same handling as
1288 // above for ACTION_LOCALE_CHANGED
1289 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001290 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001291 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001292 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001293 forceReload();
1294 }
1295 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001296 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001297 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1298 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001299 Callbacks callbacks = getCallback();
1300 if (callbacks != null) {
1301 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001302 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001303 }
1304 }
1305
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001306 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001307 resetLoadedState(true, true);
1308
Reena Lee93f824a2011-09-23 17:20:28 -07001309 // Do this here because if the launcher activity is running it will be restarted.
1310 // If it's not running startLoaderFromBackground will merely tell it that it needs
1311 // to reload.
1312 startLoaderFromBackground();
1313 }
1314
Winson Chungf0c6ae02012-03-21 16:10:31 -07001315 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1316 synchronized (mLock) {
1317 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1318 // mWorkspaceLoaded to true later
1319 stopLoaderLocked();
1320 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1321 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1322 }
1323 }
1324
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001325 /**
1326 * When the launcher is in the background, it's possible for it to miss paired
1327 * configuration changes. So whenever we trigger the loader from the background
1328 * tell the launcher that it needs to re-run the loader when it comes back instead
1329 * of doing it now.
1330 */
1331 public void startLoaderFromBackground() {
1332 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001333 Callbacks callbacks = getCallback();
1334 if (callbacks != null) {
1335 // Only actually run the loader if they're not paused.
1336 if (!callbacks.setLoadOnResume()) {
1337 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001338 }
1339 }
1340 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001341 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001342 }
Joe Onorato36115782010-06-17 13:28:48 -04001343 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001344
Reena Lee93f824a2011-09-23 17:20:28 -07001345 // If there is already a loader task running, tell it to stop.
1346 // returns true if isLaunching() was true on the old task
1347 private boolean stopLoaderLocked() {
1348 boolean isLaunching = false;
1349 LoaderTask oldTask = mLoaderTask;
1350 if (oldTask != null) {
1351 if (oldTask.isLaunching()) {
1352 isLaunching = true;
1353 }
1354 oldTask.stopLocked();
1355 }
1356 return isLaunching;
1357 }
1358
Adam Cohen1a85c582014-09-30 09:48:49 -07001359 public boolean isCurrentCallbacks(Callbacks callbacks) {
1360 return (mCallbacks != null && mCallbacks.get() == callbacks);
1361 }
1362
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001363 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001364 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1365 }
1366
1367 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001368 synchronized (mLock) {
1369 if (DEBUG_LOADERS) {
1370 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1371 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001372
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001373 // Clear any deferred bind-runnables from the synchronized load process
1374 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001375 synchronized (mDeferredBindRunnables) {
1376 mDeferredBindRunnables.clear();
1377 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001378
Joe Onorato36115782010-06-17 13:28:48 -04001379 // Don't bother to start the thread if we know it's not going to do anything
1380 if (mCallbacks != null && mCallbacks.get() != null) {
1381 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001382 // also, don't downgrade isLaunching if we're already running
1383 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001384 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001385 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1386 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1388 } else {
1389 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1390 sWorker.post(mLoaderTask);
1391 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001392 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001393 }
1394 }
1395
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001396 void bindRemainingSynchronousPages() {
1397 // Post the remaining side pages to be loaded
1398 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001399 Runnable[] deferredBindRunnables = null;
1400 synchronized (mDeferredBindRunnables) {
1401 deferredBindRunnables = mDeferredBindRunnables.toArray(
1402 new Runnable[mDeferredBindRunnables.size()]);
1403 mDeferredBindRunnables.clear();
1404 }
1405 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001406 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001407 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001408 }
1409 }
1410
Joe Onorato36115782010-06-17 13:28:48 -04001411 public void stopLoader() {
1412 synchronized (mLock) {
1413 if (mLoaderTask != null) {
1414 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001415 }
1416 }
Joe Onorato36115782010-06-17 13:28:48 -04001417 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001418
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001419 /**
1420 * Loads the workspace screen ids in an ordered list.
1421 */
Adam Cohen091440a2015-03-18 14:16:05 -07001422 @Thunk static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001423 final ContentResolver contentResolver = context.getContentResolver();
1424 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001425
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001426 // Get screens ordered by rank.
1427 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1428 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1429 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001430 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001431 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001432 while (sc.moveToNext()) {
1433 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001434 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001435 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001436 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1437 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001438 }
1439 }
1440 } finally {
1441 sc.close();
1442 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001443 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001444 }
1445
Michael Jurkac57b7a82011-08-09 22:02:20 -07001446 public boolean isAllAppsLoaded() {
1447 return mAllAppsLoaded;
1448 }
1449
Winson Chung36a62fe2012-05-06 18:04:42 -07001450 boolean isLoadingWorkspace() {
1451 synchronized (mLock) {
1452 if (mLoaderTask != null) {
1453 return mLoaderTask.isLoadingWorkspace();
1454 }
1455 }
1456 return false;
1457 }
1458
Joe Onorato36115782010-06-17 13:28:48 -04001459 /**
1460 * Runnable for the thread that loads the contents of the launcher:
1461 * - workspace icons
1462 * - widgets
1463 * - all apps icons
1464 */
1465 private class LoaderTask implements Runnable {
1466 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001467 private boolean mIsLaunching;
Adam Cohen091440a2015-03-18 14:16:05 -07001468 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001469 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -07001470 @Thunk boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001471 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001472
Dan Sandlerd5024042014-01-09 15:01:33 -05001473 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001474 mContext = context;
1475 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001476 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001477 }
1478
Joe Onorato36115782010-06-17 13:28:48 -04001479 boolean isLaunching() {
1480 return mIsLaunching;
1481 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001482
Winson Chung36a62fe2012-05-06 18:04:42 -07001483 boolean isLoadingWorkspace() {
1484 return mIsLoadingAndBindingWorkspace;
1485 }
1486
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001487 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001488 mIsLoadingAndBindingWorkspace = true;
1489
Joe Onorato36115782010-06-17 13:28:48 -04001490 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001491 if (DEBUG_LOADERS) {
1492 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001493 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001494
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001495 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001496 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001497 synchronized (LoaderTask.this) {
1498 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001499 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001500 }
1501 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001502 }
1503 }
1504
Joe Onorato36115782010-06-17 13:28:48 -04001505 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001506 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001507 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001508
Joe Onorato36115782010-06-17 13:28:48 -04001509 private void waitForIdle() {
1510 // Wait until the either we're stopped or the other threads are done.
1511 // This way we don't start loading all apps until the workspace has settled
1512 // down.
1513 synchronized (LoaderTask.this) {
1514 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001515
Joe Onorato36115782010-06-17 13:28:48 -04001516 mHandler.postIdle(new Runnable() {
1517 public void run() {
1518 synchronized (LoaderTask.this) {
1519 mLoadAndBindStepFinished = true;
1520 if (DEBUG_LOADERS) {
1521 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001522 }
Joe Onorato36115782010-06-17 13:28:48 -04001523 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001524 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001525 }
Joe Onorato36115782010-06-17 13:28:48 -04001526 });
1527
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001528 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001529 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001530 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1531 // wait no longer than 1sec at a time
1532 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001533 } catch (InterruptedException ex) {
1534 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001535 }
1536 }
Joe Onorato36115782010-06-17 13:28:48 -04001537 if (DEBUG_LOADERS) {
1538 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001539 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001540 + "ms for previous step to finish binding");
1541 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001542 }
Joe Onorato36115782010-06-17 13:28:48 -04001543 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001544
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001545 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001546 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001547 // Ensure that we have a valid page index to load synchronously
1548 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1549 "valid page index");
1550 }
1551 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1552 // Ensure that we don't try and bind a specified page when the pages have not been
1553 // loaded already (we should load everything asynchronously in that case)
1554 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1555 }
1556 synchronized (mLock) {
1557 if (mIsLoaderTaskRunning) {
1558 // Ensure that we are never running the background loading at this point since
1559 // we also touch the background collections
1560 throw new RuntimeException("Error! Background loading is already running");
1561 }
1562 }
1563
1564 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1565 // data structures, we can't allow any other thread to touch that data, but because
1566 // this call is synchronous, we can get away with not locking).
1567
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001568 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001569 // operations from the previous activity. We need to ensure that all queued operations
1570 // are executed before any synchronous binding work is done.
1571 mHandler.flush();
1572
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001573 // Divide the set of loaded items into those that we are binding synchronously, and
1574 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001575 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001576 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1577 // arise from that.
1578 onlyBindAllApps();
1579 }
1580
Joe Onorato36115782010-06-17 13:28:48 -04001581 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 synchronized (mLock) {
1583 mIsLoaderTaskRunning = true;
1584 }
Joe Onorato36115782010-06-17 13:28:48 -04001585 // Optimize for end-user experience: if the Launcher is up and // running with the
1586 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1587 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001588 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001589 // Elevate priority when Home launches for the first time to avoid
1590 // starving at boot time. Staring at a blank home is not cool.
1591 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001592 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1593 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001594 android.os.Process.setThreadPriority(mIsLaunching
1595 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1596 }
Winson Chung64359a52013-07-08 17:17:08 -07001597 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001598 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001599
Joe Onorato36115782010-06-17 13:28:48 -04001600 if (mStopped) {
1601 break keep_running;
1602 }
1603
1604 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1605 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001606 synchronized (mLock) {
1607 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001608 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001609 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1610 }
1611 }
Joe Onorato36115782010-06-17 13:28:48 -04001612 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001613
1614 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001615 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1616 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001617
Sunny Goyal5b0e6692015-03-19 14:31:19 -07001618 // Remove entries for packages which changed while the launcher was dead.
1619 LauncherAppState.getInstance().getWidgetCache().removeObsoletePreviews();
1620
Winson Chung7ed37742011-09-08 15:45:51 -07001621 // Restore the default thread priority after we are done loading items
1622 synchronized (mLock) {
1623 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1624 }
Joe Onorato36115782010-06-17 13:28:48 -04001625 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001626
Joe Onorato36115782010-06-17 13:28:48 -04001627 // Clear out this reference, otherwise we end up holding it until all of the
1628 // callback runnables are done.
1629 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001630
Joe Onorato36115782010-06-17 13:28:48 -04001631 synchronized (mLock) {
1632 // If we are still the last one to be scheduled, remove ourselves.
1633 if (mLoaderTask == this) {
1634 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001635 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001636 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001637 }
Joe Onorato36115782010-06-17 13:28:48 -04001638 }
1639
1640 public void stopLocked() {
1641 synchronized (LoaderTask.this) {
1642 mStopped = true;
1643 this.notify();
1644 }
1645 }
1646
1647 /**
1648 * Gets the callbacks object. If we've been stopped, or if the launcher object
1649 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1650 * object that was around when the deferred message was scheduled, and if there's
1651 * a new Callbacks object around then also return null. This will save us from
1652 * calling onto it with data that will be ignored.
1653 */
1654 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1655 synchronized (mLock) {
1656 if (mStopped) {
1657 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001658 }
Joe Onorato36115782010-06-17 13:28:48 -04001659
1660 if (mCallbacks == null) {
1661 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001662 }
Joe Onorato36115782010-06-17 13:28:48 -04001663
1664 final Callbacks callbacks = mCallbacks.get();
1665 if (callbacks != oldCallbacks) {
1666 return null;
1667 }
1668 if (callbacks == null) {
1669 Log.w(TAG, "no mCallbacks");
1670 return null;
1671 }
1672
1673 return callbacks;
1674 }
1675 }
1676
1677 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001678 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001679 LauncherAppState app = LauncherAppState.getInstance();
1680 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001681 final int countX = (int) grid.numColumns;
1682 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001683
Adam Cohendcd297f2013-06-18 13:13:40 -07001684 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001685 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001686 // Return early if we detect that an item is under the hotseat button
1687 if (mCallbacks == null ||
1688 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001689 Log.e(TAG, "Error loading shortcut into hotseat " + item
1690 + " into position (" + item.screenId + ":" + item.cellX + ","
1691 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001692 return false;
1693 }
1694
Dan Sandler295ae182013-12-10 16:05:47 -05001695 final ItemInfo[][] hotseatItems =
1696 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1697
Adam Cohenae4409d2013-11-26 10:34:59 -08001698 if (item.screenId >= grid.numHotseatIcons) {
1699 Log.e(TAG, "Error loading shortcut " + item
1700 + " into hotseat position " + item.screenId
1701 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1702 + ")");
1703 return false;
1704 }
1705
Dan Sandler295ae182013-12-10 16:05:47 -05001706 if (hotseatItems != null) {
1707 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001708 Log.e(TAG, "Error loading shortcut into hotseat " + item
1709 + " into position (" + item.screenId + ":" + item.cellX + ","
1710 + item.cellY + ") occupied by "
1711 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1712 [(int) item.screenId][0]);
1713 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001714 } else {
1715 hotseatItems[(int) item.screenId][0] = item;
1716 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001717 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001718 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001719 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001720 items[(int) item.screenId][0] = item;
1721 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001722 return true;
1723 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001724 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1725 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001726 return true;
1727 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001728
Adam Cohendcd297f2013-06-18 13:13:40 -07001729 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001730 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001731 occupied.put(item.screenId, items);
1732 }
1733
Dan Sandler295ae182013-12-10 16:05:47 -05001734 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001735 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1736 item.cellX < 0 || item.cellY < 0 ||
1737 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1738 Log.e(TAG, "Error loading shortcut " + item
1739 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1740 + item.cellX + "," + item.cellY
1741 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1742 return false;
1743 }
1744
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001745 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001746 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1747 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001748 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001749 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001750 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001751 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001752 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001753 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001754 return false;
1755 }
1756 }
1757 }
1758 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1759 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001760 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001761 }
1762 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001763
Joe Onorato36115782010-06-17 13:28:48 -04001764 return true;
1765 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001766
Winson Chungba9c37f2013-08-30 14:11:37 -07001767 /** Clears all the sBg data structures */
1768 private void clearSBgDataStructures() {
1769 synchronized (sBgLock) {
1770 sBgWorkspaceItems.clear();
1771 sBgAppWidgets.clear();
1772 sBgFolders.clear();
1773 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001774 sBgWorkspaceScreens.clear();
1775 }
1776 }
1777
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001778 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001779 // Log to disk
1780 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1781
Joe Onorato36115782010-06-17 13:28:48 -04001782 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001783
Joe Onorato36115782010-06-17 13:28:48 -04001784 final Context context = mContext;
1785 final ContentResolver contentResolver = context.getContentResolver();
1786 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001787 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001788 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1789 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001790 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001791
Winson Chung892c74d2013-08-22 16:15:50 -07001792 LauncherAppState app = LauncherAppState.getInstance();
1793 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1794 int countX = (int) grid.numColumns;
1795 int countY = (int) grid.numRows;
1796
Dan Sandlerd5024042014-01-09 15:01:33 -05001797 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1798 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1799 LauncherAppState.getLauncherProvider().deleteDatabase();
1800 }
1801
1802 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1803 // append the user's Launcher2 shortcuts
1804 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1805 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1806 } else {
1807 // Make sure the default workspace is loaded
1808 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001809 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001810 }
Adam Cohene25af792013-06-06 23:08:25 -07001811
Winson Chung2abf94d2012-07-18 18:16:38 -07001812 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001813 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001814 final HashSet<String> installingPkgs = PackageInstallerCompat
1815 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001816
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001817 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001818 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07001819 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
Chris Wrene523e702013-10-09 10:36:55 -04001820 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001821 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001822
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001823 // +1 for the hotseat (it can be larger than the workspace)
1824 // Load workspace in reverse order to ensure that latest items are loaded first (and
1825 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001826 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001827
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001828 try {
1829 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1830 final int intentIndex = c.getColumnIndexOrThrow
1831 (LauncherSettings.Favorites.INTENT);
1832 final int titleIndex = c.getColumnIndexOrThrow
1833 (LauncherSettings.Favorites.TITLE);
1834 final int iconTypeIndex = c.getColumnIndexOrThrow(
1835 LauncherSettings.Favorites.ICON_TYPE);
1836 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1837 final int iconPackageIndex = c.getColumnIndexOrThrow(
1838 LauncherSettings.Favorites.ICON_PACKAGE);
1839 final int iconResourceIndex = c.getColumnIndexOrThrow(
1840 LauncherSettings.Favorites.ICON_RESOURCE);
1841 final int containerIndex = c.getColumnIndexOrThrow(
1842 LauncherSettings.Favorites.CONTAINER);
1843 final int itemTypeIndex = c.getColumnIndexOrThrow(
1844 LauncherSettings.Favorites.ITEM_TYPE);
1845 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1846 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001847 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1848 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001849 final int screenIndex = c.getColumnIndexOrThrow(
1850 LauncherSettings.Favorites.SCREEN);
1851 final int cellXIndex = c.getColumnIndexOrThrow
1852 (LauncherSettings.Favorites.CELLX);
1853 final int cellYIndex = c.getColumnIndexOrThrow
1854 (LauncherSettings.Favorites.CELLY);
1855 final int spanXIndex = c.getColumnIndexOrThrow
1856 (LauncherSettings.Favorites.SPANX);
1857 final int spanYIndex = c.getColumnIndexOrThrow(
1858 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001859 final int rankIndex = c.getColumnIndexOrThrow(
1860 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001861 final int restoredIndex = c.getColumnIndexOrThrow(
1862 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001863 final int profileIdIndex = c.getColumnIndexOrThrow(
1864 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001865 final int optionsIndex = c.getColumnIndexOrThrow(
1866 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001867
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001868 ShortcutInfo info;
1869 String intentDescription;
1870 LauncherAppWidgetInfo appWidgetInfo;
1871 int container;
1872 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001873 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001874 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001875 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001876
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001877 while (!mStopped && c.moveToNext()) {
1878 try {
1879 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001880 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001881 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001882
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001883 switch (itemType) {
1884 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1885 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001886 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001887 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001888 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001889 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001890 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001891 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001892 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001893 if (user == null) {
1894 // User has been deleted remove the item.
1895 itemsToRemove.add(id);
1896 continue;
1897 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001898 try {
1899 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001900 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001901 if (cn != null && cn.getPackageName() != null) {
1902 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1903 cn.getPackageName(), user);
1904 boolean validComponent = validPkg &&
1905 launcherApps.isActivityEnabledForProfile(cn, user);
1906
1907 if (validComponent) {
1908 if (restored) {
1909 // no special handling necessary for this item
1910 restoredRows.add(id);
1911 restored = false;
1912 }
1913 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001914 intent = null;
1915 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1916 // We allow auto install apps to have their intent
1917 // updated after an install.
1918 intent = manager.getLaunchIntentForPackage(
1919 cn.getPackageName());
1920 if (intent != null) {
1921 ContentValues values = new ContentValues();
1922 values.put(LauncherSettings.Favorites.INTENT,
1923 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001924 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001925 }
1926 }
1927
1928 if (intent == null) {
1929 // The app is installed but the component is no
1930 // longer available.
1931 Launcher.addDumpLog(TAG,
1932 "Invalid component removed: " + cn, true);
1933 itemsToRemove.add(id);
1934 continue;
1935 } else {
1936 // no special handling necessary for this item
1937 restoredRows.add(id);
1938 restored = false;
1939 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001940 } else if (restored) {
1941 // Package is not yet available but might be
1942 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001943 Launcher.addDumpLog(TAG,
1944 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001945
1946 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1947 // Restore has started once.
1948 } else if (installingPkgs.contains(cn.getPackageName())) {
1949 // App restore has started. Update the flag
1950 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1951 ContentValues values = new ContentValues();
1952 values.put(LauncherSettings.Favorites.RESTORED,
1953 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001954 updateItem(id, values);
1955 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1956 // This is a common app. Try to replace this.
1957 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1958 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1959 if (parser.findDefaultApp()) {
1960 // Default app found. Replace it.
1961 intent = parser.parsedIntent;
1962 cn = intent.getComponent();
1963 ContentValues values = parser.parsedValues;
1964 values.put(LauncherSettings.Favorites.RESTORED, 0);
1965 updateItem(id, values);
1966 restored = false;
1967 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001968
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001969 } else if (REMOVE_UNRESTORED_ICONS) {
1970 Launcher.addDumpLog(TAG,
1971 "Unrestored package removed: " + cn, true);
1972 itemsToRemove.add(id);
1973 continue;
1974 }
Sunny Goyal94485362014-09-18 16:13:58 -07001975 } else if (REMOVE_UNRESTORED_ICONS) {
1976 Launcher.addDumpLog(TAG,
1977 "Unrestored package removed: " + cn, true);
1978 itemsToRemove.add(id);
1979 continue;
1980 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001981 } else if (launcherApps.isAppEnabled(
1982 manager, cn.getPackageName(),
1983 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1984 // Package is present but not available.
1985 allowMissingTarget = true;
1986 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1987 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001988 // SdCard is not ready yet. Package might get available,
1989 // once it is ready.
1990 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1991 + " (check again later)", true);
1992 HashSet<String> pkgs = sPendingPackages.get(user);
1993 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001994 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001995 sPendingPackages.put(user, pkgs);
1996 }
1997 pkgs.add(cn.getPackageName());
1998 allowMissingTarget = true;
1999 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002000
2001 } else {
2002 // Do not wait for external media load anymore.
2003 // Log the invalid package, and remove it
2004 Launcher.addDumpLog(TAG,
2005 "Invalid package removed: " + cn, true);
2006 itemsToRemove.add(id);
2007 continue;
Winson Chungee055712013-07-30 14:46:24 -07002008 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002009 } else if (cn == null) {
2010 // For shortcuts with no component, keep them as they are
2011 restoredRows.add(id);
2012 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002013 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002014 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002015 Launcher.addDumpLog(TAG,
2016 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002017 continue;
2018 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002019
Sunny Goyal34b65272015-03-11 16:56:52 -07002020 container = c.getInt(containerIndex);
2021 boolean useLowResIcon = container >= 0 &&
2022 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2023
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002024 if (itemReplaced) {
2025 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002026 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002027 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002028 } else {
2029 // Don't replace items for other profiles.
2030 itemsToRemove.add(id);
2031 continue;
2032 }
2033 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002034 if (user.equals(UserHandleCompat.myUserHandle())) {
2035 Launcher.addDumpLog(TAG,
2036 "constructing info for partially restored package",
2037 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002038 info = getRestoredItemInfo(c, titleIndex, intent,
2039 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002040 intent = getRestoredItemIntent(c, context, intent);
2041 } else {
2042 // Don't restore items for other profiles.
2043 itemsToRemove.add(id);
2044 continue;
2045 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002046 } else if (itemType ==
2047 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002048 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002049 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002050 } else {
2051 info = getShortcutInfo(c, context, iconTypeIndex,
2052 iconPackageIndex, iconResourceIndex, iconIndex,
2053 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002054
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002055 // App shortcuts that used to be automatically added to Launcher
2056 // didn't always have the correct intent flags set, so do that
2057 // here
2058 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002059 intent.getCategories() != null &&
2060 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002061 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002062 intent.addFlags(
2063 Intent.FLAG_ACTIVITY_NEW_TASK |
2064 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2065 }
Michael Jurka96879562012-03-22 05:54:33 -07002066 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002067
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002068 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002069 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002070 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002072 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002073 info.cellX = c.getInt(cellXIndex);
2074 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002075 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002076 info.spanX = 1;
2077 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002078 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002079 info.isDisabled = disabledState;
2080 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2081 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2082 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002083
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002084 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002085 if (!checkItemPlacement(occupied, info)) {
2086 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002087 break;
2088 }
2089
2090 switch (container) {
2091 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2092 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2093 sBgWorkspaceItems.add(info);
2094 break;
2095 default:
2096 // Item is in a user folder
2097 FolderInfo folderInfo =
2098 findOrMakeFolder(sBgFolders, container);
2099 folderInfo.add(info);
2100 break;
2101 }
2102 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002103 } else {
2104 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002105 }
2106 break;
2107
2108 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2109 id = c.getLong(idIndex);
2110 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2111
2112 folderInfo.title = c.getString(titleIndex);
2113 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002114 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002115 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002116 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002117 folderInfo.cellX = c.getInt(cellXIndex);
2118 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002119 folderInfo.spanX = 1;
2120 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002121 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002122
Daniel Sandler8802e962010-05-26 16:28:16 -04002123 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002124 if (!checkItemPlacement(occupied, folderInfo)) {
2125 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002126 break;
2127 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002128
Joe Onorato9c1289c2009-08-17 11:03:03 -04002129 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002130 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2131 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2132 sBgWorkspaceItems.add(folderInfo);
2133 break;
Joe Onorato36115782010-06-17 13:28:48 -04002134 }
Joe Onorato17a89222011-02-08 17:26:11 -08002135
Chris Wrenf4d08112014-01-16 18:13:56 -05002136 if (restored) {
2137 // no special handling required for restored folders
2138 restoredRows.add(id);
2139 }
2140
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002141 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2142 sBgFolders.put(folderInfo.id, folderInfo);
2143 break;
2144
2145 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002146 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002147 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002148 boolean customWidget = itemType ==
2149 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2150
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002151 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002152 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002153 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002154 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002155 final ComponentName component =
2156 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002157
Sunny Goyal651077b2014-06-30 14:15:31 -07002158 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002159 final boolean isIdValid = (restoreStatus &
2160 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002161
Sunny Goyalff572272014-07-23 13:58:07 -07002162 final boolean wasProviderReady = (restoreStatus &
2163 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002164
Adam Cohen59400422014-03-05 18:07:04 -08002165 final LauncherAppWidgetProviderInfo provider =
2166 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002167 ComponentName.unflattenFromString(savedProvider),
2168 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002169
2170 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002171 if (!isSafeMode && !customWidget &&
2172 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002173 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002174 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002175
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002176 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002177 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002178 itemsToRemove.add(id);
2179 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002180 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002181 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2182 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002183
2184 if (!customWidget) {
2185 int[] minSpan =
2186 Launcher.getMinSpanForWidget(context, provider);
2187 appWidgetInfo.minSpanX = minSpan[0];
2188 appWidgetInfo.minSpanY = minSpan[1];
2189 }
Sunny Goyalff572272014-07-23 13:58:07 -07002190
2191 int status = restoreStatus;
2192 if (!wasProviderReady) {
2193 // If provider was not previously ready, update the
2194 // status and UI flag.
2195
2196 // Id would be valid only if the widget restore broadcast was received.
2197 if (isIdValid) {
2198 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2199 } else {
2200 status &= ~LauncherAppWidgetInfo
2201 .FLAG_PROVIDER_NOT_READY;
2202 }
2203 }
2204 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002205 } else {
2206 Log.v(TAG, "Widget restore pending id=" + id
2207 + " appWidgetId=" + appWidgetId
2208 + " status =" + restoreStatus);
2209 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002210 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002211 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002212
2213 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2214 // Restore has started once.
2215 } else if (installingPkgs.contains(component.getPackageName())) {
2216 // App restore has started. Update the flag
2217 appWidgetInfo.restoreStatus |=
2218 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002219 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002220 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002221 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002222 itemsToRemove.add(id);
2223 continue;
2224 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002225 }
Sunny Goyalff572272014-07-23 13:58:07 -07002226
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002227 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002228 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002229 appWidgetInfo.cellX = c.getInt(cellXIndex);
2230 appWidgetInfo.cellY = c.getInt(cellYIndex);
2231 appWidgetInfo.spanX = c.getInt(spanXIndex);
2232 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002233
Adam Cohen59400422014-03-05 18:07:04 -08002234 if (!customWidget) {
2235 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2236 appWidgetInfo.minSpanX = minSpan[0];
2237 appWidgetInfo.minSpanY = minSpan[1];
2238 }
2239
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002240 container = c.getInt(containerIndex);
2241 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2242 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2243 Log.e(TAG, "Widget found where container != " +
2244 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2245 continue;
2246 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002247
Adam Cohene25af792013-06-06 23:08:25 -07002248 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002249 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002250 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2251 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002252 break;
2253 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002254
Adam Cohen59400422014-03-05 18:07:04 -08002255 if (!customWidget) {
2256 String providerName =
2257 appWidgetInfo.providerName.flattenToString();
2258 if (!providerName.equals(savedProvider) ||
2259 (appWidgetInfo.restoreStatus != restoreStatus)) {
2260 ContentValues values = new ContentValues();
2261 values.put(
2262 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2263 providerName);
2264 values.put(LauncherSettings.Favorites.RESTORED,
2265 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002266 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002267 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002268 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002269 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2270 sBgAppWidgets.add(appWidgetInfo);
2271 }
Joe Onorato36115782010-06-17 13:28:48 -04002272 break;
2273 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002274 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002275 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002276 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002277 }
2278 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002279 if (c != null) {
2280 c.close();
2281 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002282 }
2283
Winson Chungba9c37f2013-08-30 14:11:37 -07002284 // Break early if we've stopped loading
2285 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002286 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002287 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002288 }
2289
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002290 if (itemsToRemove.size() > 0) {
2291 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002292 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 // Remove dead items
2294 for (long id : itemsToRemove) {
2295 if (DEBUG_LOADERS) {
2296 Log.d(TAG, "Removed id = " + id);
2297 }
2298 // Don't notify content observers
2299 try {
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002300 client.delete(LauncherSettings.Favorites.getContentUri(id), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002301 } catch (RemoteException e) {
2302 Log.w(TAG, "Could not remove id = " + id);
2303 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002304 }
2305 }
2306
Chris Wrenf4d08112014-01-16 18:13:56 -05002307 if (restoredRows.size() > 0) {
2308 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002309 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002310 // Update restored items that no longer require special handling
2311 try {
2312 StringBuilder selectionBuilder = new StringBuilder();
2313 selectionBuilder.append(LauncherSettings.Favorites._ID);
2314 selectionBuilder.append(" IN (");
2315 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2316 selectionBuilder.append(")");
2317 ContentValues values = new ContentValues();
2318 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002319 updater.update(LauncherSettings.Favorites.CONTENT_URI,
Chris Wrenf4d08112014-01-16 18:13:56 -05002320 values, selectionBuilder.toString(), null);
2321 } catch (RemoteException e) {
2322 Log.w(TAG, "Could not update restored rows");
2323 }
2324 }
2325
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002326 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2327 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002328 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002329 null, sWorker);
2330 }
2331
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002332 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2333 // Log to disk
2334 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2335 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002336
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002337 // Remove any empty screens
2338 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2339 for (ItemInfo item: sBgItemsIdMap.values()) {
2340 long screenId = item.screenId;
2341 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2342 unusedScreens.contains(screenId)) {
2343 unusedScreens.remove(screenId);
2344 }
2345 }
2346
2347 // If there are any empty screens remove them, and update.
2348 if (unusedScreens.size() != 0) {
2349 // Log to disk
2350 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2351 TextUtils.join(", ", unusedScreens), true);
2352
2353 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002354 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002355 }
2356
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002357 if (DEBUG_LOADERS) {
2358 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2359 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002360 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002361 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002362 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002363
Daniel Sandler566da102013-06-25 23:43:45 -04002364 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002365 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002366 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002367 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002368 line += " | ";
2369 }
Winson Chung892c74d2013-08-22 16:15:50 -07002370 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002371 ItemInfo[][] screen = occupied.get(screenId);
2372 if (x < screen.length && y < screen[x].length) {
2373 line += (screen[x][y] != null) ? "#" : ".";
2374 } else {
2375 line += "!";
2376 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002377 }
Joe Onorato36115782010-06-17 13:28:48 -04002378 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002379 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002380 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002381 }
Joe Onorato36115782010-06-17 13:28:48 -04002382 }
Adam Cohene25af792013-06-06 23:08:25 -07002383 }
2384
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002385 /**
2386 * Partially updates the item without any notification. Must be called on the worker thread.
2387 */
2388 private void updateItem(long itemId, ContentValues update) {
2389 mContext.getContentResolver().update(
Sunny Goyal1d4a2df2015-03-30 11:11:46 -07002390 LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002391 update,
2392 BaseColumns._ID + "= ?",
2393 new String[]{Long.toString(itemId)});
2394 }
2395
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002396 /** Filters the set of items who are directly or indirectly (via another container) on the
2397 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002398 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002399 ArrayList<ItemInfo> allWorkspaceItems,
2400 ArrayList<ItemInfo> currentScreenItems,
2401 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002402 // Purge any null ItemInfos
2403 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2404 while (iter.hasNext()) {
2405 ItemInfo i = iter.next();
2406 if (i == null) {
2407 iter.remove();
2408 }
2409 }
2410
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002411 // Order the set of items by their containers first, this allows use to walk through the
2412 // list sequentially, build up a list of containers that are in the specified screen,
2413 // as well as all items in those containers.
2414 Set<Long> itemsOnScreen = new HashSet<Long>();
2415 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2416 @Override
2417 public int compare(ItemInfo lhs, ItemInfo rhs) {
2418 return (int) (lhs.container - rhs.container);
2419 }
2420 });
2421 for (ItemInfo info : allWorkspaceItems) {
2422 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002423 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002424 currentScreenItems.add(info);
2425 itemsOnScreen.add(info.id);
2426 } else {
2427 otherScreenItems.add(info);
2428 }
2429 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2430 currentScreenItems.add(info);
2431 itemsOnScreen.add(info.id);
2432 } else {
2433 if (itemsOnScreen.contains(info.container)) {
2434 currentScreenItems.add(info);
2435 itemsOnScreen.add(info.id);
2436 } else {
2437 otherScreenItems.add(info);
2438 }
2439 }
2440 }
2441 }
2442
2443 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002444 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002445 ArrayList<LauncherAppWidgetInfo> appWidgets,
2446 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2447 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002448
2449 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002450 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002451 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002452 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002453 currentScreenWidgets.add(widget);
2454 } else {
2455 otherScreenWidgets.add(widget);
2456 }
2457 }
2458 }
2459
2460 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002461 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002462 HashMap<Long, ItemInfo> itemsIdMap,
2463 HashMap<Long, FolderInfo> folders,
2464 HashMap<Long, FolderInfo> currentScreenFolders,
2465 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466
2467 for (long id : folders.keySet()) {
2468 ItemInfo info = itemsIdMap.get(id);
2469 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002470 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002471 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002472 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002473 currentScreenFolders.put(id, folder);
2474 } else {
2475 otherScreenFolders.put(id, folder);
2476 }
2477 }
2478 }
2479
2480 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2481 * right) */
2482 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002483 final LauncherAppState app = LauncherAppState.getInstance();
2484 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002485 // XXX: review this
2486 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002487 @Override
2488 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002489 int cellCountX = (int) grid.numColumns;
2490 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002491 int screenOffset = cellCountX * cellCountY;
2492 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002493 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002494 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002495 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002496 rhs.cellY * cellCountX + rhs.cellX);
2497 return (int) (lr - rr);
2498 }
2499 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002500 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002501
Adam Cohendcd297f2013-06-18 13:13:40 -07002502 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2503 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002504 final Runnable r = new Runnable() {
2505 @Override
2506 public void run() {
2507 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2508 if (callbacks != null) {
2509 callbacks.bindScreens(orderedScreens);
2510 }
2511 }
2512 };
2513 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2514 }
2515
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002516 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2517 final ArrayList<ItemInfo> workspaceItems,
2518 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2519 final HashMap<Long, FolderInfo> folders,
2520 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002521
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002522 final boolean postOnMainThread = (deferredBindRunnables != null);
2523
2524 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002525 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002527 final int start = i;
2528 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002529 final Runnable r = new Runnable() {
2530 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002531 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002532 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002533 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002534 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2535 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002536 }
2537 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002538 };
2539 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002540 synchronized (deferredBindRunnables) {
2541 deferredBindRunnables.add(r);
2542 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002543 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002544 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002545 }
Joe Onorato36115782010-06-17 13:28:48 -04002546 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547
2548 // Bind the folders
2549 if (!folders.isEmpty()) {
2550 final Runnable r = new Runnable() {
2551 public void run() {
2552 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2553 if (callbacks != null) {
2554 callbacks.bindFolders(folders);
2555 }
2556 }
2557 };
2558 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002559 synchronized (deferredBindRunnables) {
2560 deferredBindRunnables.add(r);
2561 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002562 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002563 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002564 }
2565 }
2566
2567 // Bind the widgets, one at a time
2568 N = appWidgets.size();
2569 for (int i = 0; i < N; i++) {
2570 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2571 final Runnable r = new Runnable() {
2572 public void run() {
2573 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2574 if (callbacks != null) {
2575 callbacks.bindAppWidget(widget);
2576 }
2577 }
2578 };
2579 if (postOnMainThread) {
2580 deferredBindRunnables.add(r);
2581 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002582 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002583 }
2584 }
2585 }
2586
2587 /**
2588 * Binds all loaded data to actual views on the main thread.
2589 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002590 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002591 final long t = SystemClock.uptimeMillis();
2592 Runnable r;
2593
2594 // Don't use these two variables in any of the callback runnables.
2595 // Otherwise we hold a reference to them.
2596 final Callbacks oldCallbacks = mCallbacks.get();
2597 if (oldCallbacks == null) {
2598 // This launcher has exited and nobody bothered to tell us. Just bail.
2599 Log.w(TAG, "LoaderTask running with no launcher");
2600 return;
2601 }
2602
Winson Chung9b9fb962013-11-15 15:39:34 -08002603 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002604 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2605 ArrayList<LauncherAppWidgetInfo> appWidgets =
2606 new ArrayList<LauncherAppWidgetInfo>();
2607 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2608 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002609 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002610 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002611 workspaceItems.addAll(sBgWorkspaceItems);
2612 appWidgets.addAll(sBgAppWidgets);
2613 folders.putAll(sBgFolders);
2614 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002615 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002616 }
2617
Derek Prothro7aff3992013-12-10 14:00:37 -05002618 final boolean isLoadingSynchronously =
2619 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002620 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002621 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002622 if (currScreen >= orderedScreenIds.size()) {
2623 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002624 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002625 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002626 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002627 final long currentScreenId = currentScreen < 0
2628 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002629
2630 // Load all the items that are on the current page first (and in the process, unbind
2631 // all the existing workspace items before we call startBinding() below.
2632 unbindWorkspaceItemsOnMainThread();
2633
2634 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002635 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2636 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2637 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2638 new ArrayList<LauncherAppWidgetInfo>();
2639 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2640 new ArrayList<LauncherAppWidgetInfo>();
2641 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2642 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2643
Winson Chung9b9fb962013-11-15 15:39:34 -08002644 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002645 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002646 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002647 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002648 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002649 otherFolders);
2650 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2651 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2652
2653 // Tell the workspace that we're about to start binding items
2654 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002655 public void run() {
2656 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2657 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002658 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002659 }
2660 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002661 };
Winson Chung81b52252012-08-27 15:34:29 -07002662 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002663
Adam Cohendcd297f2013-06-18 13:13:40 -07002664 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2665
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002666 // Load items on the current page
2667 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2668 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002669 if (isLoadingSynchronously) {
2670 r = new Runnable() {
2671 public void run() {
2672 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002673 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002674 callbacks.onPageBoundSynchronously(currentScreen);
2675 }
2676 }
2677 };
Winson Chung81b52252012-08-27 15:34:29 -07002678 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002679 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002680
Winson Chung4a2afa32012-07-19 14:53:05 -07002681 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2682 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002683 synchronized (mDeferredBindRunnables) {
2684 mDeferredBindRunnables.clear();
2685 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002686 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002687 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002688
2689 // Tell the workspace that we're done binding items
2690 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002691 public void run() {
2692 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2693 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002694 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002695 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002696
Winson Chung98e030b2012-05-07 16:01:11 -07002697 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002698 if (DEBUG_LOADERS) {
2699 Log.d(TAG, "bound workspace in "
2700 + (SystemClock.uptimeMillis()-t) + "ms");
2701 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002702
2703 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002704 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002705 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002706 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002707 synchronized (mDeferredBindRunnables) {
2708 mDeferredBindRunnables.add(r);
2709 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002710 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002711 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002712 }
Joe Onorato36115782010-06-17 13:28:48 -04002713 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002714
Joe Onorato36115782010-06-17 13:28:48 -04002715 private void loadAndBindAllApps() {
2716 if (DEBUG_LOADERS) {
2717 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2718 }
2719 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002720 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002721 synchronized (LoaderTask.this) {
2722 if (mStopped) {
2723 return;
2724 }
2725 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002726 }
Joe Onorato36115782010-06-17 13:28:48 -04002727 } else {
2728 onlyBindAllApps();
2729 }
2730 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002731
Joe Onorato36115782010-06-17 13:28:48 -04002732 private void onlyBindAllApps() {
2733 final Callbacks oldCallbacks = mCallbacks.get();
2734 if (oldCallbacks == null) {
2735 // This launcher has exited and nobody bothered to tell us. Just bail.
2736 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2737 return;
2738 }
2739
2740 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002741 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002742 final ArrayList<AppInfo> list
2743 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002744 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002745 public void run() {
2746 final long t = SystemClock.uptimeMillis();
2747 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2748 if (callbacks != null) {
2749 callbacks.bindAllApplications(list);
2750 }
2751 if (DEBUG_LOADERS) {
2752 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2753 + (SystemClock.uptimeMillis()-t) + "ms");
2754 }
2755 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002756 };
2757 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002758 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002759 r.run();
2760 } else {
2761 mHandler.post(r);
2762 }
Joe Onorato36115782010-06-17 13:28:48 -04002763 }
2764
Winson Chung64359a52013-07-08 17:17:08 -07002765 private void loadAllApps() {
2766 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002767
Joe Onorato36115782010-06-17 13:28:48 -04002768 final Callbacks oldCallbacks = mCallbacks.get();
2769 if (oldCallbacks == null) {
2770 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002771 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002772 return;
2773 }
2774
2775 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2776 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2777
Kenny Guyed131872014-04-30 03:02:21 +01002778 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2779
Winson Chung64359a52013-07-08 17:17:08 -07002780 // Clear the list of apps
2781 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002782 SharedPreferences prefs = mContext.getSharedPreferences(
2783 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002784 for (UserHandleCompat user : profiles) {
2785 // Query for the set of apps
2786 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2787 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2788 if (DEBUG_LOADERS) {
2789 Log.d(TAG, "getActivityList took "
2790 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2791 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2792 }
2793 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002794 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002795 if (apps == null || apps.isEmpty()) {
2796 return;
2797 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002798
2799 // Update icon cache
2800 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2801
2802 // If any package icon has changed (app was updated while launcher was dead),
2803 // update the corresponding shortcuts.
2804 if (!updatedPackages.isEmpty()) {
2805 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2806 synchronized (sBgLock) {
2807 for (ItemInfo info : sBgItemsIdMap.values()) {
2808 if (info instanceof ShortcutInfo && user.equals(info.user)
2809 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2810 ShortcutInfo si = (ShortcutInfo) info;
2811 ComponentName cn = si.getTargetComponent();
2812 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2813 si.updateIcon(mIconCache);
2814 updates.add(si);
2815 }
2816 }
2817 }
2818 }
2819
2820 if (!updates.isEmpty()) {
2821 final UserHandleCompat userFinal = user;
2822 mHandler.post(new Runnable() {
2823
2824 public void run() {
2825 Callbacks cb = getCallback();
2826 if (cb != null) {
2827 cb.bindShortcutsChanged(
2828 updates, new ArrayList<ShortcutInfo>(), userFinal);
2829 }
2830 }
2831 });
2832 }
Kenny Guyed131872014-04-30 03:02:21 +01002833 }
Joe Onorato36115782010-06-17 13:28:48 -04002834
Kenny Guyed131872014-04-30 03:02:21 +01002835 // Create the ApplicationInfos
2836 for (int i = 0; i < apps.size(); i++) {
2837 LauncherActivityInfoCompat app = apps.get(i);
2838 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002839 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002840 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002841
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002842 if (!user.equals(UserHandleCompat.myUserHandle())) {
2843 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
2844 if (heuristic != null) {
2845 heuristic.processUserApps(apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002846 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002847 }
Winson Chung64359a52013-07-08 17:17:08 -07002848 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002849 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002850 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2851 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002852
2853 // Post callback on main thread
2854 mHandler.post(new Runnable() {
2855 public void run() {
2856 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002857 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002858 if (callbacks != null) {
2859 callbacks.bindAllApplications(added);
2860 if (DEBUG_LOADERS) {
2861 Log.d(TAG, "bound " + added.size() + " apps in "
2862 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2863 }
2864 } else {
2865 Log.i(TAG, "not binding apps: no Launcher activity");
2866 }
2867 }
2868 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002869 // Cleanup any data stored for a deleted user.
2870 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Winson Chung64359a52013-07-08 17:17:08 -07002871
Joe Onorato36115782010-06-17 13:28:48 -04002872 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002873 Log.d(TAG, "Icons processed in "
2874 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002875 }
2876 }
2877
2878 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002879 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002880 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2881 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2882 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2883 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2884 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2885 }
Joe Onorato36115782010-06-17 13:28:48 -04002886 }
2887 }
2888
2889 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002890 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002891 }
2892
Adam Cohen091440a2015-03-18 14:16:05 -07002893 @Thunk class AppsAvailabilityCheck extends BroadcastReceiver {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002894
2895 @Override
2896 public void onReceive(Context context, Intent intent) {
2897 synchronized (sBgLock) {
2898 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2899 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002900 final PackageManager manager = context.getPackageManager();
2901 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2902 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002903 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2904 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002905 packagesRemoved.clear();
2906 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002907 for (String pkg : entry.getValue()) {
2908 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002909 boolean packageOnSdcard = launcherApps.isAppEnabled(
2910 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2911 if (packageOnSdcard) {
2912 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2913 packagesUnavailable.add(pkg);
2914 } else {
2915 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2916 packagesRemoved.add(pkg);
2917 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002918 }
2919 }
2920 if (!packagesRemoved.isEmpty()) {
2921 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2922 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2923 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002924 if (!packagesUnavailable.isEmpty()) {
2925 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2926 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2927 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002928 }
Sunny Goyal34942622014-08-29 17:20:55 -07002929 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002930 }
2931 }
2932 }
2933
Joe Onorato36115782010-06-17 13:28:48 -04002934 private class PackageUpdatedTask implements Runnable {
2935 int mOp;
2936 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002937 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002938
2939 public static final int OP_NONE = 0;
2940 public static final int OP_ADD = 1;
2941 public static final int OP_UPDATE = 2;
2942 public static final int OP_REMOVE = 3; // uninstlled
2943 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2944
2945
Kenny Guyed131872014-04-30 03:02:21 +01002946 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002947 mOp = op;
2948 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002949 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002950 }
2951
2952 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002953 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002954
2955 final String[] packages = mPackages;
2956 final int N = packages.length;
2957 switch (mOp) {
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002958 case OP_ADD: {
Joe Onorato36115782010-06-17 13:28:48 -04002959 for (int i=0; i<N; i++) {
2960 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002961 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002962 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002963 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002964
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002965 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2966 if (heuristic != null) {
2967 heuristic.processPackageAdd(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002968 }
Joe Onorato36115782010-06-17 13:28:48 -04002969 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002970 }
Joe Onorato36115782010-06-17 13:28:48 -04002971 case OP_UPDATE:
2972 for (int i=0; i<N; i++) {
2973 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002974 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002975 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002976 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002977 }
2978 break;
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002979 case OP_REMOVE: {
2980 ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(context, mUser);
2981 if (heuristic != null) {
2982 heuristic.processPackageRemoved(mPackages);
Sunny Goyale0f58d72014-11-10 18:05:31 -08002983 }
Joe Onorato36115782010-06-17 13:28:48 -04002984 for (int i=0; i<N; i++) {
2985 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002986 mIconCache.removeIconsForPkg(packages[i], mUser);
2987 }
2988 // Fall through
Sunny Goyal18bf8e22015-04-08 18:13:46 -07002989 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002990 case OP_UNAVAILABLE:
2991 for (int i=0; i<N; i++) {
2992 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
2993 mBgAllAppsList.removePackage(packages[i], mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -07002994 mApp.getWidgetCache().removePackage(packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002995 }
2996 break;
2997 }
2998
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002999 ArrayList<AppInfo> added = null;
3000 ArrayList<AppInfo> modified = null;
3001 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003002
Adam Cohen487f7dd2012-06-28 18:12:10 -07003003 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003004 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003005 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003006 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003007 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003008 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003009 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003010 }
Winson Chung5d55f332012-07-16 20:45:03 -07003011 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003012 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003013 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003014 }
3015
Sunny Goyale0f58d72014-11-10 18:05:31 -08003016 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003017 if (callbacks == null) {
3018 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3019 return;
3020 }
3021
Sunny Goyal4390ace2014-10-13 11:33:11 -07003022 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3023 new HashMap<ComponentName, AppInfo>();
3024
Joe Onorato36115782010-06-17 13:28:48 -04003025 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003026 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003027 for (AppInfo ai : added) {
3028 addedOrUpdatedApps.put(ai.componentName, ai);
3029 }
Joe Onorato36115782010-06-17 13:28:48 -04003030 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003031
Joe Onorato36115782010-06-17 13:28:48 -04003032 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003033 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003034 for (AppInfo ai : modified) {
3035 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003036 }
3037
Joe Onorato36115782010-06-17 13:28:48 -04003038 mHandler.post(new Runnable() {
3039 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003040 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003041 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003042 callbacks.bindAppsUpdated(modifiedFinal);
3043 }
3044 }
3045 });
3046 }
Winson Chung83892cc2013-05-01 16:53:33 -07003047
Sunny Goyal4390ace2014-10-13 11:33:11 -07003048 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003049 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003050 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3051 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3052 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3053
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003054 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003055 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003056 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003057 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3058 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003059 boolean infoUpdated = false;
3060 boolean shortcutUpdated = false;
3061
3062 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003063 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003064 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003065 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3066 si.iconResource.resourceName, mIconCache, context);
3067 if (icon != null) {
3068 si.setIcon(icon);
3069 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003070 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003071 }
3072 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003073
3074 ComponentName cn = si.getTargetComponent();
3075 if (cn != null && packageSet.contains(cn.getPackageName())) {
3076 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3077
3078 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003079 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3080 // Auto install icon
3081 PackageManager pm = context.getPackageManager();
3082 ResolveInfo matched = pm.resolveActivity(
3083 new Intent(Intent.ACTION_MAIN)
3084 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3085 PackageManager.MATCH_DEFAULT_ONLY);
3086 if (matched == null) {
3087 // Try to find the best match activity.
3088 Intent intent = pm.getLaunchIntentForPackage(
3089 cn.getPackageName());
3090 if (intent != null) {
3091 cn = intent.getComponent();
3092 appInfo = addedOrUpdatedApps.get(cn);
3093 }
3094
3095 if ((intent == null) || (appInfo == null)) {
3096 removedShortcuts.add(si);
3097 continue;
3098 }
3099 si.promisedIntent = intent;
3100 }
3101 }
3102
3103 // Restore the shortcut.
3104 si.intent = si.promisedIntent;
3105 si.promisedIntent = null;
3106 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3107 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3108 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3109
3110 infoUpdated = true;
3111 si.updateIcon(mIconCache);
3112 }
3113
3114 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3115 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3116 si.updateIcon(mIconCache);
3117 si.title = appInfo.title.toString();
3118 si.contentDescription = appInfo.contentDescription;
3119 infoUpdated = true;
3120 }
3121
3122 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3123 // Since package was just updated, the target must be available now.
3124 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3125 shortcutUpdated = true;
3126 }
3127 }
3128
3129 if (infoUpdated || shortcutUpdated) {
3130 updatedShortcuts.add(si);
3131 }
3132 if (infoUpdated) {
3133 updateItemInDatabase(context, si);
3134 }
3135 } else if (info instanceof LauncherAppWidgetInfo) {
3136 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3137 if (mUser.equals(widgetInfo.user)
3138 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3139 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3140 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3141 widgets.add(widgetInfo);
3142 updateItemInDatabase(context, widgetInfo);
3143 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003144 }
3145 }
3146 }
3147
Sunny Goyal4390ace2014-10-13 11:33:11 -07003148 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3149 mHandler.post(new Runnable() {
3150
3151 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003152 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003153 if (callbacks == cb && cb != null) {
3154 callbacks.bindShortcutsChanged(
3155 updatedShortcuts, removedShortcuts, mUser);
3156 }
3157 }
3158 });
3159 if (!removedShortcuts.isEmpty()) {
3160 deleteItemsFromDatabase(context, removedShortcuts);
3161 }
3162 }
3163 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003164 mHandler.post(new Runnable() {
3165 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003166 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003167 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003168 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003169 }
3170 }
3171 });
3172 }
3173 }
3174
Winson Chungdf95eb12013-10-16 14:57:07 -07003175 final ArrayList<String> removedPackageNames =
3176 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003177 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003178 // Mark all packages in the broadcast to be removed
3179 removedPackageNames.addAll(Arrays.asList(packages));
3180 } else if (mOp == OP_UPDATE) {
3181 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003182 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003183 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003184 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003185 }
3186 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003187 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003188
Winson Chungdf95eb12013-10-16 14:57:07 -07003189 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003190 final int removeReason;
3191 if (mOp == OP_UNAVAILABLE) {
3192 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3193 } else {
3194 // Remove all the components associated with this package
3195 for (String pn : removedPackageNames) {
3196 deletePackageFromDatabase(context, pn, mUser);
3197 }
3198 // Remove all the specific components
3199 for (AppInfo a : removedApps) {
3200 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3201 deleteItemsFromDatabase(context, infos);
3202 }
3203 removeReason = 0;
3204 }
3205
Winson Chungdf95eb12013-10-16 14:57:07 -07003206 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003207 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003208 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003209 mHandler.post(new Runnable() {
3210 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003211 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003212 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003213 callbacks.bindComponentsRemoved(
3214 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003215 }
3216 }
3217 });
Joe Onoratobe386092009-11-17 17:32:16 -08003218 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003219
Michael Jurkac402cd92013-05-20 15:49:32 +02003220 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003221 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003222 mHandler.post(new Runnable() {
3223 @Override
3224 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003225 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003226 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003227 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003228 }
3229 }
3230 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003231
3232 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003233 mHandler.post(new Runnable() {
3234 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003235 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003236 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003237 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003238 }
3239 }
3240 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003241 }
3242 }
3243
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003244 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3245 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003246 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003247 if (sBgWidgetProviders == null || refresh) {
3248 sBgWidgetProviders = new HashMap<>();
3249 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3250 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003251
Robin Lee26ace122015-03-16 19:41:43 +00003252 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3253 for (AppWidgetProviderInfo pInfo : widgets) {
3254 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3255 UserHandleCompat user = wm.getUser(info);
3256 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3257 }
3258
3259 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3260 for (CustomAppWidget widget : customWidgets) {
3261 info = new LauncherAppWidgetProviderInfo(context, widget);
3262 UserHandleCompat user = wm.getUser(info);
3263 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3264 }
Adam Cohen59400422014-03-05 18:07:04 -08003265 }
Adam Cohen59400422014-03-05 18:07:04 -08003266 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3267 }
3268 }
3269
Robin Lee26ace122015-03-16 19:41:43 +00003270 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3271 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003272 synchronized (sBgLock) {
3273 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003274 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003275 }
Robin Lee26ace122015-03-16 19:41:43 +00003276 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003277 }
3278 }
3279
Winson Chungb745afb2015-03-02 11:51:23 -08003280 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003281 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003282 PackageManager packageManager = context.getPackageManager();
3283 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003284 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003285 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3286 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003287 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003288 return widgetsAndShortcuts;
3289 }
3290
Adam Cohen091440a2015-03-18 14:16:05 -07003291 @Thunk static boolean isPackageDisabled(Context context, String packageName,
Kenny Guyed131872014-04-30 03:02:21 +01003292 UserHandleCompat user) {
3293 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3294 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003295 }
Adam Cohen556f6132014-01-15 15:18:08 -08003296
Kenny Guyed131872014-04-30 03:02:21 +01003297 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3298 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003299 if (cn == null) {
3300 return false;
3301 }
Kenny Guyed131872014-04-30 03:02:21 +01003302 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3303 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003304 return false;
3305 }
Kenny Guyed131872014-04-30 03:02:21 +01003306 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003307 }
3308
Adam Cohena28b78e2014-05-20 17:03:04 -07003309 public static boolean isValidPackage(Context context, String packageName,
3310 UserHandleCompat user) {
3311 if (packageName == null) {
3312 return false;
3313 }
3314 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3315 return launcherApps.isPackageEnabledForProfile(packageName, user);
3316 }
3317
Joe Onorato9c1289c2009-08-17 11:03:03 -04003318 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003319 * Make an ShortcutInfo object for a restored application or shortcut item that points
3320 * to a package that is not yet installed on the system.
3321 */
Sunny Goyal34942622014-08-29 17:20:55 -07003322 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003323 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003324 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003325 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003326 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003327
3328 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3329 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3330 if (!TextUtils.isEmpty(title)) {
3331 info.title = title;
3332 }
3333 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3334 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3335 if (TextUtils.isEmpty(info.title)) {
3336 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3337 }
3338 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3339 } else {
3340 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3341 }
3342
Kenny Guyc2bd8102014-06-30 12:30:31 +01003343 info.contentDescription = mUserManager.getBadgedLabelForUser(
3344 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003345 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003346 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003347 return info;
3348 }
3349
3350 /**
3351 * Make an Intent object for a restored application or shortcut item that points
3352 * to the market page for the item.
3353 */
Adam Cohen091440a2015-03-18 14:16:05 -07003354 @Thunk Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003355 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003356 return getMarketIntent(componentName.getPackageName());
3357 }
3358
3359 static Intent getMarketIntent(String packageName) {
3360 return new Intent(Intent.ACTION_VIEW)
3361 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003362 .scheme("market")
3363 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003364 .appendQueryParameter("id", packageName)
3365 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003366 }
3367
3368 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003369 * Make an ShortcutInfo object for a shortcut that is an application.
3370 *
3371 * If c is not null, then it will be used to fill in missing data like the title and icon.
3372 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003373 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003374 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003375 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003376 if (user == null) {
3377 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003378 return null;
3379 }
3380
Kenny Guyed131872014-04-30 03:02:21 +01003381 ComponentName componentName = intent.getComponent();
3382 if (componentName == null) {
3383 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3384 return null;
3385 }
3386
3387 Intent newIntent = new Intent(intent.getAction(), null);
3388 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3389 newIntent.setComponent(componentName);
3390 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003391 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003392 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3393 return null;
3394 }
3395
3396 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003397 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003398 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3399 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3400 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003401 }
3402
Joe Onorato56d82912010-03-07 14:32:10 -05003403 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003404 if (TextUtils.isEmpty(info.title) && c != null) {
3405 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003406 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003407
Joe Onorato56d82912010-03-07 14:32:10 -05003408 // fall back to the class name of the activity
3409 if (info.title == null) {
3410 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003411 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003412
Joe Onorato9c1289c2009-08-17 11:03:03 -04003413 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003414 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003415 info.contentDescription = mUserManager.getBadgedLabelForUser(
3416 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003417 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003418 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003419
Winson Chung64359a52013-07-08 17:17:08 -07003420 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3421 ItemInfoFilter f) {
3422 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3423 for (ItemInfo i : infos) {
3424 if (i instanceof ShortcutInfo) {
3425 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003426 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003427 if (cn != null && f.filterItem(null, info, cn)) {
3428 filtered.add(info);
3429 }
3430 } else if (i instanceof FolderInfo) {
3431 FolderInfo info = (FolderInfo) i;
3432 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003433 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003434 if (cn != null && f.filterItem(info, s, cn)) {
3435 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003436 }
3437 }
Winson Chung64359a52013-07-08 17:17:08 -07003438 } else if (i instanceof LauncherAppWidgetInfo) {
3439 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3440 ComponentName cn = info.providerName;
3441 if (cn != null && f.filterItem(null, info, cn)) {
3442 filtered.add(info);
3443 }
Winson Chung8a435102012-08-30 17:16:53 -07003444 }
3445 }
Winson Chung64359a52013-07-08 17:17:08 -07003446 return new ArrayList<ItemInfo>(filtered);
3447 }
3448
Adam Cohen091440a2015-03-18 14:16:05 -07003449 @Thunk ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
Kenny Guyed131872014-04-30 03:02:21 +01003450 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003451 ItemInfoFilter filter = new ItemInfoFilter() {
3452 @Override
3453 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003454 if (info.user == null) {
3455 return cn.equals(cname);
3456 } else {
3457 return cn.equals(cname) && info.user.equals(user);
3458 }
Winson Chung64359a52013-07-08 17:17:08 -07003459 }
3460 };
3461 return filterItemInfos(sBgItemsIdMap.values(), filter);
3462 }
3463
Sunny Goyal1a745e82014-10-02 15:58:31 -07003464 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003465 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003466 */
Adam Cohen091440a2015-03-18 14:16:05 -07003467 @Thunk ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003468 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3469 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003470
Joe Onorato56d82912010-03-07 14:32:10 -05003471 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003472 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003473 // Non-app shortcuts are only supported for current user.
3474 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003475 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003476
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003477 // TODO: If there's an explicit component and we can't install that, delete it.
3478
Joe Onorato56d82912010-03-07 14:32:10 -05003479 info.title = c.getString(titleIndex);
3480
Joe Onorato9c1289c2009-08-17 11:03:03 -04003481 int iconType = c.getInt(iconTypeIndex);
3482 switch (iconType) {
3483 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3484 String packageName = c.getString(iconPackageIndex);
3485 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003486 info.customIcon = false;
3487 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003488 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003489 // the db
3490 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003491 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003492 }
3493 // the fallback icon
3494 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003495 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003496 info.usingFallbackIcon = true;
3497 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003498 break;
3499 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003500 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003501 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003502 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003503 info.customIcon = false;
3504 info.usingFallbackIcon = true;
3505 } else {
3506 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003507 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003508 break;
3509 default:
Kenny Guyed131872014-04-30 03:02:21 +01003510 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003511 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003512 info.customIcon = false;
3513 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003514 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003515 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003516 return info;
3517 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003518
Sunny Goyal2350bc92014-10-14 16:42:54 -07003519 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003520 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3521 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3522 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3523
Adam Cohend9198822011-11-22 16:42:47 -08003524 if (intent == null) {
3525 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3526 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3527 return null;
3528 }
3529
Joe Onorato0589f0f2010-02-08 13:44:00 -08003530 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003531 boolean customIcon = false;
3532 ShortcutIconResource iconResource = null;
3533
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003534 if (bitmap instanceof Bitmap) {
3535 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003536 customIcon = true;
3537 } else {
3538 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003539 if (extra instanceof ShortcutIconResource) {
3540 iconResource = (ShortcutIconResource) extra;
3541 icon = Utilities.createIconBitmap(iconResource.packageName,
3542 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003543 }
3544 }
3545
Michael Jurkac9d95c52011-08-29 14:03:34 -07003546 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003547
Kenny Guyed131872014-04-30 03:02:21 +01003548 // Only support intents for current user for now. Intents sent from other
3549 // users wouldn't get here without intent forwarding anyway.
3550 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003551 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003552 icon = mIconCache.getDefaultIcon(info.user);
3553 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003554 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003555 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003556
Joe Onorato0589f0f2010-02-08 13:44:00 -08003557 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003558 info.contentDescription = mUserManager.getBadgedLabelForUser(
3559 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003560 info.intent = intent;
3561 info.customIcon = customIcon;
3562 info.iconResource = iconResource;
3563
3564 return info;
3565 }
3566
Joe Onorato9c1289c2009-08-17 11:03:03 -04003567 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003568 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003569 * or make a new one.
3570 */
Adam Cohen091440a2015-03-18 14:16:05 -07003571 @Thunk static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003572 // See if a placeholder was created for us already
3573 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003574 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003575 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003576 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003577 folders.put(id, folderInfo);
3578 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003579 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003580 }
3581
Winson Chung1ed747a2011-05-03 16:18:34 -07003582 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003583 private final AppWidgetManagerCompat mManager;
3584 private final PackageManager mPackageManager;
3585 private final HashMap<Object, String> mLabelCache;
3586 private final Collator mCollator;
3587
Hyunyoung Song3f471442015-04-08 19:01:34 -07003588 public WidgetAndShortcutNameComparator(Context context) {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003589 mManager = AppWidgetManagerCompat.getInstance(context);
3590 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003591 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003592 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003593 }
3594 public final int compare(Object a, Object b) {
3595 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003596 if (mLabelCache.containsKey(a)) {
3597 labelA = mLabelCache.get(a);
3598 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003599 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3600 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003601 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003602 mLabelCache.put(a, labelA);
3603 }
3604 if (mLabelCache.containsKey(b)) {
3605 labelB = mLabelCache.get(b);
3606 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003607 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c1652015-01-30 10:28:23 -08003608 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003609 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003610 mLabelCache.put(b, labelB);
3611 }
Winson Chung11904872012-09-17 16:58:46 -07003612 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003613 }
3614 };
Joe Onoratobe386092009-11-17 17:32:16 -08003615
Sunny Goyal651077b2014-06-30 14:15:31 -07003616 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3617 return (provider != null) && (provider.provider != null)
3618 && (provider.provider.getPackageName() != null);
3619 }
3620
Joe Onoratobe386092009-11-17 17:32:16 -08003621 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003622 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003623 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3624 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3625 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3626 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003627 if (mLoaderTask != null) {
3628 mLoaderTask.dumpState();
3629 } else {
3630 Log.d(TAG, "mLoaderTask=null");
3631 }
Joe Onoratobe386092009-11-17 17:32:16 -08003632 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003633
3634 public Callbacks getCallback() {
3635 return mCallbacks != null ? mCallbacks.get() : null;
3636 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07003637
3638 /**
3639 * @return {@link FolderInfo} if its already loaded.
3640 */
3641 public FolderInfo findFolderById(Long folderId) {
3642 synchronized (sBgLock) {
3643 return sBgFolders.get(folderId);
3644 }
3645 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003646}