blob: 135930146cdc137573839749ceafaba582cbca77 [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;
Romain Guyedcce092010-03-04 13:03:17 -080062
Michael Jurkac2f801e2011-07-12 14:19:46 -070063import java.lang.ref.WeakReference;
64import java.net.URISyntaxException;
Sunny Goyal34942622014-08-29 17:20:55 -070065import java.security.InvalidParameterException;
Michael Jurkac2f801e2011-07-12 14:19:46 -070066import java.text.Collator;
67import java.util.ArrayList;
Adam Cohendcd297f2013-06-18 13:13:40 -070068import java.util.Arrays;
Winson Chung64359a52013-07-08 17:17:08 -070069import java.util.Collection;
Michael Jurkac2f801e2011-07-12 14:19:46 -070070import java.util.Collections;
71import java.util.Comparator;
72import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070073import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070074import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070075import java.util.List;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070076import java.util.Map.Entry;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070077import java.util.Set;
Michael Jurkac2f801e2011-07-12 14:19:46 -070078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079/**
80 * Maintains in-memory state of the Launcher. It is expected that there should be only one
81 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070082 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 */
Kenny Guyed131872014-04-30 03:02:21 +010084public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +010085 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080086 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -040087 private static final boolean DEBUG_RECEIVER = false;
Sunny Goyal94485362014-09-18 16:13:58 -070088 private static final boolean REMOVE_UNRESTORED_ICONS = true;
Sunny Goyal2a66bbf2014-11-20 17:01:00 -080089 private static final boolean ADD_MANAGED_PROFILE_SHORTCUTS = false;
Chris Wrenb358f812014-04-16 13:37:00 -040090
Joe Onorato9c1289c2009-08-17 11:03:03 -040091 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070092
Dan Sandlerd5024042014-01-09 15:01:33 -050093 public static final int LOADER_FLAG_NONE = 0;
94 public static final int LOADER_FLAG_CLEAR_WORKSPACE = 1 << 0;
95 public static final int LOADER_FLAG_MIGRATE_SHORTCUTS = 1 << 1;
96
Joe Onorato36115782010-06-17 13:28:48 -040097 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -050098 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -080099
Winson Chungee055712013-07-30 14:46:24 -0700100 private final boolean mAppsCanBeOnRemoveableStorage;
Winson Chunga6945242014-01-08 14:04:34 -0800101 private final boolean mOldContentProviderExists;
Daniel Sandlerdca66122010-04-13 16:23:58 -0400102
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400103 private final LauncherAppState mApp;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400104 private final Object mLock = new Object();
105 private DeferredHandler mHandler = new DeferredHandler();
Joe Onorato36115782010-06-17 13:28:48 -0400106 private LoaderTask mLoaderTask;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700107 private boolean mIsLoaderTaskRunning;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108
Sunny Goyale0f58d72014-11-10 18:05:31 -0800109 /**
110 * Maintain a set of packages per user, for which we added a shortcut on the workspace.
111 */
112 private static final String INSTALLED_SHORTCUTS_SET_PREFIX = "installed_shortcuts_set_for_user_";
113
Winson Chung81b52252012-08-27 15:34:29 -0700114 // Specific runnable types that are run on the main thread deferred handler, this allows us to
115 // clear all queued binding runnables when the Launcher activity is destroyed.
116 private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
117 private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
118
Jason Monkbbe1e242014-05-16 17:37:34 -0400119 private static final String MIGRATE_AUTHORITY = "com.android.launcher2.settings";
Winson Chung81b52252012-08-27 15:34:29 -0700120
Sunny Goyal34b65272015-03-11 16:56:52 -0700121 static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700122 static {
123 sWorkerThread.start();
124 }
125 private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
126
Joe Onoratocc67f472010-06-08 10:54:30 -0700127 // We start off with everything not loaded. After that, we assume that
128 // our monitoring of the package manager provides all updates and we never
129 // need to do a requery. These are only ever touched from the loader thread.
130 private boolean mWorkspaceLoaded;
131 private boolean mAllAppsLoaded;
132
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700133 // When we are loading pages synchronously, we can't just post the binding of items on the side
134 // pages as this delays the rotation process. Instead, we wait for a callback from the first
135 // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
136 // a normal load, we also clear this set of Runnables.
137 static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
138
Joe Onorato9c1289c2009-08-17 11:03:03 -0400139 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700141 // < only access in worker thread >
Adam Cohen4caf2982013-08-20 18:54:31 -0700142 AllAppsList mBgAllAppsList;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800143
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700144 // The lock that must be acquired before referencing any static bg data structures. Unlike
145 // other locks, this one can generally be held long-term because we never expect any of these
146 // static data structures to be referenced outside of the worker thread except on the first
147 // load after configuration change.
Winson Chung2abf94d2012-07-18 18:16:38 -0700148 static final Object sBgLock = new Object();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700149
Adam Cohen487f7dd2012-06-28 18:12:10 -0700150 // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700151 // LauncherModel to their ids
Adam Cohen487f7dd2012-06-28 18:12:10 -0700152 static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700153
Adam Cohen487f7dd2012-06-28 18:12:10 -0700154 // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
155 // created by LauncherModel that are directly on the home screen (however, no widgets or
156 // shortcuts within folders).
157 static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700158
Adam Cohen487f7dd2012-06-28 18:12:10 -0700159 // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
160 static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700161 new ArrayList<LauncherAppWidgetInfo>();
162
Adam Cohen487f7dd2012-06-28 18:12:10 -0700163 // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
164 static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
Winson Chungb1094bd2011-08-24 16:14:08 -0700165
Adam Cohendcd297f2013-06-18 13:13:40 -0700166 // sBgWorkspaceScreens is the ordered set of workspace screens.
167 static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
168
Adam Cohen59400422014-03-05 18:07:04 -0800169 // sBgWidgetProviders is the set of widget providers including custom internal widgets
Robin Lee26ace122015-03-16 19:41:43 +0000170 public static HashMap<ComponentKey, LauncherAppWidgetProviderInfo> sBgWidgetProviders;
Adam Cohen59400422014-03-05 18:07:04 -0800171
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700172 // sPendingPackages is a set of packages which could be on sdcard and are not available yet
Sameer Padala513edae2014-07-29 16:17:08 -0700173 static final HashMap<UserHandleCompat, HashSet<String>> sPendingPackages =
174 new HashMap<UserHandleCompat, HashSet<String>>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700175
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700176 // </ only access in worker thread >
177
178 private IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179
Reena Lee99a73f32011-10-24 17:27:37 -0700180 protected int mPreviousConfigMcc;
Reena Lee93f824a2011-09-23 17:20:28 -0700181
Kenny Guyed131872014-04-30 03:02:21 +0100182 private final LauncherAppsCompat mLauncherApps;
183 private final UserManagerCompat mUserManager;
184
Joe Onorato9c1289c2009-08-17 11:03:03 -0400185 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700186 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400187 public int getCurrentWorkspaceScreen();
188 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700189 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
190 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700191 public void bindScreens(ArrayList<Long> orderedScreenIds);
Winson Chung64359a52013-07-08 17:17:08 -0700192 public void bindAddScreens(ArrayList<Long> orderedScreenIds);
Joe Onoratoad72e172009-11-06 16:25:04 -0500193 public void bindFolders(HashMap<Long,FolderInfo> folders);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800194 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400195 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200196 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700197 public void bindAppsAdded(ArrayList<Long> newScreens,
198 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700199 ArrayList<ItemInfo> addAnimated,
200 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200201 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700202 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
203 ArrayList<ShortcutInfo> removed, UserHandleCompat user);
204 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyale755d462014-07-22 13:48:29 -0700205 public void updatePackageState(ArrayList<PackageInstallInfo> installInfo);
Sunny Goyala22666f2014-09-18 13:25:15 -0700206 public void updatePackageBadge(String packageName);
Winson Chung83892cc2013-05-01 16:53:33 -0700207 public void bindComponentsRemoved(ArrayList<String> packageNames,
Sunny Goyal1a745e82014-10-02 15:58:31 -0700208 ArrayList<AppInfo> appInfos, UserHandleCompat user, int reason);
Michael Jurkac402cd92013-05-20 15:49:32 +0200209 public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100210 public void bindSearchablesChanged();
Winson Chunga0b7e862013-09-05 16:03:15 -0700211 public boolean isAllAppsButtonRank(int rank);
Adam Cohen1462de32012-07-24 22:34:36 -0700212 public void onPageBoundSynchronously(int page);
Winson Chungede41292013-09-19 16:27:36 -0700213 public void dumpLogsToLocalData();
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800214 public void bindAddPendingItem(PendingAddItemInfo info, long container, long screenId,
215 int[] cell, int spanX, int spanY);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400216 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217
Winson Chung64359a52013-07-08 17:17:08 -0700218 public interface ItemInfoFilter {
219 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
220 }
221
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800222 public interface ScreenPosProvider {
223 int getScreenIndex(ArrayList<Long> screenIDs);
224 }
225
Bjorn Bringert1307f632013-10-03 22:31:03 +0100226 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800227 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400228
Winson Chungee055712013-07-30 14:46:24 -0700229 mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
Adam Cohen71483f42014-05-15 14:04:01 -0700230 String oldProvider = context.getString(R.string.old_launcher_provider_uri);
Jason Monkbbe1e242014-05-16 17:37:34 -0400231 // This may be the same as MIGRATE_AUTHORITY, or it may be replaced by a different
232 // resource string.
233 String redirectAuthority = Uri.parse(oldProvider).getAuthority();
234 ProviderInfo providerInfo =
235 context.getPackageManager().resolveContentProvider(MIGRATE_AUTHORITY, 0);
236 ProviderInfo redirectProvider =
237 context.getPackageManager().resolveContentProvider(redirectAuthority, 0);
Adam Cohen71483f42014-05-15 14:04:01 -0700238
239 Log.d(TAG, "Old launcher provider: " + oldProvider);
Jason Monkbbe1e242014-05-16 17:37:34 -0400240 mOldContentProviderExists = (providerInfo != null) && (redirectProvider != null);
Adam Cohen71483f42014-05-15 14:04:01 -0700241
242 if (mOldContentProviderExists) {
243 Log.d(TAG, "Old launcher provider exists.");
244 } else {
245 Log.d(TAG, "Old launcher provider does not exist.");
246 }
247
Daniel Sandlere4f98912013-06-25 15:13:26 -0400248 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100249 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800250 mIconCache = iconCache;
251
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400252 final Resources res = context.getResources();
Reena Lee99a73f32011-10-24 17:27:37 -0700253 Configuration config = res.getConfiguration();
254 mPreviousConfigMcc = config.mcc;
Kenny Guyed131872014-04-30 03:02:21 +0100255 mLauncherApps = LauncherAppsCompat.getInstance(context);
256 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800257 }
258
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700259 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
260 * posted on the main thread handler. */
261 private void runOnMainThread(Runnable r) {
Winson Chung81b52252012-08-27 15:34:29 -0700262 runOnMainThread(r, 0);
263 }
264 private void runOnMainThread(Runnable r, int type) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700265 if (sWorkerThread.getThreadId() == Process.myTid()) {
266 // If we are on the worker thread, post onto the main handler
267 mHandler.post(r);
268 } else {
269 r.run();
270 }
271 }
272
273 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
274 * posted on the worker thread handler. */
275 private static void runOnWorkerThread(Runnable r) {
276 if (sWorkerThread.getThreadId() == Process.myTid()) {
277 r.run();
278 } else {
279 // If we are not on the worker thread, then post to the worker handler
280 sWorker.post(r);
281 }
282 }
283
Winson Chunge43a1e72014-01-15 10:33:02 -0800284 boolean canMigrateFromOldLauncherDb(Launcher launcher) {
285 return mOldContentProviderExists && !launcher.isLauncherPreinstalled() ;
Winson Chunga6945242014-01-08 14:04:34 -0800286 }
287
Sunny Goyale755d462014-07-22 13:48:29 -0700288 public void setPackageState(final ArrayList<PackageInstallInfo> installInfo) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500289 // Process the updated package state
290 Runnable r = new Runnable() {
291 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800292 Callbacks callbacks = getCallback();
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500293 if (callbacks != null) {
Sunny Goyale755d462014-07-22 13:48:29 -0700294 callbacks.updatePackageState(installInfo);
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500295 }
296 }
297 };
298 mHandler.post(r);
299 }
300
Sunny Goyala22666f2014-09-18 13:25:15 -0700301 public void updatePackageBadge(final String packageName) {
302 // Process the updated package badge
303 Runnable r = new Runnable() {
304 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800305 Callbacks callbacks = getCallback();
Sunny Goyala22666f2014-09-18 13:25:15 -0700306 if (callbacks != null) {
307 callbacks.updatePackageBadge(packageName);
308 }
309 }
310 };
311 mHandler.post(r);
312 }
313
Adam Cohen76a47a12014-02-05 11:47:43 -0800314 public void addAppsToAllApps(final Context ctx, final ArrayList<AppInfo> allAppsApps) {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800315 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800316
317 if (allAppsApps == null) {
318 throw new RuntimeException("allAppsApps must not be null");
319 }
320 if (allAppsApps.isEmpty()) {
321 return;
322 }
323
324 // Process the newly added applications and add them to the database first
325 Runnable r = new Runnable() {
326 public void run() {
327 runOnMainThread(new Runnable() {
328 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800329 Callbacks cb = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800330 if (callbacks == cb && cb != null) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500331 callbacks.bindAppsAdded(null, null, null, allAppsApps);
Adam Cohen76a47a12014-02-05 11:47:43 -0800332 }
333 }
334 });
335 }
336 };
337 runOnWorkerThread(r);
Winson Chung997a9232013-07-24 15:33:46 -0700338 }
Adam Cohen76a47a12014-02-05 11:47:43 -0800339
340 public void addAndBindAddedWorkspaceApps(final Context context,
341 final ArrayList<ItemInfo> workspaceApps) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800342 addAndBindAddedWorkspaceApps(context, workspaceApps,
343 new ScreenPosProvider() {
Adam Cohen76a47a12014-02-05 11:47:43 -0800344
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800345 @Override
346 public int getScreenIndex(ArrayList<Long> screenIDs) {
347 return screenIDs.isEmpty() ? 0 : 1;
348 }
349 }, 1, false);
350 }
351
352 private static boolean findNextAvailableIconSpaceInScreen(ArrayList<Rect> occupiedPos,
353 int[] xy, int spanX, int spanY) {
354 LauncherAppState app = LauncherAppState.getInstance();
355 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
356 final int xCount = (int) grid.numColumns;
357 final int yCount = (int) grid.numRows;
358 boolean[][] occupied = new boolean[xCount][yCount];
359 if (occupiedPos != null) {
360 for (Rect r : occupiedPos) {
361 for (int x = r.left; 0 <= x && x < r.right && x < xCount; x++) {
362 for (int y = r.top; 0 <= y && y < r.bottom && y < yCount; y++) {
363 occupied[x][y] = true;
364 }
365 }
366 }
Winson Chungfe9d96a2013-11-14 11:30:05 -0800367 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800368 return CellLayout.findVacantCell(xy, spanX, spanY, xCount, yCount, occupied);
369 }
370
371 /**
372 * Find a position on the screen for the given size or adds a new screen.
373 * @return screenId and the coordinates for the item.
374 */
375 private static Pair<Long, int[]> findSpaceForItem(
376 Context context,
377 ScreenPosProvider preferredScreen,
378 int fallbackStartScreen,
379 ArrayList<Long> workspaceScreens,
380 ArrayList<Long> addedWorkspaceScreensFinal,
381 int spanX, int spanY) {
382 // Load position of items which are on the desktop. We can't use sBgItemsIdMap because
383 // loadWorkspace() may not have been called.
384 final ContentResolver cr = context.getContentResolver();
385 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
386 new String[] {
387 LauncherSettings.Favorites.SCREEN,
388 LauncherSettings.Favorites.CELLX,
389 LauncherSettings.Favorites.CELLY,
390 LauncherSettings.Favorites.SPANX,
391 LauncherSettings.Favorites.SPANY,
392 LauncherSettings.Favorites.CONTAINER
393 },
394 "container=?",
395 new String[] { Integer.toString(LauncherSettings.Favorites.CONTAINER_DESKTOP) },
396 null);
397
398 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
399 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
400 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
401 final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
402 final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
403 LongSparseArray<ArrayList<Rect>> screenItems = new LongSparseArray<ArrayList<Rect>>();
404 try {
405 while (c.moveToNext()) {
406 Rect rect = new Rect();
407 rect.left = c.getInt(cellXIndex);
408 rect.top = c.getInt(cellYIndex);
409 rect.right = rect.left + Math.max(1, c.getInt(spanXIndex));
410 rect.bottom = rect.top + Math.max(1, c.getInt(spanYIndex));
411
412 long screenId = c.getInt(screenIndex);
413 ArrayList<Rect> items = screenItems.get(screenId);
414 if (items == null) {
415 items = new ArrayList<Rect>();
416 screenItems.put(screenId, items);
417 }
418 items.add(rect);
419 }
420 } catch (Exception e) {
421 screenItems.clear();
422 } finally {
423 c.close();
424 }
425
426 // Find appropriate space for the item.
427 long screenId = 0;
428 int[] cordinates = new int[2];
429 boolean found = false;
430
431 int screenCount = workspaceScreens.size();
432 // First check the preferred screen.
433 int preferredScreenIndex = preferredScreen.getScreenIndex(workspaceScreens);
434 if (preferredScreenIndex < screenCount) {
435 screenId = workspaceScreens.get(preferredScreenIndex);
436 found = findNextAvailableIconSpaceInScreen(
437 screenItems.get(screenId), cordinates, spanX, spanY);
438 }
439
440 if (!found) {
441 // Search on any of the screens.
442 for (int screen = fallbackStartScreen; screen < screenCount; screen++) {
443 screenId = workspaceScreens.get(screen);
444 if (findNextAvailableIconSpaceInScreen(
445 screenItems.get(screenId), cordinates, spanX, spanY)) {
446 // We found a space for it
447 found = true;
448 break;
449 }
450 }
451 }
452
453 if (!found) {
454 // Still no position found. Add a new screen to the end.
455 screenId = LauncherAppState.getLauncherProvider().generateNewScreenId();
456
457 // Save the screen id for binding in the workspace
458 workspaceScreens.add(screenId);
459 addedWorkspaceScreensFinal.add(screenId);
460
461 // If we still can't find an empty space, then God help us all!!!
462 if (!findNextAvailableIconSpaceInScreen(
463 screenItems.get(screenId), cordinates, spanX, spanY)) {
464 throw new RuntimeException("Can't find space to add the item");
465 }
466 }
467 return Pair.create(screenId, cordinates);
468 }
469
470 /**
471 * Adds the provided items to the workspace.
472 * @param preferredScreen the screen where we should try to add the app first
473 * @param fallbackStartScreen the screen to start search for empty space if
474 * preferredScreen is not available.
475 */
476 public void addAndBindPendingItem(
477 final Context context,
478 final PendingAddItemInfo addInfo,
479 final ScreenPosProvider preferredScreen,
480 final int fallbackStartScreen) {
481 final Callbacks callbacks = getCallback();
482 // Process the newly added applications and add them to the database first
483 Runnable r = new Runnable() {
484 public void run() {
485 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800486 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800487
488 // Find appropriate space for the item.
489 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
490 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
491 addInfo.spanX,
492 addInfo.spanY);
493 final long screenId = coords.first;
494 final int[] cordinates = coords.second;
495
496 // Update the workspace screens
497 updateWorkspaceScreenOrder(context, workspaceScreens);
498 runOnMainThread(new Runnable() {
499 public void run() {
500 Callbacks cb = getCallback();
501 if (callbacks == cb && cb != null) {
502 cb.bindAddScreens(addedWorkspaceScreensFinal);
503 cb.bindAddPendingItem(addInfo,
504 LauncherSettings.Favorites.CONTAINER_DESKTOP,
505 screenId, cordinates, addInfo.spanX, addInfo.spanY);
506 }
507 }
508 });
509 }
510 };
511 runOnWorkerThread(r);
512 }
513
514 /**
515 * Adds the provided items to the workspace.
516 * @param preferredScreen the screen where we should try to add the app first
517 * @param fallbackStartScreen the screen to start search for empty space if
518 * preferredScreen is not available.
519 */
520 public void addAndBindAddedWorkspaceApps(final Context context,
521 final ArrayList<ItemInfo> workspaceApps,
522 final ScreenPosProvider preferredScreen,
523 final int fallbackStartScreen,
524 final boolean allowDuplicate) {
525 final Callbacks callbacks = getCallback();
Adam Cohen76a47a12014-02-05 11:47:43 -0800526 if (workspaceApps.isEmpty()) {
Winson Chung9e6a0a22013-08-27 11:58:12 -0700527 return;
Winson Chung997a9232013-07-24 15:33:46 -0700528 }
Winson Chung64359a52013-07-08 17:17:08 -0700529 // Process the newly added applications and add them to the database first
530 Runnable r = new Runnable() {
531 public void run() {
532 final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
533 final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
534
Winson Chung76828c82013-08-19 15:43:29 -0700535 // Get the list of workspace screens. We need to append to this list and
536 // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
537 // called.
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800538 ArrayList<Long> workspaceScreens = loadWorkspaceScreensDb(context);
Winson Chung64359a52013-07-08 17:17:08 -0700539 synchronized(sBgLock) {
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800540 for (ItemInfo item : workspaceApps) {
541 if (!allowDuplicate) {
542 // Short-circuit this logic if the icon exists somewhere on the workspace
543 if (shortcutExists(context, item.title.toString(),
544 item.getIntent(), item.user)) {
545 continue;
Winson Chungc763c4e2013-07-19 13:49:06 -0700546 }
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800547 }
Winson Chung76828c82013-08-19 15:43:29 -0700548
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800549 // Find appropriate space for the item.
550 Pair<Long, int[]> coords = findSpaceForItem(context, preferredScreen,
551 fallbackStartScreen, workspaceScreens, addedWorkspaceScreensFinal,
552 1, 1);
553 long screenId = coords.first;
554 int[] cordinates = coords.second;
Winson Chung64359a52013-07-08 17:17:08 -0700555
Winson Chung997a9232013-07-24 15:33:46 -0700556 ShortcutInfo shortcutInfo;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800557 if (item instanceof ShortcutInfo) {
558 shortcutInfo = (ShortcutInfo) item;
559 } else if (item instanceof AppInfo) {
560 shortcutInfo = ((AppInfo) item).makeShortcut();
Winson Chung997a9232013-07-24 15:33:46 -0700561 } else {
562 throw new RuntimeException("Unexpected info type");
563 }
Winson Chung94d67682013-09-25 16:29:40 -0700564
Winson Chung64359a52013-07-08 17:17:08 -0700565 // Add the shortcut to the db
566 addItemToDatabase(context, shortcutInfo,
567 LauncherSettings.Favorites.CONTAINER_DESKTOP,
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800568 screenId, cordinates[0], cordinates[1], false);
Winson Chung64359a52013-07-08 17:17:08 -0700569 // Save the ShortcutInfo for binding in the workspace
570 addedShortcutsFinal.add(shortcutInfo);
571 }
572 }
573
Winson Chung76828c82013-08-19 15:43:29 -0700574 // Update the workspace screens
575 updateWorkspaceScreenOrder(context, workspaceScreens);
576
Adam Cohen76a47a12014-02-05 11:47:43 -0800577 if (!addedShortcutsFinal.isEmpty()) {
Winson Chung997a9232013-07-24 15:33:46 -0700578 runOnMainThread(new Runnable() {
579 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800580 Callbacks cb = getCallback();
Winson Chung997a9232013-07-24 15:33:46 -0700581 if (callbacks == cb && cb != null) {
Winson Chung997a9232013-07-24 15:33:46 -0700582 final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
583 final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
Winson Chung94d67682013-09-25 16:29:40 -0700584 if (!addedShortcutsFinal.isEmpty()) {
585 ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
586 long lastScreenId = info.screenId;
587 for (ItemInfo i : addedShortcutsFinal) {
588 if (i.screenId == lastScreenId) {
589 addAnimated.add(i);
590 } else {
591 addNotAnimated.add(i);
592 }
Winson Chung997a9232013-07-24 15:33:46 -0700593 }
594 }
Winson Chungd64d1762013-08-20 14:37:16 -0700595 callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
Adam Cohen76a47a12014-02-05 11:47:43 -0800596 addNotAnimated, addAnimated, null);
Winson Chung997a9232013-07-24 15:33:46 -0700597 }
Winson Chung64359a52013-07-08 17:17:08 -0700598 }
Winson Chung997a9232013-07-24 15:33:46 -0700599 });
600 }
Winson Chung64359a52013-07-08 17:17:08 -0700601 }
602 };
603 runOnWorkerThread(r);
604 }
605
Winson Chung81b52252012-08-27 15:34:29 -0700606 public void unbindItemInfosAndClearQueuedBindRunnables() {
607 if (sWorkerThread.getThreadId() == Process.myTid()) {
608 throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
609 "main thread");
610 }
611
612 // Clear any deferred bind runnables
Jason Monka0a7a742014-04-22 09:23:19 -0400613 synchronized (mDeferredBindRunnables) {
614 mDeferredBindRunnables.clear();
615 }
Winson Chung81b52252012-08-27 15:34:29 -0700616 // Remove any queued bind runnables
617 mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
618 // Unbind all the workspace items
619 unbindWorkspaceItemsOnMainThread();
Winson Chung603bcb92011-09-02 11:45:39 -0700620 }
621
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700622 /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
Winson Chung81b52252012-08-27 15:34:29 -0700623 void unbindWorkspaceItemsOnMainThread() {
Winson Chung603bcb92011-09-02 11:45:39 -0700624 // Ensure that we don't use the same workspace items data structure on the main thread
625 // by making a copy of workspace items first.
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700626 final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
627 final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
Winson Chung2abf94d2012-07-18 18:16:38 -0700628 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700629 tmpWorkspaceItems.addAll(sBgWorkspaceItems);
630 tmpAppWidgets.addAll(sBgAppWidgets);
631 }
632 Runnable r = new Runnable() {
633 @Override
634 public void run() {
635 for (ItemInfo item : tmpWorkspaceItems) {
636 item.unbind();
637 }
638 for (ItemInfo item : tmpAppWidgets) {
639 item.unbind();
640 }
641 }
642 };
643 runOnMainThread(r);
Adam Cohen4eac29a2011-07-11 17:53:37 -0700644 }
645
Joe Onorato9c1289c2009-08-17 11:03:03 -0400646 /**
647 * Adds an item to the DB if it was not created previously, or move it to a new
648 * <container, screen, cellX, cellY>
649 */
650 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700651 long screenId, int cellX, int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400652 if (item.container == ItemInfo.NO_ID) {
653 // From all apps
Adam Cohendcd297f2013-06-18 13:13:40 -0700654 addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400655 } else {
656 // From somewhere else
Adam Cohendcd297f2013-06-18 13:13:40 -0700657 moveItemInDatabase(context, item, container, screenId, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 }
659 }
660
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700661 static void checkItemInfoLocked(
662 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
663 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
664 if (modelItem != null && item != modelItem) {
665 // check all the data is consistent
666 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
667 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
668 ShortcutInfo shortcut = (ShortcutInfo) item;
669 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
670 modelShortcut.intent.filterEquals(shortcut.intent) &&
671 modelShortcut.id == shortcut.id &&
672 modelShortcut.itemType == shortcut.itemType &&
673 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700674 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700675 modelShortcut.cellX == shortcut.cellX &&
676 modelShortcut.cellY == shortcut.cellY &&
677 modelShortcut.spanX == shortcut.spanX &&
678 modelShortcut.spanY == shortcut.spanY &&
679 ((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
680 (modelShortcut.dropPos != null &&
681 shortcut.dropPos != null &&
682 modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
683 modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
684 // For all intents and purposes, this is the same object
685 return;
686 }
687 }
688
689 // the modelItem needs to match up perfectly with item if our model is
690 // to be consistent with the database-- for now, just require
691 // modelItem == item or the equality check above
692 String msg = "item: " + ((item != null) ? item.toString() : "null") +
693 "modelItem: " +
694 ((modelItem != null) ? modelItem.toString() : "null") +
695 "Error: ItemInfo passed to checkItemInfo doesn't match original";
696 RuntimeException e = new RuntimeException(msg);
697 if (stackTrace != null) {
698 e.setStackTrace(stackTrace);
699 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800700 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700701 }
702 }
703
Michael Jurka816474f2012-06-25 14:49:02 -0700704 static void checkItemInfo(final ItemInfo item) {
705 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
706 final long itemId = item.id;
707 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700708 public void run() {
709 synchronized (sBgLock) {
710 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700711 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700712 }
713 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700714 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700715 }
716
Michael Jurkac9d95c52011-08-29 14:03:34 -0700717 static void updateItemInDatabaseHelper(Context context, final ContentValues values,
718 final ItemInfo item, final String callingFunction) {
719 final long itemId = item.id;
720 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
721 final ContentResolver cr = context.getContentResolver();
722
Adam Cohen487f7dd2012-06-28 18:12:10 -0700723 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700724 Runnable r = new Runnable() {
725 public void run() {
726 cr.update(uri, values, null, null);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700727 updateItemArrays(item, itemId, stackTrace);
728 }
729 };
730 runOnWorkerThread(r);
731 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700732
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700733 static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
734 final ArrayList<ItemInfo> items, final String callingFunction) {
735 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -0700736
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700737 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
738 Runnable r = new Runnable() {
739 public void run() {
740 ArrayList<ContentProviderOperation> ops =
741 new ArrayList<ContentProviderOperation>();
742 int count = items.size();
743 for (int i = 0; i < count; i++) {
744 ItemInfo item = items.get(i);
745 final long itemId = item.id;
746 final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
747 ContentValues values = valuesList.get(i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700748
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700749 ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
750 updateItemArrays(item, itemId, stackTrace);
751
752 }
753 try {
754 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
755 } catch (Exception e) {
756 e.printStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -0700757 }
758 }
759 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700760 runOnWorkerThread(r);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700761 }
Adam Cohenbebf0422012-04-11 18:06:28 -0700762
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700763 static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
764 // Lock on mBgLock *after* the db operation
765 synchronized (sBgLock) {
766 checkItemInfoLocked(itemId, item, stackTrace);
767
768 if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
769 item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
770 // Item is in a folder, make sure this folder exists
771 if (!sBgFolders.containsKey(item.container)) {
772 // An items container is being set to a that of an item which is not in
773 // the list of Folders.
774 String msg = "item: " + item + " container being set to: " +
775 item.container + ", not in the list of folders";
776 Log.e(TAG, msg);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700777 }
778 }
779
780 // Items are added/removed from the corresponding FolderInfo elsewhere, such
781 // as in Workspace.onDrop. Here, we just add/remove them from the list of items
782 // that are on the desktop, as appropriate
783 ItemInfo modelItem = sBgItemsIdMap.get(itemId);
Winson Chung33231f52013-12-09 16:57:45 -0800784 if (modelItem != null &&
785 (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
786 modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700787 switch (modelItem.itemType) {
788 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
789 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
790 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
791 if (!sBgWorkspaceItems.contains(modelItem)) {
792 sBgWorkspaceItems.add(modelItem);
793 }
794 break;
795 default:
796 break;
797 }
798 } else {
799 sBgWorkspaceItems.remove(modelItem);
800 }
801 }
802 }
803
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800804 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400805 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700806 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700807 static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700808 final long screenId, final int cellX, final int cellY) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400809 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400810 item.cellX = cellX;
811 item.cellY = cellY;
Michael Jurkac9d95c52011-08-29 14:03:34 -0700812
Winson Chung3d503fb2011-07-13 17:25:49 -0700813 // We store hotseat items in canonical form which is this orientation invariant position
814 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -0700816 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700817 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -0700818 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700819 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -0700820 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400821
822 final ContentValues values = new ContentValues();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400823 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Winson Chung3d503fb2011-07-13 17:25:49 -0700824 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
825 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800826 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700827 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400828
Michael Jurkac9d95c52011-08-29 14:03:34 -0700829 updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700830 }
831
832 /**
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700833 * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
834 * cellX, cellY have already been updated on the ItemInfos.
835 */
836 static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
837 final long container, final int screen) {
838
839 ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
840 int count = items.size();
841
842 for (int i = 0; i < count; i++) {
843 ItemInfo item = items.get(i);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700844 item.container = container;
845
846 // We store hotseat items in canonical form which is this orientation invariant position
847 // in the hotseat
848 if (context instanceof Launcher && screen < 0 &&
849 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700850 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700851 item.cellY);
852 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700853 item.screenId = screen;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700854 }
855
856 final ContentValues values = new ContentValues();
857 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
858 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
859 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800860 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohendcd297f2013-06-18 13:13:40 -0700861 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700862
863 contentValues.add(values);
864 }
865 updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
866 }
867
868 /**
Adam Cohenbebf0422012-04-11 18:06:28 -0700869 * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
Adam Cohend4844c32011-02-18 19:25:06 -0800870 */
Adam Cohenbebf0422012-04-11 18:06:28 -0700871 static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700872 final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
Winson Chung0f84a602013-09-30 14:30:58 -0700873 item.container = container;
Adam Cohend4844c32011-02-18 19:25:06 -0800874 item.cellX = cellX;
875 item.cellY = cellY;
Adam Cohenbebf0422012-04-11 18:06:28 -0700876 item.spanX = spanX;
877 item.spanY = spanY;
878
879 // We store hotseat items in canonical form which is this orientation invariant position
880 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -0700881 if (context instanceof Launcher && screenId < 0 &&
Adam Cohenbebf0422012-04-11 18:06:28 -0700882 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700883 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Adam Cohenbebf0422012-04-11 18:06:28 -0700884 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -0700885 item.screenId = screenId;
Adam Cohenbebf0422012-04-11 18:06:28 -0700886 }
Adam Cohend4844c32011-02-18 19:25:06 -0800887
Adam Cohend4844c32011-02-18 19:25:06 -0800888 final ContentValues values = new ContentValues();
Adam Cohend4844c32011-02-18 19:25:06 -0800889 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
Adam Cohenbebf0422012-04-11 18:06:28 -0700890 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
891 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800892 values.put(LauncherSettings.Favorites.RANK, item.rank);
Adam Cohenbebf0422012-04-11 18:06:28 -0700893 values.put(LauncherSettings.Favorites.SPANX, item.spanX);
894 values.put(LauncherSettings.Favorites.SPANY, item.spanY);
Adam Cohendcd297f2013-06-18 13:13:40 -0700895 values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
Adam Cohend4844c32011-02-18 19:25:06 -0800896
Michael Jurka816474f2012-06-25 14:49:02 -0700897 updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
Adam Cohenbebf0422012-04-11 18:06:28 -0700898 }
Michael Jurkac9d95c52011-08-29 14:03:34 -0700899
900 /**
901 * Update an item to the database in a specified container.
902 */
903 static void updateItemInDatabase(Context context, final ItemInfo item) {
904 final ContentValues values = new ContentValues();
Kenny Guyed131872014-04-30 03:02:21 +0100905 item.onAddToDatabase(context, values);
Michael Jurkac9d95c52011-08-29 14:03:34 -0700906 updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
Adam Cohend4844c32011-02-18 19:25:06 -0800907 }
908
909 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400910 * Returns true if the shortcuts already exists in the database.
911 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800912 */
Sunny Goyale0f58d72014-11-10 18:05:31 -0800913 static boolean shortcutExists(Context context, String title, Intent intent,
914 UserHandleCompat user) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400915 final ContentResolver cr = context.getContentResolver();
Sunny Goyal2a6cf092014-06-26 15:27:14 -0700916 final Intent intentWithPkg, intentWithoutPkg;
917
918 if (intent.getComponent() != null) {
919 // If component is not null, an intent with null package will produce
920 // the same result and should also be a match.
921 if (intent.getPackage() != null) {
922 intentWithPkg = intent;
923 intentWithoutPkg = new Intent(intent).setPackage(null);
924 } else {
925 intentWithPkg = new Intent(intent).setPackage(
926 intent.getComponent().getPackageName());
927 intentWithoutPkg = intent;
928 }
929 } else {
930 intentWithPkg = intent;
931 intentWithoutPkg = intent;
932 }
Sunny Goyale0f58d72014-11-10 18:05:31 -0800933 String userSerial = Long.toString(UserManagerCompat.getInstance(context)
934 .getSerialNumberForUser(user));
Joe Onorato9c1289c2009-08-17 11:03:03 -0400935 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
Sunny Goyale0f58d72014-11-10 18:05:31 -0800936 new String[] { "title", "intent", "profileId" },
937 "title=? and (intent=? or intent=?) and profileId=?",
938 new String[] { title, intentWithPkg.toUri(0), intentWithoutPkg.toUri(0), userSerial },
939 null);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400940 try {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800941 return c.moveToFirst();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400942 } finally {
943 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800944 }
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700945 }
946
Joe Onorato9c1289c2009-08-17 11:03:03 -0400947 /**
948 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
949 */
950 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
951 final ContentResolver cr = context.getContentResolver();
952 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
953 "_id=? and (itemType=? or itemType=?)",
954 new String[] { String.valueOf(id),
Adam Cohendf2cc412011-04-27 16:56:57 -0700955 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700956
Joe Onorato9c1289c2009-08-17 11:03:03 -0400957 try {
958 if (c.moveToFirst()) {
959 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
960 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
961 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
962 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
963 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
964 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700965 final int optionsIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.OPTIONS);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966
Joe Onorato9c1289c2009-08-17 11:03:03 -0400967 FolderInfo folderInfo = null;
968 switch (c.getInt(itemTypeIndex)) {
Adam Cohendf2cc412011-04-27 16:56:57 -0700969 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
970 folderInfo = findOrMakeFolder(folderList, id);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400971 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700972 }
973
Joe Onorato9c1289c2009-08-17 11:03:03 -0400974 folderInfo.title = c.getString(titleIndex);
975 folderInfo.id = id;
976 folderInfo.container = c.getInt(containerIndex);
Adam Cohendcd297f2013-06-18 13:13:40 -0700977 folderInfo.screenId = c.getInt(screenIndex);
Adam Cohend22015c2010-07-26 22:02:18 -0700978 folderInfo.cellX = c.getInt(cellXIndex);
979 folderInfo.cellY = c.getInt(cellYIndex);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700980 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400981
982 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700983 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400984 } finally {
985 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700986 }
987
988 return null;
989 }
990
Joe Onorato9c1289c2009-08-17 11:03:03 -0400991 /**
992 * Add an item to the database in a specified container. Sets the container, screen, cellX and
993 * cellY fields of the item. Also assigns an ID to the item.
994 */
Winson Chung3d503fb2011-07-13 17:25:49 -0700995 static void addItemToDatabase(Context context, final ItemInfo item, final long container,
Adam Cohendcd297f2013-06-18 13:13:40 -0700996 final long screenId, final int cellX, final int cellY, final boolean notify) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400997 item.container = container;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400998 item.cellX = cellX;
999 item.cellY = cellY;
Winson Chung3d503fb2011-07-13 17:25:49 -07001000 // We store hotseat items in canonical form which is this orientation invariant position
1001 // in the hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07001002 if (context instanceof Launcher && screenId < 0 &&
Winson Chung3d503fb2011-07-13 17:25:49 -07001003 container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
Winson Chung3d503fb2011-07-13 17:25:49 -07001005 } else {
Adam Cohendcd297f2013-06-18 13:13:40 -07001006 item.screenId = screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07001007 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001008
1009 final ContentValues values = new ContentValues();
1010 final ContentResolver cr = context.getContentResolver();
Kenny Guyed131872014-04-30 03:02:21 +01001011 item.onAddToDatabase(context, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001012
Michael Jurka414300a2013-08-27 15:42:35 +02001013 item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001014 values.put(LauncherSettings.Favorites._ID, item.id);
Winson Chungaafa03c2010-06-11 17:34:16 -07001015
Jason Monk8e19cf22014-03-20 15:06:57 -04001016 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Michael Jurkac9d95c52011-08-29 14:03:34 -07001017 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001018 public void run() {
1019 cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
1020 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001021
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001022 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001023 synchronized (sBgLock) {
Jason Monk8e19cf22014-03-20 15:06:57 -04001024 checkItemInfoLocked(item.id, item, stackTrace);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001025 sBgItemsIdMap.put(item.id, item);
1026 switch (item.itemType) {
1027 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1028 sBgFolders.put(item.id, (FolderInfo) item);
1029 // Fall through
1030 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1031 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1032 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
1033 item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1034 sBgWorkspaceItems.add(item);
1035 } else {
1036 if (!sBgFolders.containsKey(item.container)) {
1037 // Adding an item to a folder that doesn't exist.
1038 String msg = "adding item: " + item + " to a folder that " +
1039 " doesn't exist";
Adam Cohen28b3e102012-10-04 17:21:33 -07001040 Log.e(TAG, msg);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001041 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07001042 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001043 break;
1044 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1045 sBgAppWidgets.add((LauncherAppWidgetInfo) item);
1046 break;
1047 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001048 }
1049 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001050 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001051 runOnWorkerThread(r);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001052 }
1053
Joe Onorato9c1289c2009-08-17 11:03:03 -04001054 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07001055 * Creates a new unique child id, for a given cell span across all layouts.
1056 */
Michael Jurka845ba3b2010-09-28 17:09:46 -07001057 static int getCellLayoutChildId(
Adam Cohendcd297f2013-06-18 13:13:40 -07001058 long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
Winson Chung3d503fb2011-07-13 17:25:49 -07001059 return (((int) container & 0xFF) << 24)
Adam Cohendcd297f2013-06-18 13:13:40 -07001060 | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
Winson Chungaafa03c2010-06-11 17:34:16 -07001061 }
1062
Sunny Goyal34942622014-08-29 17:20:55 -07001063 private static ArrayList<ItemInfo> getItemsByPackageName(
1064 final String pn, final UserHandleCompat user) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001065 ItemInfoFilter filter = new ItemInfoFilter() {
1066 @Override
1067 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
1068 return cn.getPackageName().equals(pn) && info.user.equals(user);
1069 }
1070 };
Sunny Goyal34942622014-08-29 17:20:55 -07001071 return filterItemInfos(sBgItemsIdMap.values(), filter);
1072 }
1073
1074 /**
1075 * Removes all the items from the database corresponding to the specified package.
1076 */
1077 static void deletePackageFromDatabase(Context context, final String pn,
1078 final UserHandleCompat user) {
1079 deleteItemsFromDatabase(context, getItemsByPackageName(pn, user));
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001080 }
1081
1082 /**
Michael Jurkac9d95c52011-08-29 14:03:34 -07001083 * Removes the specified item from the database
1084 * @param context
1085 * @param item
Joe Onorato9c1289c2009-08-17 11:03:03 -04001086 */
Michael Jurkac9d95c52011-08-29 14:03:34 -07001087 static void deleteItemFromDatabase(Context context, final ItemInfo item) {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001088 ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
1089 items.add(item);
1090 deleteItemsFromDatabase(context, items);
1091 }
1092
1093 /**
1094 * Removes the specified items from the database
1095 * @param context
1096 * @param item
1097 */
Sunny Goyal4390ace2014-10-13 11:33:11 -07001098 static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001099 final ContentResolver cr = context.getContentResolver();
Adam Cohen487f7dd2012-06-28 18:12:10 -07001100
Michael Jurka83df1882011-08-31 20:59:26 -07001101 Runnable r = new Runnable() {
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001102 public void run() {
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001103 for (ItemInfo item : items) {
1104 final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
1105 cr.delete(uri, null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001106
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001107 // Lock on mBgLock *after* the db operation
1108 synchronized (sBgLock) {
1109 switch (item.itemType) {
1110 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
1111 sBgFolders.remove(item.id);
1112 for (ItemInfo info: sBgItemsIdMap.values()) {
1113 if (info.container == item.id) {
1114 // We are deleting a folder which still contains items that
1115 // think they are contained by that folder.
1116 String msg = "deleting a folder (" + item + ") which still " +
1117 "contains items (" + info + ")";
1118 Log.e(TAG, msg);
1119 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001120 }
Sunny Goyale7b8cd92014-08-27 14:04:33 -07001121 sBgWorkspaceItems.remove(item);
1122 break;
1123 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1124 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1125 sBgWorkspaceItems.remove(item);
1126 break;
1127 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
1128 sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
1129 break;
1130 }
1131 sBgItemsIdMap.remove(item.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001132 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001133 }
1134 }
Michael Jurka83df1882011-08-31 20:59:26 -07001135 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001136 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001137 }
1138
1139 /**
Adam Cohendcd297f2013-06-18 13:13:40 -07001140 * Update the order of the workspace screens in the database. The array list contains
1141 * a list of screen ids in the order that they should appear.
1142 */
Winson Chungc9168342013-06-26 14:54:55 -07001143 void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chunga90303b2013-11-15 13:05:06 -08001144 // Log to disk
1145 Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
1146 Launcher.addDumpLog(TAG, "11683562 - screens: " + TextUtils.join(", ", screens), true);
1147
Winson Chung64359a52013-07-08 17:17:08 -07001148 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001149 final ContentResolver cr = context.getContentResolver();
1150 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
1151
1152 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -07001153 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -07001154 while (iter.hasNext()) {
1155 long id = iter.next();
1156 if (id < 0) {
1157 iter.remove();
1158 }
1159 }
1160
1161 Runnable r = new Runnable() {
1162 @Override
1163 public void run() {
Yura085c8532014-02-11 15:15:29 +00001164 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -07001165 // Clear the table
Yura085c8532014-02-11 15:15:29 +00001166 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -07001167 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -07001168 for (int i = 0; i < count; i++) {
1169 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -07001170 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -07001171 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
1172 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +00001173 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -07001174 }
Yura085c8532014-02-11 15:15:29 +00001175
1176 try {
1177 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
1178 } catch (Exception ex) {
1179 throw new RuntimeException(ex);
1180 }
Winson Chung9e6a0a22013-08-27 11:58:12 -07001181
Winson Chungba9c37f2013-08-30 14:11:37 -07001182 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001183 sBgWorkspaceScreens.clear();
1184 sBgWorkspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -07001185 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001186 }
1187 };
1188 runOnWorkerThread(r);
1189 }
1190
1191 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001192 * Remove the contents of the specified folder from the database
1193 */
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001194 static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04001195 final ContentResolver cr = context.getContentResolver();
1196
Michael Jurkac9d95c52011-08-29 14:03:34 -07001197 Runnable r = new Runnable() {
1198 public void run() {
1199 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001200 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001201 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001202 sBgItemsIdMap.remove(info.id);
1203 sBgFolders.remove(info.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 sBgWorkspaceItems.remove(info);
1205 }
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001206
Michael Jurkac9d95c52011-08-29 14:03:34 -07001207 cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
1208 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001209 // Lock on mBgLock *after* the db operation
Winson Chung2abf94d2012-07-18 18:16:38 -07001210 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001211 for (ItemInfo childInfo : info.contents) {
1212 sBgItemsIdMap.remove(childInfo.id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001213 }
Adam Cohenafb01ee2011-06-23 15:38:03 -07001214 }
Michael Jurkac9d95c52011-08-29 14:03:34 -07001215 }
1216 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001217 runOnWorkerThread(r);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001218 }
1219
1220 /**
1221 * Set this as the current Launcher activity object for the loader.
1222 */
1223 public void initialize(Callbacks callbacks) {
1224 synchronized (mLock) {
1225 mCallbacks = new WeakReference<Callbacks>(callbacks);
1226 }
1227 }
1228
Kenny Guyed131872014-04-30 03:02:21 +01001229 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001230 public void onPackageChanged(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001231 int op = PackageUpdatedTask.OP_UPDATE;
1232 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1233 user));
1234 }
1235
1236 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001237 public void onPackageRemoved(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001238 int op = PackageUpdatedTask.OP_REMOVE;
1239 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1240 user));
1241 }
1242
1243 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001244 public void onPackageAdded(String packageName, UserHandleCompat user) {
Kenny Guyed131872014-04-30 03:02:21 +01001245 int op = PackageUpdatedTask.OP_ADD;
1246 enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
1247 user));
1248 }
1249
1250 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001251 public void onPackagesAvailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001252 boolean replacing) {
1253 if (!replacing) {
1254 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packageNames,
1255 user));
1256 if (mAppsCanBeOnRemoveableStorage) {
1257 // Only rebind if we support removable storage. It catches the
1258 // case where
1259 // apps on the external sd card need to be reloaded
1260 startLoaderFromBackground();
1261 }
1262 } else {
1263 // If we are replacing then just update the packages in the list
1264 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE,
1265 packageNames, user));
1266 }
1267 }
1268
1269 @Override
Kenny Guyc2bd8102014-06-30 12:30:31 +01001270 public void onPackagesUnavailable(String[] packageNames, UserHandleCompat user,
Kenny Guyed131872014-04-30 03:02:21 +01001271 boolean replacing) {
1272 if (!replacing) {
1273 enqueuePackageUpdated(new PackageUpdatedTask(
1274 PackageUpdatedTask.OP_UNAVAILABLE, packageNames,
1275 user));
1276 }
Kenny Guyed131872014-04-30 03:02:21 +01001277 }
1278
Joe Onorato1d8e7bb2009-10-15 19:49:43 -07001279 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -04001280 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
1281 * ACTION_PACKAGE_CHANGED.
1282 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +01001283 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -04001284 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -04001285 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -07001286
Joe Onorato36115782010-06-17 13:28:48 -04001287 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +01001288 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -07001289 // If we have changed locale we need to clear out the labels in all apps/workspace.
1290 forceReload();
1291 } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1292 // Check if configuration change was an mcc/mnc change which would affect app resources
1293 // and we would need to clear out the labels in all apps/workspace. Same handling as
1294 // above for ACTION_LOCALE_CHANGED
1295 Configuration currentConfig = context.getResources().getConfiguration();
Reena Lee99a73f32011-10-24 17:27:37 -07001296 if (mPreviousConfigMcc != currentConfig.mcc) {
Reena Lee93f824a2011-09-23 17:20:28 -07001297 Log.d(TAG, "Reload apps on config change. curr_mcc:"
Reena Lee99a73f32011-10-24 17:27:37 -07001298 + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
Reena Lee93f824a2011-09-23 17:20:28 -07001299 forceReload();
1300 }
1301 // Update previousConfig
Reena Lee99a73f32011-10-24 17:27:37 -07001302 mPreviousConfigMcc = currentConfig.mcc;
Winson Chungcbf7c4d2011-08-23 11:58:54 -07001303 } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
1304 SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08001305 Callbacks callbacks = getCallback();
1306 if (callbacks != null) {
1307 callbacks.bindSearchablesChanged();
Winson Chungcfdf7ee2011-08-25 11:38:34 -07001308 }
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001309 }
1310 }
1311
Amith Yamasani6cc806d2014-05-02 13:47:11 -07001312 void forceReload() {
Winson Chungf0c6ae02012-03-21 16:10:31 -07001313 resetLoadedState(true, true);
1314
Reena Lee93f824a2011-09-23 17:20:28 -07001315 // Do this here because if the launcher activity is running it will be restarted.
1316 // If it's not running startLoaderFromBackground will merely tell it that it needs
1317 // to reload.
1318 startLoaderFromBackground();
1319 }
1320
Winson Chungf0c6ae02012-03-21 16:10:31 -07001321 public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
1322 synchronized (mLock) {
1323 // Stop any existing loaders first, so they don't set mAllAppsLoaded or
1324 // mWorkspaceLoaded to true later
1325 stopLoaderLocked();
1326 if (resetAllAppsLoaded) mAllAppsLoaded = false;
1327 if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
1328 }
1329 }
1330
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001331 /**
1332 * When the launcher is in the background, it's possible for it to miss paired
1333 * configuration changes. So whenever we trigger the loader from the background
1334 * tell the launcher that it needs to re-run the loader when it comes back instead
1335 * of doing it now.
1336 */
1337 public void startLoaderFromBackground() {
1338 boolean runLoader = false;
Sunny Goyale0f58d72014-11-10 18:05:31 -08001339 Callbacks callbacks = getCallback();
1340 if (callbacks != null) {
1341 // Only actually run the loader if they're not paused.
1342 if (!callbacks.setLoadOnResume()) {
1343 runLoader = true;
Joe Onoratoe9ad59e2010-10-29 17:35:36 -07001344 }
1345 }
1346 if (runLoader) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001347 startLoader(false, PagedView.INVALID_RESTORE_PAGE);
Joe Onorato790c2d92010-06-11 00:14:11 -07001348 }
Joe Onorato36115782010-06-17 13:28:48 -04001349 }
Joe Onoratof99f8c12009-10-31 17:27:36 -04001350
Reena Lee93f824a2011-09-23 17:20:28 -07001351 // If there is already a loader task running, tell it to stop.
1352 // returns true if isLaunching() was true on the old task
1353 private boolean stopLoaderLocked() {
1354 boolean isLaunching = false;
1355 LoaderTask oldTask = mLoaderTask;
1356 if (oldTask != null) {
1357 if (oldTask.isLaunching()) {
1358 isLaunching = true;
1359 }
1360 oldTask.stopLocked();
1361 }
1362 return isLaunching;
1363 }
1364
Adam Cohen1a85c582014-09-30 09:48:49 -07001365 public boolean isCurrentCallbacks(Callbacks callbacks) {
1366 return (mCallbacks != null && mCallbacks.get() == callbacks);
1367 }
1368
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001369 public void startLoader(boolean isLaunching, int synchronousBindPage) {
Dan Sandlerd5024042014-01-09 15:01:33 -05001370 startLoader(isLaunching, synchronousBindPage, LOADER_FLAG_NONE);
1371 }
1372
1373 public void startLoader(boolean isLaunching, int synchronousBindPage, int loadFlags) {
Joe Onorato36115782010-06-17 13:28:48 -04001374 synchronized (mLock) {
1375 if (DEBUG_LOADERS) {
1376 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
1377 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001378
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001379 // Clear any deferred bind-runnables from the synchronized load process
1380 // We must do this before any loading/binding is scheduled below.
Jason Monka0a7a742014-04-22 09:23:19 -04001381 synchronized (mDeferredBindRunnables) {
1382 mDeferredBindRunnables.clear();
1383 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001384
Joe Onorato36115782010-06-17 13:28:48 -04001385 // Don't bother to start the thread if we know it's not going to do anything
1386 if (mCallbacks != null && mCallbacks.get() != null) {
1387 // If there is already one running, tell it to stop.
Reena Lee93f824a2011-09-23 17:20:28 -07001388 // also, don't downgrade isLaunching if we're already running
1389 isLaunching = isLaunching || stopLoaderLocked();
Dan Sandlerd5024042014-01-09 15:01:33 -05001390 mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching, loadFlags);
Derek Prothro7aff3992013-12-10 14:00:37 -05001391 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
1392 && mAllAppsLoaded && mWorkspaceLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001393 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
1394 } else {
1395 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
1396 sWorker.post(mLoaderTask);
1397 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001398 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001399 }
1400 }
1401
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001402 void bindRemainingSynchronousPages() {
1403 // Post the remaining side pages to be loaded
1404 if (!mDeferredBindRunnables.isEmpty()) {
Jason Monka0a7a742014-04-22 09:23:19 -04001405 Runnable[] deferredBindRunnables = null;
1406 synchronized (mDeferredBindRunnables) {
1407 deferredBindRunnables = mDeferredBindRunnables.toArray(
1408 new Runnable[mDeferredBindRunnables.size()]);
1409 mDeferredBindRunnables.clear();
1410 }
1411 for (final Runnable r : deferredBindRunnables) {
Winson Chung81b52252012-08-27 15:34:29 -07001412 mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001413 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001414 }
1415 }
1416
Joe Onorato36115782010-06-17 13:28:48 -04001417 public void stopLoader() {
1418 synchronized (mLock) {
1419 if (mLoaderTask != null) {
1420 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001421 }
1422 }
Joe Onorato36115782010-06-17 13:28:48 -04001423 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001424
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001425 /**
1426 * Loads the workspace screen ids in an ordered list.
1427 */
1428 private static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -07001429 final ContentResolver contentResolver = context.getContentResolver();
1430 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -07001431
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001432 // Get screens ordered by rank.
1433 final Cursor sc = contentResolver.query(screensUri, null, null, null,
1434 LauncherSettings.WorkspaceScreens.SCREEN_RANK);
1435 ArrayList<Long> screenIds = new ArrayList<Long>();
Winson Chung76828c82013-08-19 15:43:29 -07001436 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001437 final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
Winson Chung76828c82013-08-19 15:43:29 -07001438 while (sc.moveToNext()) {
1439 try {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001440 screenIds.add(sc.getLong(idIndex));
Winson Chung76828c82013-08-19 15:43:29 -07001441 } catch (Exception e) {
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001442 Launcher.addDumpLog(TAG, "Desktop items loading interrupted"
1443 + " - invalid screens: " + e, true);
Winson Chung76828c82013-08-19 15:43:29 -07001444 }
1445 }
1446 } finally {
1447 sc.close();
1448 }
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -08001449 return screenIds;
Winson Chung76828c82013-08-19 15:43:29 -07001450 }
1451
Michael Jurkac57b7a82011-08-09 22:02:20 -07001452 public boolean isAllAppsLoaded() {
1453 return mAllAppsLoaded;
1454 }
1455
Winson Chung36a62fe2012-05-06 18:04:42 -07001456 boolean isLoadingWorkspace() {
1457 synchronized (mLock) {
1458 if (mLoaderTask != null) {
1459 return mLoaderTask.isLoadingWorkspace();
1460 }
1461 }
1462 return false;
1463 }
1464
Joe Onorato36115782010-06-17 13:28:48 -04001465 /**
1466 * Runnable for the thread that loads the contents of the launcher:
1467 * - workspace icons
1468 * - widgets
1469 * - all apps icons
1470 */
1471 private class LoaderTask implements Runnable {
1472 private Context mContext;
Joe Onorato36115782010-06-17 13:28:48 -04001473 private boolean mIsLaunching;
Winson Chung36a62fe2012-05-06 18:04:42 -07001474 private boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -04001475 private boolean mStopped;
1476 private boolean mLoadAndBindStepFinished;
Dan Sandlerd5024042014-01-09 15:01:33 -05001477 private int mFlags;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001478
Dan Sandlerd5024042014-01-09 15:01:33 -05001479 LoaderTask(Context context, boolean isLaunching, int flags) {
Joe Onorato36115782010-06-17 13:28:48 -04001480 mContext = context;
1481 mIsLaunching = isLaunching;
Dan Sandlerd5024042014-01-09 15:01:33 -05001482 mFlags = flags;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001483 }
1484
Joe Onorato36115782010-06-17 13:28:48 -04001485 boolean isLaunching() {
1486 return mIsLaunching;
1487 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001488
Winson Chung36a62fe2012-05-06 18:04:42 -07001489 boolean isLoadingWorkspace() {
1490 return mIsLoadingAndBindingWorkspace;
1491 }
1492
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001493 private void loadAndBindWorkspace() {
Winson Chung36a62fe2012-05-06 18:04:42 -07001494 mIsLoadingAndBindingWorkspace = true;
1495
Joe Onorato36115782010-06-17 13:28:48 -04001496 // Load the workspace
Joe Onorato36115782010-06-17 13:28:48 -04001497 if (DEBUG_LOADERS) {
1498 Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001499 }
Michael Jurka288a36b2011-07-12 16:53:48 -07001500
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001501 if (!mWorkspaceLoaded) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001502 loadWorkspace();
Reena Lee93f824a2011-09-23 17:20:28 -07001503 synchronized (LoaderTask.this) {
1504 if (mStopped) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001505 return;
Reena Lee93f824a2011-09-23 17:20:28 -07001506 }
1507 mWorkspaceLoaded = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001508 }
1509 }
1510
Joe Onorato36115782010-06-17 13:28:48 -04001511 // Bind the workspace
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001512 bindWorkspace(-1);
Joe Onorato36115782010-06-17 13:28:48 -04001513 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001514
Joe Onorato36115782010-06-17 13:28:48 -04001515 private void waitForIdle() {
1516 // Wait until the either we're stopped or the other threads are done.
1517 // This way we don't start loading all apps until the workspace has settled
1518 // down.
1519 synchronized (LoaderTask.this) {
1520 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -07001521
Joe Onorato36115782010-06-17 13:28:48 -04001522 mHandler.postIdle(new Runnable() {
1523 public void run() {
1524 synchronized (LoaderTask.this) {
1525 mLoadAndBindStepFinished = true;
1526 if (DEBUG_LOADERS) {
1527 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -04001528 }
Joe Onorato36115782010-06-17 13:28:48 -04001529 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -04001530 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001531 }
Joe Onorato36115782010-06-17 13:28:48 -04001532 });
1533
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08001534 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -04001535 try {
Michael Jurkac7700af2013-05-14 20:17:58 +02001536 // Just in case mFlushingWorkerThread changes but we aren't woken up,
1537 // wait no longer than 1sec at a time
1538 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -04001539 } catch (InterruptedException ex) {
1540 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -04001541 }
1542 }
Joe Onorato36115782010-06-17 13:28:48 -04001543 if (DEBUG_LOADERS) {
1544 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -07001545 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -04001546 + "ms for previous step to finish binding");
1547 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001548 }
Joe Onorato36115782010-06-17 13:28:48 -04001549 }
Daniel Sandler843e8602010-06-07 14:59:01 -04001550
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001551 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -05001552 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001553 // Ensure that we have a valid page index to load synchronously
1554 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
1555 "valid page index");
1556 }
1557 if (!mAllAppsLoaded || !mWorkspaceLoaded) {
1558 // Ensure that we don't try and bind a specified page when the pages have not been
1559 // loaded already (we should load everything asynchronously in that case)
1560 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
1561 }
1562 synchronized (mLock) {
1563 if (mIsLoaderTaskRunning) {
1564 // Ensure that we are never running the background loading at this point since
1565 // we also touch the background collections
1566 throw new RuntimeException("Error! Background loading is already running");
1567 }
1568 }
1569
1570 // XXX: Throw an exception if we are already loading (since we touch the worker thread
1571 // data structures, we can't allow any other thread to touch that data, but because
1572 // this call is synchronous, we can get away with not locking).
1573
Daniel Sandlercc8befa2013-06-11 14:45:48 -04001574 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -07001575 // operations from the previous activity. We need to ensure that all queued operations
1576 // are executed before any synchronous binding work is done.
1577 mHandler.flush();
1578
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001579 // Divide the set of loaded items into those that we are binding synchronously, and
1580 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001581 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001582 // XXX: For now, continue posting the binding of AllApps as there are other issues that
1583 // arise from that.
1584 onlyBindAllApps();
1585 }
1586
Joe Onorato36115782010-06-17 13:28:48 -04001587 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001588 synchronized (mLock) {
1589 mIsLoaderTaskRunning = true;
1590 }
Joe Onorato36115782010-06-17 13:28:48 -04001591 // Optimize for end-user experience: if the Launcher is up and // running with the
1592 // All Apps interface in the foreground, load All Apps first. Otherwise, load the
1593 // workspace first (default).
Joe Onorato36115782010-06-17 13:28:48 -04001594 keep_running: {
Daniel Sandler843e8602010-06-07 14:59:01 -04001595 // Elevate priority when Home launches for the first time to avoid
1596 // starving at boot time. Staring at a blank home is not cool.
1597 synchronized (mLock) {
Winson Chungaac01e12011-08-17 10:37:13 -07001598 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
1599 (mIsLaunching ? "DEFAULT" : "BACKGROUND"));
Daniel Sandler843e8602010-06-07 14:59:01 -04001600 android.os.Process.setThreadPriority(mIsLaunching
1601 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
1602 }
Winson Chung64359a52013-07-08 17:17:08 -07001603 if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001604 loadAndBindWorkspace();
Daniel Sandler843e8602010-06-07 14:59:01 -04001605
Joe Onorato36115782010-06-17 13:28:48 -04001606 if (mStopped) {
1607 break keep_running;
1608 }
1609
1610 // Whew! Hard work done. Slow us down, and wait until the UI thread has
1611 // settled down.
Daniel Sandler843e8602010-06-07 14:59:01 -04001612 synchronized (mLock) {
1613 if (mIsLaunching) {
Winson Chungaac01e12011-08-17 10:37:13 -07001614 if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
Daniel Sandler843e8602010-06-07 14:59:01 -04001615 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1616 }
1617 }
Joe Onorato36115782010-06-17 13:28:48 -04001618 waitForIdle();
Daniel Sandler843e8602010-06-07 14:59:01 -04001619
1620 // second step
Winson Chung64359a52013-07-08 17:17:08 -07001621 if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
1622 loadAndBindAllApps();
Winson Chung7ed37742011-09-08 15:45:51 -07001623
1624 // Restore the default thread priority after we are done loading items
1625 synchronized (mLock) {
1626 android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1627 }
Joe Onorato36115782010-06-17 13:28:48 -04001628 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001629
Joe Onorato36115782010-06-17 13:28:48 -04001630 // Clear out this reference, otherwise we end up holding it until all of the
1631 // callback runnables are done.
1632 mContext = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001633
Joe Onorato36115782010-06-17 13:28:48 -04001634 synchronized (mLock) {
1635 // If we are still the last one to be scheduled, remove ourselves.
1636 if (mLoaderTask == this) {
1637 mLoaderTask = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001638 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001639 mIsLoaderTaskRunning = false;
Joe Onorato36115782010-06-17 13:28:48 -04001640 }
Joe Onorato36115782010-06-17 13:28:48 -04001641 }
1642
1643 public void stopLocked() {
1644 synchronized (LoaderTask.this) {
1645 mStopped = true;
1646 this.notify();
1647 }
1648 }
1649
1650 /**
1651 * Gets the callbacks object. If we've been stopped, or if the launcher object
1652 * has somehow been garbage collected, return null instead. Pass in the Callbacks
1653 * object that was around when the deferred message was scheduled, and if there's
1654 * a new Callbacks object around then also return null. This will save us from
1655 * calling onto it with data that will be ignored.
1656 */
1657 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
1658 synchronized (mLock) {
1659 if (mStopped) {
1660 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001661 }
Joe Onorato36115782010-06-17 13:28:48 -04001662
1663 if (mCallbacks == null) {
1664 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -04001665 }
Joe Onorato36115782010-06-17 13:28:48 -04001666
1667 final Callbacks callbacks = mCallbacks.get();
1668 if (callbacks != oldCallbacks) {
1669 return null;
1670 }
1671 if (callbacks == null) {
1672 Log.w(TAG, "no mCallbacks");
1673 return null;
1674 }
1675
1676 return callbacks;
1677 }
1678 }
1679
1680 // check & update map of what's occupied; used to discard overlapping/invalid items
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07001681 private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
Winson Chung892c74d2013-08-22 16:15:50 -07001682 LauncherAppState app = LauncherAppState.getInstance();
1683 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Dan Sandler295ae182013-12-10 16:05:47 -05001684 final int countX = (int) grid.numColumns;
1685 final int countY = (int) grid.numRows;
Winson Chung892c74d2013-08-22 16:15:50 -07001686
Adam Cohendcd297f2013-06-18 13:13:40 -07001687 long containerIndex = item.screenId;
Winson Chungf30ad5f2011-08-08 10:55:42 -07001688 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Winson Chunga0b7e862013-09-05 16:03:15 -07001689 // Return early if we detect that an item is under the hotseat button
1690 if (mCallbacks == null ||
1691 mCallbacks.get().isAllAppsButtonRank((int) item.screenId)) {
Dan Sandler295ae182013-12-10 16:05:47 -05001692 Log.e(TAG, "Error loading shortcut into hotseat " + item
1693 + " into position (" + item.screenId + ":" + item.cellX + ","
1694 + item.cellY + ") occupied by all apps");
Winson Chunga0b7e862013-09-05 16:03:15 -07001695 return false;
1696 }
1697
Dan Sandler295ae182013-12-10 16:05:47 -05001698 final ItemInfo[][] hotseatItems =
1699 occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
1700
Adam Cohenae4409d2013-11-26 10:34:59 -08001701 if (item.screenId >= grid.numHotseatIcons) {
1702 Log.e(TAG, "Error loading shortcut " + item
1703 + " into hotseat position " + item.screenId
1704 + ", position out of bounds: (0 to " + (grid.numHotseatIcons - 1)
1705 + ")");
1706 return false;
1707 }
1708
Dan Sandler295ae182013-12-10 16:05:47 -05001709 if (hotseatItems != null) {
1710 if (hotseatItems[(int) item.screenId][0] != null) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001711 Log.e(TAG, "Error loading shortcut into hotseat " + item
1712 + " into position (" + item.screenId + ":" + item.cellX + ","
1713 + item.cellY + ") occupied by "
1714 + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
1715 [(int) item.screenId][0]);
1716 return false;
Dan Sandler295ae182013-12-10 16:05:47 -05001717 } else {
1718 hotseatItems[(int) item.screenId][0] = item;
1719 return true;
Adam Cohendcd297f2013-06-18 13:13:40 -07001720 }
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001721 } else {
Adam Cohenae4409d2013-11-26 10:34:59 -08001722 final ItemInfo[][] items = new ItemInfo[(int) grid.numHotseatIcons][1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001723 items[(int) item.screenId][0] = item;
1724 occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001725 return true;
1726 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001727 } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1728 // Skip further checking if it is not the hotseat or workspace container
Daniel Sandler8802e962010-05-26 16:28:16 -04001729 return true;
1730 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001731
Adam Cohendcd297f2013-06-18 13:13:40 -07001732 if (!occupied.containsKey(item.screenId)) {
Winson Chung892c74d2013-08-22 16:15:50 -07001733 ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
Adam Cohendcd297f2013-06-18 13:13:40 -07001734 occupied.put(item.screenId, items);
1735 }
1736
Dan Sandler295ae182013-12-10 16:05:47 -05001737 final ItemInfo[][] screens = occupied.get(item.screenId);
Adam Cohenae4409d2013-11-26 10:34:59 -08001738 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1739 item.cellX < 0 || item.cellY < 0 ||
1740 item.cellX + item.spanX > countX || item.cellY + item.spanY > countY) {
1741 Log.e(TAG, "Error loading shortcut " + item
1742 + " into cell (" + containerIndex + "-" + item.screenId + ":"
1743 + item.cellX + "," + item.cellY
1744 + ") out of screen bounds ( " + countX + "x" + countY + ")");
1745 return false;
1746 }
1747
Winson Chung6ba2a1b2011-09-02 16:22:11 -07001748 // Check if any workspace icons overlap with each other
Joe Onorato36115782010-06-17 13:28:48 -04001749 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1750 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001751 if (screens[x][y] != null) {
Joe Onorato36115782010-06-17 13:28:48 -04001752 Log.e(TAG, "Error loading shortcut " + item
Adam Cohendcd297f2013-06-18 13:13:40 -07001753 + " into cell (" + containerIndex + "-" + item.screenId + ":"
Joe Onorato36115782010-06-17 13:28:48 -04001754 + x + "," + y
Winson Chungaafa03c2010-06-11 17:34:16 -07001755 + ") occupied by "
Adam Cohendcd297f2013-06-18 13:13:40 -07001756 + screens[x][y]);
Joe Onorato36115782010-06-17 13:28:48 -04001757 return false;
1758 }
1759 }
1760 }
1761 for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
1762 for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001763 screens[x][y] = item;
Joe Onorato36115782010-06-17 13:28:48 -04001764 }
1765 }
Winson Chungf30ad5f2011-08-08 10:55:42 -07001766
Joe Onorato36115782010-06-17 13:28:48 -04001767 return true;
1768 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001769
Winson Chungba9c37f2013-08-30 14:11:37 -07001770 /** Clears all the sBg data structures */
1771 private void clearSBgDataStructures() {
1772 synchronized (sBgLock) {
1773 sBgWorkspaceItems.clear();
1774 sBgAppWidgets.clear();
1775 sBgFolders.clear();
1776 sBgItemsIdMap.clear();
Winson Chungba9c37f2013-08-30 14:11:37 -07001777 sBgWorkspaceScreens.clear();
1778 }
1779 }
1780
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001781 private void loadWorkspace() {
Winson Chung9f9f00b2013-11-15 13:27:00 -08001782 // Log to disk
1783 Launcher.addDumpLog(TAG, "11683562 - loadWorkspace()", true);
1784
Joe Onorato36115782010-06-17 13:28:48 -04001785 final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001786
Joe Onorato36115782010-06-17 13:28:48 -04001787 final Context context = mContext;
1788 final ContentResolver contentResolver = context.getContentResolver();
1789 final PackageManager manager = context.getPackageManager();
Joe Onorato36115782010-06-17 13:28:48 -04001790 final boolean isSafeMode = manager.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001791 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
1792 final boolean isSdCardReady = context.registerReceiver(null,
Sunny Goyal05e318d2014-07-29 11:49:35 -07001793 new IntentFilter(StartupReceiver.SYSTEM_READY)) != null;
Joe Onorato3c2f7e12009-10-31 19:17:31 -04001794
Winson Chung892c74d2013-08-22 16:15:50 -07001795 LauncherAppState app = LauncherAppState.getInstance();
1796 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1797 int countX = (int) grid.numColumns;
1798 int countY = (int) grid.numRows;
1799
Dan Sandlerd5024042014-01-09 15:01:33 -05001800 if ((mFlags & LOADER_FLAG_CLEAR_WORKSPACE) != 0) {
1801 Launcher.addDumpLog(TAG, "loadWorkspace: resetting launcher database", true);
1802 LauncherAppState.getLauncherProvider().deleteDatabase();
1803 }
1804
1805 if ((mFlags & LOADER_FLAG_MIGRATE_SHORTCUTS) != 0) {
1806 // append the user's Launcher2 shortcuts
1807 Launcher.addDumpLog(TAG, "loadWorkspace: migrating from launcher2", true);
1808 LauncherAppState.getLauncherProvider().migrateLauncher2Shortcuts();
1809 } else {
1810 // Make sure the default workspace is loaded
1811 Launcher.addDumpLog(TAG, "loadWorkspace: loading default favorites", false);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001812 LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary();
Dan Sandlerd5024042014-01-09 15:01:33 -05001813 }
Adam Cohene25af792013-06-06 23:08:25 -07001814
Winson Chung2abf94d2012-07-18 18:16:38 -07001815 synchronized (sBgLock) {
Winson Chungba9c37f2013-08-30 14:11:37 -07001816 clearSBgDataStructures();
Sunny Goyal94485362014-09-18 16:13:58 -07001817 final HashSet<String> installingPkgs = PackageInstallerCompat
1818 .getInstance(mContext).updateAndGetActiveSessionCache();
Romain Guy5c16f3e2010-01-12 17:24:58 -08001819
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001820 final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
Chris Wrenf4d08112014-01-16 18:13:56 -05001821 final ArrayList<Long> restoredRows = new ArrayList<Long>();
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07001822 final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION;
Chris Wrene523e702013-10-09 10:36:55 -04001823 if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri);
Adam Cohene25af792013-06-06 23:08:25 -07001824 final Cursor c = contentResolver.query(contentUri, null, null, null, null);
Daniel Sandler8802e962010-05-26 16:28:16 -04001825
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001826 // +1 for the hotseat (it can be larger than the workspace)
1827 // Load workspace in reverse order to ensure that latest items are loaded first (and
1828 // before any earlier duplicates)
Adam Cohendcd297f2013-06-18 13:13:40 -07001829 final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
Joe Onorato9c1289c2009-08-17 11:03:03 -04001830
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001831 try {
1832 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
1833 final int intentIndex = c.getColumnIndexOrThrow
1834 (LauncherSettings.Favorites.INTENT);
1835 final int titleIndex = c.getColumnIndexOrThrow
1836 (LauncherSettings.Favorites.TITLE);
1837 final int iconTypeIndex = c.getColumnIndexOrThrow(
1838 LauncherSettings.Favorites.ICON_TYPE);
1839 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
1840 final int iconPackageIndex = c.getColumnIndexOrThrow(
1841 LauncherSettings.Favorites.ICON_PACKAGE);
1842 final int iconResourceIndex = c.getColumnIndexOrThrow(
1843 LauncherSettings.Favorites.ICON_RESOURCE);
1844 final int containerIndex = c.getColumnIndexOrThrow(
1845 LauncherSettings.Favorites.CONTAINER);
1846 final int itemTypeIndex = c.getColumnIndexOrThrow(
1847 LauncherSettings.Favorites.ITEM_TYPE);
1848 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
1849 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -04001850 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
1851 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001852 final int screenIndex = c.getColumnIndexOrThrow(
1853 LauncherSettings.Favorites.SCREEN);
1854 final int cellXIndex = c.getColumnIndexOrThrow
1855 (LauncherSettings.Favorites.CELLX);
1856 final int cellYIndex = c.getColumnIndexOrThrow
1857 (LauncherSettings.Favorites.CELLY);
1858 final int spanXIndex = c.getColumnIndexOrThrow
1859 (LauncherSettings.Favorites.SPANX);
1860 final int spanYIndex = c.getColumnIndexOrThrow(
1861 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -08001862 final int rankIndex = c.getColumnIndexOrThrow(
1863 LauncherSettings.Favorites.RANK);
Chris Wrenf4d08112014-01-16 18:13:56 -05001864 final int restoredIndex = c.getColumnIndexOrThrow(
1865 LauncherSettings.Favorites.RESTORED);
Kenny Guyed131872014-04-30 03:02:21 +01001866 final int profileIdIndex = c.getColumnIndexOrThrow(
1867 LauncherSettings.Favorites.PROFILE_ID);
Sunny Goyal5d85c442015-03-10 13:14:47 -07001868 final int optionsIndex = c.getColumnIndexOrThrow(
1869 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001870
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001871 ShortcutInfo info;
1872 String intentDescription;
1873 LauncherAppWidgetInfo appWidgetInfo;
1874 int container;
1875 long id;
Robin Lee26ace122015-03-16 19:41:43 +00001876 long serialNumber;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001877 Intent intent;
Kenny Guyed131872014-04-30 03:02:21 +01001878 UserHandleCompat user;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001879
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001880 while (!mStopped && c.moveToNext()) {
1881 try {
1882 int itemType = c.getInt(itemTypeIndex);
Chris Wrenf4d08112014-01-16 18:13:56 -05001883 boolean restored = 0 != c.getInt(restoredIndex);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001884 boolean allowMissingTarget = false;
Joe Onorato9c1289c2009-08-17 11:03:03 -04001885
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001886 switch (itemType) {
1887 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1888 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungee055712013-07-30 14:46:24 -07001889 id = c.getLong(idIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001890 intentDescription = c.getString(intentIndex);
Robin Lee26ace122015-03-16 19:41:43 +00001891 serialNumber = c.getInt(profileIdIndex);
Kenny Guyed131872014-04-30 03:02:21 +01001892 user = mUserManager.getUserForSerialNumber(serialNumber);
Sunny Goyal34942622014-08-29 17:20:55 -07001893 int promiseType = c.getInt(restoredIndex);
Sunny Goyal1a745e82014-10-02 15:58:31 -07001894 int disabledState = 0;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001895 boolean itemReplaced = false;
Kenny Guyed131872014-04-30 03:02:21 +01001896 if (user == null) {
1897 // User has been deleted remove the item.
1898 itemsToRemove.add(id);
1899 continue;
1900 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001901 try {
1902 intent = Intent.parseUri(intentDescription, 0);
Winson Chungee055712013-07-30 14:46:24 -07001903 ComponentName cn = intent.getComponent();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001904 if (cn != null && cn.getPackageName() != null) {
1905 boolean validPkg = launcherApps.isPackageEnabledForProfile(
1906 cn.getPackageName(), user);
1907 boolean validComponent = validPkg &&
1908 launcherApps.isActivityEnabledForProfile(cn, user);
1909
1910 if (validComponent) {
1911 if (restored) {
1912 // no special handling necessary for this item
1913 restoredRows.add(id);
1914 restored = false;
1915 }
1916 } else if (validPkg) {
Sunny Goyal34942622014-08-29 17:20:55 -07001917 intent = null;
1918 if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
1919 // We allow auto install apps to have their intent
1920 // updated after an install.
1921 intent = manager.getLaunchIntentForPackage(
1922 cn.getPackageName());
1923 if (intent != null) {
1924 ContentValues values = new ContentValues();
1925 values.put(LauncherSettings.Favorites.INTENT,
1926 intent.toUri(0));
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001927 updateItem(id, values);
Sunny Goyal34942622014-08-29 17:20:55 -07001928 }
1929 }
1930
1931 if (intent == null) {
1932 // The app is installed but the component is no
1933 // longer available.
1934 Launcher.addDumpLog(TAG,
1935 "Invalid component removed: " + cn, true);
1936 itemsToRemove.add(id);
1937 continue;
1938 } else {
1939 // no special handling necessary for this item
1940 restoredRows.add(id);
1941 restored = false;
1942 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001943 } else if (restored) {
1944 // Package is not yet available but might be
1945 // installed later.
Chris Wrenf4d08112014-01-16 18:13:56 -05001946 Launcher.addDumpLog(TAG,
1947 "package not yet restored: " + cn, true);
Sunny Goyal94485362014-09-18 16:13:58 -07001948
1949 if ((promiseType & ShortcutInfo.FLAG_RESTORE_STARTED) != 0) {
1950 // Restore has started once.
1951 } else if (installingPkgs.contains(cn.getPackageName())) {
1952 // App restore has started. Update the flag
1953 promiseType |= ShortcutInfo.FLAG_RESTORE_STARTED;
1954 ContentValues values = new ContentValues();
1955 values.put(LauncherSettings.Favorites.RESTORED,
1956 promiseType);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001957 updateItem(id, values);
1958 } else if ((promiseType & ShortcutInfo.FLAG_RESTORED_APP_TYPE) != 0) {
1959 // This is a common app. Try to replace this.
1960 int appType = CommonAppTypeParser.decodeItemTypeFromFlag(promiseType);
1961 CommonAppTypeParser parser = new CommonAppTypeParser(id, appType, context);
1962 if (parser.findDefaultApp()) {
1963 // Default app found. Replace it.
1964 intent = parser.parsedIntent;
1965 cn = intent.getComponent();
1966 ContentValues values = parser.parsedValues;
1967 values.put(LauncherSettings.Favorites.RESTORED, 0);
1968 updateItem(id, values);
1969 restored = false;
1970 itemReplaced = true;
Sunny Goyal94485362014-09-18 16:13:58 -07001971
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001972 } else if (REMOVE_UNRESTORED_ICONS) {
1973 Launcher.addDumpLog(TAG,
1974 "Unrestored package removed: " + cn, true);
1975 itemsToRemove.add(id);
1976 continue;
1977 }
Sunny Goyal94485362014-09-18 16:13:58 -07001978 } else if (REMOVE_UNRESTORED_ICONS) {
1979 Launcher.addDumpLog(TAG,
1980 "Unrestored package removed: " + cn, true);
1981 itemsToRemove.add(id);
1982 continue;
1983 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07001984 } else if (launcherApps.isAppEnabled(
1985 manager, cn.getPackageName(),
1986 PackageManager.GET_UNINSTALLED_PACKAGES)) {
1987 // Package is present but not available.
1988 allowMissingTarget = true;
1989 disabledState = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
1990 } else if (!isSdCardReady) {
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001991 // SdCard is not ready yet. Package might get available,
1992 // once it is ready.
1993 Launcher.addDumpLog(TAG, "Invalid package: " + cn
1994 + " (check again later)", true);
1995 HashSet<String> pkgs = sPendingPackages.get(user);
1996 if (pkgs == null) {
Sameer Padala513edae2014-07-29 16:17:08 -07001997 pkgs = new HashSet<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001998 sPendingPackages.put(user, pkgs);
1999 }
2000 pkgs.add(cn.getPackageName());
2001 allowMissingTarget = true;
2002 // Add the icon on the workspace anyway.
Sunny Goyal1a745e82014-10-02 15:58:31 -07002003
2004 } else {
2005 // Do not wait for external media load anymore.
2006 // Log the invalid package, and remove it
2007 Launcher.addDumpLog(TAG,
2008 "Invalid package removed: " + cn, true);
2009 itemsToRemove.add(id);
2010 continue;
Winson Chungee055712013-07-30 14:46:24 -07002011 }
Sunny Goyal938a53d2014-09-05 03:17:45 -07002012 } else if (cn == null) {
2013 // For shortcuts with no component, keep them as they are
2014 restoredRows.add(id);
2015 restored = false;
Winson Chungee055712013-07-30 14:46:24 -07002016 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002017 } catch (URISyntaxException e) {
Chris Wrenf4d08112014-01-16 18:13:56 -05002018 Launcher.addDumpLog(TAG,
2019 "Invalid uri: " + intentDescription, true);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002020 continue;
2021 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002022
Sunny Goyal34b65272015-03-11 16:56:52 -07002023 container = c.getInt(containerIndex);
2024 boolean useLowResIcon = container >= 0 &&
2025 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
2026
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002027 if (itemReplaced) {
2028 if (user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002029 info = getAppShortcutInfo(manager, intent, user, context, null,
Sunny Goyal34b65272015-03-11 16:56:52 -07002030 iconIndex, titleIndex, false, useLowResIcon);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002031 } else {
2032 // Don't replace items for other profiles.
2033 itemsToRemove.add(id);
2034 continue;
2035 }
2036 } else if (restored) {
Kenny Guyed131872014-04-30 03:02:21 +01002037 if (user.equals(UserHandleCompat.myUserHandle())) {
2038 Launcher.addDumpLog(TAG,
2039 "constructing info for partially restored package",
2040 true);
Sunny Goyal34b65272015-03-11 16:56:52 -07002041 info = getRestoredItemInfo(c, titleIndex, intent,
2042 promiseType, useLowResIcon);
Kenny Guyed131872014-04-30 03:02:21 +01002043 intent = getRestoredItemIntent(c, context, intent);
2044 } else {
2045 // Don't restore items for other profiles.
2046 itemsToRemove.add(id);
2047 continue;
2048 }
Chris Wrenf4d08112014-01-16 18:13:56 -05002049 } else if (itemType ==
2050 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002051 info = getAppShortcutInfo(manager, intent, user, context, c,
Sunny Goyal34b65272015-03-11 16:56:52 -07002052 iconIndex, titleIndex, allowMissingTarget, useLowResIcon);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002053 } else {
2054 info = getShortcutInfo(c, context, iconTypeIndex,
2055 iconPackageIndex, iconResourceIndex, iconIndex,
2056 titleIndex);
Michael Jurka96879562012-03-22 05:54:33 -07002057
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002058 // App shortcuts that used to be automatically added to Launcher
2059 // didn't always have the correct intent flags set, so do that
2060 // here
2061 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07002062 intent.getCategories() != null &&
2063 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07002064 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002065 intent.addFlags(
2066 Intent.FLAG_ACTIVITY_NEW_TASK |
2067 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
2068 }
Michael Jurka96879562012-03-22 05:54:33 -07002069 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002070
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002071 if (info != null) {
Winson Chungee055712013-07-30 14:46:24 -07002072 info.id = id;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002073 info.intent = intent;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002074 info.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002075 info.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002076 info.cellX = c.getInt(cellXIndex);
2077 info.cellY = c.getInt(cellYIndex);
Sunny Goyal08f72612015-01-05 13:41:43 -08002078 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002079 info.spanX = 1;
2080 info.spanY = 1;
Kenny Guyed131872014-04-30 03:02:21 +01002081 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, serialNumber);
Sunny Goyal1a745e82014-10-02 15:58:31 -07002082 info.isDisabled = disabledState;
2083 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
2084 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
2085 }
Adam Cohenae4409d2013-11-26 10:34:59 -08002086
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002087 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002088 if (!checkItemPlacement(occupied, info)) {
2089 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002090 break;
2091 }
2092
2093 switch (container) {
2094 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2095 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2096 sBgWorkspaceItems.add(info);
2097 break;
2098 default:
2099 // Item is in a user folder
2100 FolderInfo folderInfo =
2101 findOrMakeFolder(sBgFolders, container);
2102 folderInfo.add(info);
2103 break;
2104 }
2105 sBgItemsIdMap.put(info.id, info);
Winson Chung1323b482013-08-05 12:41:55 -07002106 } else {
2107 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002108 }
2109 break;
2110
2111 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2112 id = c.getLong(idIndex);
2113 FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
2114
2115 folderInfo.title = c.getString(titleIndex);
2116 folderInfo.id = id;
Joe Onorato9c1289c2009-08-17 11:03:03 -04002117 container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002118 folderInfo.container = container;
Adam Cohendcd297f2013-06-18 13:13:40 -07002119 folderInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002120 folderInfo.cellX = c.getInt(cellXIndex);
2121 folderInfo.cellY = c.getInt(cellYIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07002122 folderInfo.spanX = 1;
2123 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07002124 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002125
Daniel Sandler8802e962010-05-26 16:28:16 -04002126 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002127 if (!checkItemPlacement(occupied, folderInfo)) {
2128 itemsToRemove.add(id);
Daniel Sandler8802e962010-05-26 16:28:16 -04002129 break;
2130 }
Winson Chung5f8afe62013-08-12 16:19:28 -07002131
Joe Onorato9c1289c2009-08-17 11:03:03 -04002132 switch (container) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002133 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
2134 case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
2135 sBgWorkspaceItems.add(folderInfo);
2136 break;
Joe Onorato36115782010-06-17 13:28:48 -04002137 }
Joe Onorato17a89222011-02-08 17:26:11 -08002138
Chris Wrenf4d08112014-01-16 18:13:56 -05002139 if (restored) {
2140 // no special handling required for restored folders
2141 restoredRows.add(id);
2142 }
2143
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002144 sBgItemsIdMap.put(folderInfo.id, folderInfo);
2145 sBgFolders.put(folderInfo.id, folderInfo);
2146 break;
2147
2148 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08002149 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002150 // Read all Launcher-specific widget details
Adam Cohen59400422014-03-05 18:07:04 -08002151 boolean customWidget = itemType ==
2152 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
2153
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002154 int appWidgetId = c.getInt(appWidgetIdIndex);
Robin Lee26ace122015-03-16 19:41:43 +00002155 serialNumber= c.getLong(profileIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04002156 String savedProvider = c.getString(appWidgetProviderIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002157 id = c.getLong(idIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002158 final ComponentName component =
2159 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04002160
Sunny Goyal651077b2014-06-30 14:15:31 -07002161 final int restoreStatus = c.getInt(restoredIndex);
Sunny Goyalff572272014-07-23 13:58:07 -07002162 final boolean isIdValid = (restoreStatus &
2163 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) == 0;
Joe Onorato36115782010-06-17 13:28:48 -04002164
Sunny Goyalff572272014-07-23 13:58:07 -07002165 final boolean wasProviderReady = (restoreStatus &
2166 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0;
Sunny Goyal651077b2014-06-30 14:15:31 -07002167
Adam Cohen59400422014-03-05 18:07:04 -08002168 final LauncherAppWidgetProviderInfo provider =
2169 LauncherModel.getProviderInfo(context,
Robin Lee26ace122015-03-16 19:41:43 +00002170 ComponentName.unflattenFromString(savedProvider),
2171 mUserManager.getUserForSerialNumber(serialNumber));
Sunny Goyalff572272014-07-23 13:58:07 -07002172
2173 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08002174 if (!isSafeMode && !customWidget &&
2175 wasProviderReady && !isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002176 String log = "Deleting widget that isn't installed anymore: "
Sunny Goyalff572272014-07-23 13:58:07 -07002177 + "id=" + id + " appWidgetId=" + appWidgetId;
Adam Cohen59400422014-03-05 18:07:04 -08002178
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002179 Log.e(TAG, log);
Adam Cohen4caf2982013-08-20 18:54:31 -07002180 Launcher.addDumpLog(TAG, log, false);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002181 itemsToRemove.add(id);
2182 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07002183 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07002184 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
2185 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08002186
2187 if (!customWidget) {
2188 int[] minSpan =
2189 Launcher.getMinSpanForWidget(context, provider);
2190 appWidgetInfo.minSpanX = minSpan[0];
2191 appWidgetInfo.minSpanY = minSpan[1];
2192 }
Sunny Goyalff572272014-07-23 13:58:07 -07002193
2194 int status = restoreStatus;
2195 if (!wasProviderReady) {
2196 // If provider was not previously ready, update the
2197 // status and UI flag.
2198
2199 // Id would be valid only if the widget restore broadcast was received.
2200 if (isIdValid) {
2201 status = LauncherAppWidgetInfo.RESTORE_COMPLETED;
2202 } else {
2203 status &= ~LauncherAppWidgetInfo
2204 .FLAG_PROVIDER_NOT_READY;
2205 }
2206 }
2207 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07002208 } else {
2209 Log.v(TAG, "Widget restore pending id=" + id
2210 + " appWidgetId=" + appWidgetId
2211 + " status =" + restoreStatus);
2212 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07002213 component);
Sunny Goyal651077b2014-06-30 14:15:31 -07002214 appWidgetInfo.restoreStatus = restoreStatus;
Sunny Goyal94485362014-09-18 16:13:58 -07002215
2216 if ((restoreStatus & LauncherAppWidgetInfo.FLAG_RESTORE_STARTED) != 0) {
2217 // Restore has started once.
2218 } else if (installingPkgs.contains(component.getPackageName())) {
2219 // App restore has started. Update the flag
2220 appWidgetInfo.restoreStatus |=
2221 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyal9b4b0812014-10-08 10:47:28 -07002222 } else if (REMOVE_UNRESTORED_ICONS && !isSafeMode) {
Sunny Goyal94485362014-09-18 16:13:58 -07002223 Launcher.addDumpLog(TAG,
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002224 "Unrestored widget removed: " + component, true);
Sunny Goyal94485362014-09-18 16:13:58 -07002225 itemsToRemove.add(id);
2226 continue;
2227 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002228 }
Sunny Goyalff572272014-07-23 13:58:07 -07002229
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002230 appWidgetInfo.id = id;
Adam Cohendcd297f2013-06-18 13:13:40 -07002231 appWidgetInfo.screenId = c.getInt(screenIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002232 appWidgetInfo.cellX = c.getInt(cellXIndex);
2233 appWidgetInfo.cellY = c.getInt(cellYIndex);
2234 appWidgetInfo.spanX = c.getInt(spanXIndex);
2235 appWidgetInfo.spanY = c.getInt(spanYIndex);
Joe Onorato36115782010-06-17 13:28:48 -04002236
Adam Cohen59400422014-03-05 18:07:04 -08002237 if (!customWidget) {
2238 int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
2239 appWidgetInfo.minSpanX = minSpan[0];
2240 appWidgetInfo.minSpanY = minSpan[1];
2241 }
2242
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002243 container = c.getInt(containerIndex);
2244 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2245 container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2246 Log.e(TAG, "Widget found where container != " +
2247 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
2248 continue;
2249 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002250
Adam Cohene25af792013-06-06 23:08:25 -07002251 appWidgetInfo.container = c.getInt(containerIndex);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002252 // check & update map of what's occupied
Sunny Goyalfc0fe6b2014-10-16 12:18:37 -07002253 if (!checkItemPlacement(occupied, appWidgetInfo)) {
2254 itemsToRemove.add(id);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002255 break;
2256 }
Sunny Goyal651077b2014-06-30 14:15:31 -07002257
Adam Cohen59400422014-03-05 18:07:04 -08002258 if (!customWidget) {
2259 String providerName =
2260 appWidgetInfo.providerName.flattenToString();
2261 if (!providerName.equals(savedProvider) ||
2262 (appWidgetInfo.restoreStatus != restoreStatus)) {
2263 ContentValues values = new ContentValues();
2264 values.put(
2265 LauncherSettings.Favorites.APPWIDGET_PROVIDER,
2266 providerName);
2267 values.put(LauncherSettings.Favorites.RESTORED,
2268 appWidgetInfo.restoreStatus);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002269 updateItem(id, values);
Adam Cohen59400422014-03-05 18:07:04 -08002270 }
Chris Wrenc3919c02013-09-18 09:48:33 -04002271 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002272 sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
2273 sBgAppWidgets.add(appWidgetInfo);
2274 }
Joe Onorato36115782010-06-17 13:28:48 -04002275 break;
2276 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002277 } catch (Exception e) {
Dan Sandler295ae182013-12-10 16:05:47 -05002278 Launcher.addDumpLog(TAG, "Desktop items loading interrupted", e, true);
Romain Guy5c16f3e2010-01-12 17:24:58 -08002279 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002280 }
2281 } finally {
Daniel Sandler47b50312013-07-25 13:16:14 -04002282 if (c != null) {
2283 c.close();
2284 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002285 }
2286
Winson Chungba9c37f2013-08-30 14:11:37 -07002287 // Break early if we've stopped loading
2288 if (mStopped) {
Winson Chungba9c37f2013-08-30 14:11:37 -07002289 clearSBgDataStructures();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002290 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07002291 }
2292
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002293 if (itemsToRemove.size() > 0) {
2294 ContentProviderClient client = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002295 contentUri);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002296 // Remove dead items
2297 for (long id : itemsToRemove) {
2298 if (DEBUG_LOADERS) {
2299 Log.d(TAG, "Removed id = " + id);
2300 }
2301 // Don't notify content observers
2302 try {
2303 client.delete(LauncherSettings.Favorites.getContentUri(id, false),
2304 null, null);
2305 } catch (RemoteException e) {
2306 Log.w(TAG, "Could not remove id = " + id);
2307 }
Romain Guy5c16f3e2010-01-12 17:24:58 -08002308 }
2309 }
2310
Chris Wrenf4d08112014-01-16 18:13:56 -05002311 if (restoredRows.size() > 0) {
2312 ContentProviderClient updater = contentResolver.acquireContentProviderClient(
Sunny Goyalc5fb59f2014-09-25 16:20:38 -07002313 contentUri);
Chris Wrenf4d08112014-01-16 18:13:56 -05002314 // Update restored items that no longer require special handling
2315 try {
2316 StringBuilder selectionBuilder = new StringBuilder();
2317 selectionBuilder.append(LauncherSettings.Favorites._ID);
2318 selectionBuilder.append(" IN (");
2319 selectionBuilder.append(TextUtils.join(", ", restoredRows));
2320 selectionBuilder.append(")");
2321 ContentValues values = new ContentValues();
2322 values.put(LauncherSettings.Favorites.RESTORED, 0);
Sunny Goyal34942622014-08-29 17:20:55 -07002323 updater.update(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
Chris Wrenf4d08112014-01-16 18:13:56 -05002324 values, selectionBuilder.toString(), null);
2325 } catch (RemoteException e) {
2326 Log.w(TAG, "Could not update restored rows");
2327 }
2328 }
2329
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002330 if (!isSdCardReady && !sPendingPackages.isEmpty()) {
2331 context.registerReceiver(new AppsAvailabilityCheck(),
Sunny Goyal05e318d2014-07-29 11:49:35 -07002332 new IntentFilter(StartupReceiver.SYSTEM_READY),
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002333 null, sWorker);
2334 }
2335
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002336 sBgWorkspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
2337 // Log to disk
2338 Launcher.addDumpLog(TAG, "11683562 - sBgWorkspaceScreens: " +
2339 TextUtils.join(", ", sBgWorkspaceScreens), true);
Winson Chung9e6a0a22013-08-27 11:58:12 -07002340
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002341 // Remove any empty screens
2342 ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
2343 for (ItemInfo item: sBgItemsIdMap.values()) {
2344 long screenId = item.screenId;
2345 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
2346 unusedScreens.contains(screenId)) {
2347 unusedScreens.remove(screenId);
2348 }
2349 }
2350
2351 // If there are any empty screens remove them, and update.
2352 if (unusedScreens.size() != 0) {
2353 // Log to disk
2354 Launcher.addDumpLog(TAG, "11683562 - unusedScreens (to be removed): " +
2355 TextUtils.join(", ", unusedScreens), true);
2356
2357 sBgWorkspaceScreens.removeAll(unusedScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002358 updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07002359 }
2360
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002361 if (DEBUG_LOADERS) {
2362 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
2363 Log.d(TAG, "workspace layout: ");
Adam Cohendcd297f2013-06-18 13:13:40 -07002364 int nScreens = occupied.size();
Winson Chung892c74d2013-08-22 16:15:50 -07002365 for (int y = 0; y < countY; y++) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002366 String line = "";
Adam Cohendcd297f2013-06-18 13:13:40 -07002367
Daniel Sandler566da102013-06-25 23:43:45 -04002368 Iterator<Long> iter = occupied.keySet().iterator();
Winson Chungc9168342013-06-26 14:54:55 -07002369 while (iter.hasNext()) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002370 long screenId = iter.next();
Winson Chungc9168342013-06-26 14:54:55 -07002371 if (screenId > 0) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002372 line += " | ";
2373 }
Winson Chung892c74d2013-08-22 16:15:50 -07002374 for (int x = 0; x < countX; x++) {
Chris Wrenaeff7ea2014-02-14 16:59:24 -05002375 ItemInfo[][] screen = occupied.get(screenId);
2376 if (x < screen.length && y < screen[x].length) {
2377 line += (screen[x][y] != null) ? "#" : ".";
2378 } else {
2379 line += "!";
2380 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002381 }
Joe Onorato36115782010-06-17 13:28:48 -04002382 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002383 Log.d(TAG, "[ " + line + " ]");
Joe Onorato36115782010-06-17 13:28:48 -04002384 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04002385 }
Joe Onorato36115782010-06-17 13:28:48 -04002386 }
Adam Cohene25af792013-06-06 23:08:25 -07002387 }
2388
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08002389 /**
2390 * Partially updates the item without any notification. Must be called on the worker thread.
2391 */
2392 private void updateItem(long itemId, ContentValues update) {
2393 mContext.getContentResolver().update(
2394 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
2395 update,
2396 BaseColumns._ID + "= ?",
2397 new String[]{Long.toString(itemId)});
2398 }
2399
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002400 /** Filters the set of items who are directly or indirectly (via another container) on the
2401 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002402 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002403 ArrayList<ItemInfo> allWorkspaceItems,
2404 ArrayList<ItemInfo> currentScreenItems,
2405 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002406 // Purge any null ItemInfos
2407 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
2408 while (iter.hasNext()) {
2409 ItemInfo i = iter.next();
2410 if (i == null) {
2411 iter.remove();
2412 }
2413 }
2414
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002415 // Order the set of items by their containers first, this allows use to walk through the
2416 // list sequentially, build up a list of containers that are in the specified screen,
2417 // as well as all items in those containers.
2418 Set<Long> itemsOnScreen = new HashSet<Long>();
2419 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
2420 @Override
2421 public int compare(ItemInfo lhs, ItemInfo rhs) {
2422 return (int) (lhs.container - rhs.container);
2423 }
2424 });
2425 for (ItemInfo info : allWorkspaceItems) {
2426 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08002427 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002428 currentScreenItems.add(info);
2429 itemsOnScreen.add(info.id);
2430 } else {
2431 otherScreenItems.add(info);
2432 }
2433 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2434 currentScreenItems.add(info);
2435 itemsOnScreen.add(info.id);
2436 } else {
2437 if (itemsOnScreen.contains(info.container)) {
2438 currentScreenItems.add(info);
2439 itemsOnScreen.add(info.id);
2440 } else {
2441 otherScreenItems.add(info);
2442 }
2443 }
2444 }
2445 }
2446
2447 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002448 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002449 ArrayList<LauncherAppWidgetInfo> appWidgets,
2450 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
2451 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002452
2453 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07002454 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002455 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002456 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002457 currentScreenWidgets.add(widget);
2458 } else {
2459 otherScreenWidgets.add(widget);
2460 }
2461 }
2462 }
2463
2464 /** Filters the set of folders which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08002465 private void filterCurrentFolders(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002466 HashMap<Long, ItemInfo> itemsIdMap,
2467 HashMap<Long, FolderInfo> folders,
2468 HashMap<Long, FolderInfo> currentScreenFolders,
2469 HashMap<Long, FolderInfo> otherScreenFolders) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002470
2471 for (long id : folders.keySet()) {
2472 ItemInfo info = itemsIdMap.get(id);
2473 FolderInfo folder = folders.get(id);
Winson Chung2abf94d2012-07-18 18:16:38 -07002474 if (info == null || folder == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002475 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08002476 info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002477 currentScreenFolders.put(id, folder);
2478 } else {
2479 otherScreenFolders.put(id, folder);
2480 }
2481 }
2482 }
2483
2484 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
2485 * right) */
2486 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Winson Chung892c74d2013-08-22 16:15:50 -07002487 final LauncherAppState app = LauncherAppState.getInstance();
2488 final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002489 // XXX: review this
2490 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07002491 @Override
2492 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung892c74d2013-08-22 16:15:50 -07002493 int cellCountX = (int) grid.numColumns;
2494 int cellCountY = (int) grid.numRows;
Winson Chungdb8a8942012-04-03 14:08:41 -07002495 int screenOffset = cellCountX * cellCountY;
2496 int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
Adam Cohendcd297f2013-06-18 13:13:40 -07002497 long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002498 lhs.cellY * cellCountX + lhs.cellX);
Adam Cohendcd297f2013-06-18 13:13:40 -07002499 long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
Winson Chungdb8a8942012-04-03 14:08:41 -07002500 rhs.cellY * cellCountX + rhs.cellX);
2501 return (int) (lr - rr);
2502 }
2503 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002504 }
Winson Chungdb8a8942012-04-03 14:08:41 -07002505
Adam Cohendcd297f2013-06-18 13:13:40 -07002506 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
2507 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07002508 final Runnable r = new Runnable() {
2509 @Override
2510 public void run() {
2511 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2512 if (callbacks != null) {
2513 callbacks.bindScreens(orderedScreens);
2514 }
2515 }
2516 };
2517 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
2518 }
2519
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002520 private void bindWorkspaceItems(final Callbacks oldCallbacks,
2521 final ArrayList<ItemInfo> workspaceItems,
2522 final ArrayList<LauncherAppWidgetInfo> appWidgets,
2523 final HashMap<Long, FolderInfo> folders,
2524 ArrayList<Runnable> deferredBindRunnables) {
Winson Chung603bcb92011-09-02 11:45:39 -07002525
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002526 final boolean postOnMainThread = (deferredBindRunnables != null);
2527
2528 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07002529 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002530 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04002531 final int start = i;
2532 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002533 final Runnable r = new Runnable() {
2534 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04002535 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08002536 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002537 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07002538 callbacks.bindItems(workspaceItems, start, start+chunkSize,
2539 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04002540 }
2541 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002542 };
2543 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002544 synchronized (deferredBindRunnables) {
2545 deferredBindRunnables.add(r);
2546 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002547 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002548 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002549 }
Joe Onorato36115782010-06-17 13:28:48 -04002550 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002551
2552 // Bind the folders
2553 if (!folders.isEmpty()) {
2554 final Runnable r = new Runnable() {
2555 public void run() {
2556 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2557 if (callbacks != null) {
2558 callbacks.bindFolders(folders);
2559 }
2560 }
2561 };
2562 if (postOnMainThread) {
Jason Monka0a7a742014-04-22 09:23:19 -04002563 synchronized (deferredBindRunnables) {
2564 deferredBindRunnables.add(r);
2565 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002566 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002567 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002568 }
2569 }
2570
2571 // Bind the widgets, one at a time
2572 N = appWidgets.size();
2573 for (int i = 0; i < N; i++) {
2574 final LauncherAppWidgetInfo widget = appWidgets.get(i);
2575 final Runnable r = new Runnable() {
2576 public void run() {
2577 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2578 if (callbacks != null) {
2579 callbacks.bindAppWidget(widget);
2580 }
2581 }
2582 };
2583 if (postOnMainThread) {
2584 deferredBindRunnables.add(r);
2585 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002586 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002587 }
2588 }
2589 }
2590
2591 /**
2592 * Binds all loaded data to actual views on the main thread.
2593 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002594 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002595 final long t = SystemClock.uptimeMillis();
2596 Runnable r;
2597
2598 // Don't use these two variables in any of the callback runnables.
2599 // Otherwise we hold a reference to them.
2600 final Callbacks oldCallbacks = mCallbacks.get();
2601 if (oldCallbacks == null) {
2602 // This launcher has exited and nobody bothered to tell us. Just bail.
2603 Log.w(TAG, "LoaderTask running with no launcher");
2604 return;
2605 }
2606
Winson Chung9b9fb962013-11-15 15:39:34 -08002607 // Save a copy of all the bg-thread collections
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002608 ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
2609 ArrayList<LauncherAppWidgetInfo> appWidgets =
2610 new ArrayList<LauncherAppWidgetInfo>();
2611 HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
2612 HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
Adam Cohendcd297f2013-06-18 13:13:40 -07002613 ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
Winson Chung2abf94d2012-07-18 18:16:38 -07002614 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002615 workspaceItems.addAll(sBgWorkspaceItems);
2616 appWidgets.addAll(sBgAppWidgets);
2617 folders.putAll(sBgFolders);
2618 itemsIdMap.putAll(sBgItemsIdMap);
Adam Cohendcd297f2013-06-18 13:13:40 -07002619 orderedScreenIds.addAll(sBgWorkspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002620 }
2621
Derek Prothro7aff3992013-12-10 14:00:37 -05002622 final boolean isLoadingSynchronously =
2623 synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE;
Adam Cohend8dbb462013-11-27 11:55:48 -08002624 int currScreen = isLoadingSynchronously ? synchronizeBindPage :
Winson Chung9b9fb962013-11-15 15:39:34 -08002625 oldCallbacks.getCurrentWorkspaceScreen();
Adam Cohend8dbb462013-11-27 11:55:48 -08002626 if (currScreen >= orderedScreenIds.size()) {
2627 // There may be no workspace screens (just hotseat items and an empty page).
Derek Prothro7aff3992013-12-10 14:00:37 -05002628 currScreen = PagedView.INVALID_RESTORE_PAGE;
Winson Chung9b9fb962013-11-15 15:39:34 -08002629 }
Adam Cohend8dbb462013-11-27 11:55:48 -08002630 final int currentScreen = currScreen;
Derek Prothro7aff3992013-12-10 14:00:37 -05002631 final long currentScreenId = currentScreen < 0
2632 ? INVALID_SCREEN_ID : orderedScreenIds.get(currentScreen);
Winson Chung9b9fb962013-11-15 15:39:34 -08002633
2634 // Load all the items that are on the current page first (and in the process, unbind
2635 // all the existing workspace items before we call startBinding() below.
2636 unbindWorkspaceItemsOnMainThread();
2637
2638 // Separate the items that are on the current screen, and all the other remaining items
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002639 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
2640 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
2641 ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
2642 new ArrayList<LauncherAppWidgetInfo>();
2643 ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
2644 new ArrayList<LauncherAppWidgetInfo>();
2645 HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
2646 HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
2647
Winson Chung9b9fb962013-11-15 15:39:34 -08002648 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002649 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08002650 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002651 otherAppWidgets);
Winson Chung9b9fb962013-11-15 15:39:34 -08002652 filterCurrentFolders(currentScreenId, itemsIdMap, folders, currentFolders,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002653 otherFolders);
2654 sortWorkspaceItemsSpatially(currentWorkspaceItems);
2655 sortWorkspaceItemsSpatially(otherWorkspaceItems);
2656
2657 // Tell the workspace that we're about to start binding items
2658 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002659 public void run() {
2660 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2661 if (callbacks != null) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002662 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04002663 }
2664 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002665 };
Winson Chung81b52252012-08-27 15:34:29 -07002666 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002667
Adam Cohendcd297f2013-06-18 13:13:40 -07002668 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
2669
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002670 // Load items on the current page
2671 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
2672 currentFolders, null);
Adam Cohen1462de32012-07-24 22:34:36 -07002673 if (isLoadingSynchronously) {
2674 r = new Runnable() {
2675 public void run() {
2676 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Derek Prothro7aff3992013-12-10 14:00:37 -05002677 if (callbacks != null && currentScreen != PagedView.INVALID_RESTORE_PAGE) {
Adam Cohen1462de32012-07-24 22:34:36 -07002678 callbacks.onPageBoundSynchronously(currentScreen);
2679 }
2680 }
2681 };
Winson Chung81b52252012-08-27 15:34:29 -07002682 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Adam Cohen1462de32012-07-24 22:34:36 -07002683 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002684
Winson Chung4a2afa32012-07-19 14:53:05 -07002685 // Load all the remaining pages (if we are loading synchronously, we want to defer this
2686 // work until after the first render)
Jason Monka0a7a742014-04-22 09:23:19 -04002687 synchronized (mDeferredBindRunnables) {
2688 mDeferredBindRunnables.clear();
2689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002690 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
Winson Chung4a2afa32012-07-19 14:53:05 -07002691 (isLoadingSynchronously ? mDeferredBindRunnables : null));
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002692
2693 // Tell the workspace that we're done binding items
2694 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002695 public void run() {
2696 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2697 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08002698 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04002699 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002700
Winson Chung98e030b2012-05-07 16:01:11 -07002701 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04002702 if (DEBUG_LOADERS) {
2703 Log.d(TAG, "bound workspace in "
2704 + (SystemClock.uptimeMillis()-t) + "ms");
2705 }
Winson Chung36a62fe2012-05-06 18:04:42 -07002706
2707 mIsLoadingAndBindingWorkspace = false;
Joe Onorato36115782010-06-17 13:28:48 -04002708 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002709 };
Winson Chung4a2afa32012-07-19 14:53:05 -07002710 if (isLoadingSynchronously) {
Jason Monka0a7a742014-04-22 09:23:19 -04002711 synchronized (mDeferredBindRunnables) {
2712 mDeferredBindRunnables.add(r);
2713 }
Winson Chung4a2afa32012-07-19 14:53:05 -07002714 } else {
Winson Chung81b52252012-08-27 15:34:29 -07002715 runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
Winson Chung4a2afa32012-07-19 14:53:05 -07002716 }
Joe Onorato36115782010-06-17 13:28:48 -04002717 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002718
Joe Onorato36115782010-06-17 13:28:48 -04002719 private void loadAndBindAllApps() {
2720 if (DEBUG_LOADERS) {
2721 Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
2722 }
2723 if (!mAllAppsLoaded) {
Winson Chung64359a52013-07-08 17:17:08 -07002724 loadAllApps();
Reena Lee93f824a2011-09-23 17:20:28 -07002725 synchronized (LoaderTask.this) {
2726 if (mStopped) {
2727 return;
2728 }
2729 mAllAppsLoaded = true;
Joe Onoratocc67f472010-06-08 10:54:30 -07002730 }
Joe Onorato36115782010-06-17 13:28:48 -04002731 } else {
2732 onlyBindAllApps();
2733 }
2734 }
Joe Onoratocc67f472010-06-08 10:54:30 -07002735
Joe Onorato36115782010-06-17 13:28:48 -04002736 private void onlyBindAllApps() {
2737 final Callbacks oldCallbacks = mCallbacks.get();
2738 if (oldCallbacks == null) {
2739 // This launcher has exited and nobody bothered to tell us. Just bail.
2740 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
2741 return;
2742 }
2743
2744 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07002745 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002746 final ArrayList<AppInfo> list
2747 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07002748 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04002749 public void run() {
2750 final long t = SystemClock.uptimeMillis();
2751 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
2752 if (callbacks != null) {
2753 callbacks.bindAllApplications(list);
2754 }
2755 if (DEBUG_LOADERS) {
2756 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
2757 + (SystemClock.uptimeMillis()-t) + "ms");
2758 }
2759 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07002760 };
2761 boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
Winson Chung64359a52013-07-08 17:17:08 -07002762 if (isRunningOnMainThread) {
Winson Chungc93e5ae2012-07-23 20:48:26 -07002763 r.run();
2764 } else {
2765 mHandler.post(r);
2766 }
Joe Onorato36115782010-06-17 13:28:48 -04002767 }
2768
Winson Chung64359a52013-07-08 17:17:08 -07002769 private void loadAllApps() {
2770 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04002771
Joe Onorato36115782010-06-17 13:28:48 -04002772 final Callbacks oldCallbacks = mCallbacks.get();
2773 if (oldCallbacks == null) {
2774 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07002775 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04002776 return;
2777 }
2778
2779 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2780 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2781
Kenny Guyed131872014-04-30 03:02:21 +01002782 final List<UserHandleCompat> profiles = mUserManager.getUserProfiles();
2783
Winson Chung64359a52013-07-08 17:17:08 -07002784 // Clear the list of apps
2785 mBgAllAppsList.clear();
Sunny Goyale0f58d72014-11-10 18:05:31 -08002786 SharedPreferences prefs = mContext.getSharedPreferences(
2787 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Kenny Guyed131872014-04-30 03:02:21 +01002788 for (UserHandleCompat user : profiles) {
2789 // Query for the set of apps
2790 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
2791 List<LauncherActivityInfoCompat> apps = mLauncherApps.getActivityList(null, user);
2792 if (DEBUG_LOADERS) {
2793 Log.d(TAG, "getActivityList took "
2794 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
2795 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
2796 }
2797 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08002798 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01002799 if (apps == null || apps.isEmpty()) {
2800 return;
2801 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002802
2803 // Update icon cache
2804 HashSet<String> updatedPackages = mIconCache.updateDBIcons(user, apps);
2805
2806 // If any package icon has changed (app was updated while launcher was dead),
2807 // update the corresponding shortcuts.
2808 if (!updatedPackages.isEmpty()) {
2809 final ArrayList<ShortcutInfo> updates = new ArrayList<ShortcutInfo>();
2810 synchronized (sBgLock) {
2811 for (ItemInfo info : sBgItemsIdMap.values()) {
2812 if (info instanceof ShortcutInfo && user.equals(info.user)
2813 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
2814 ShortcutInfo si = (ShortcutInfo) info;
2815 ComponentName cn = si.getTargetComponent();
2816 if (cn != null && updatedPackages.contains(cn.getPackageName())) {
2817 si.updateIcon(mIconCache);
2818 updates.add(si);
2819 }
2820 }
2821 }
2822 }
2823
2824 if (!updates.isEmpty()) {
2825 final UserHandleCompat userFinal = user;
2826 mHandler.post(new Runnable() {
2827
2828 public void run() {
2829 Callbacks cb = getCallback();
2830 if (cb != null) {
2831 cb.bindShortcutsChanged(
2832 updates, new ArrayList<ShortcutInfo>(), userFinal);
2833 }
2834 }
2835 });
2836 }
Kenny Guyed131872014-04-30 03:02:21 +01002837 }
Joe Onorato36115782010-06-17 13:28:48 -04002838
Kenny Guyed131872014-04-30 03:02:21 +01002839 // Create the ApplicationInfos
2840 for (int i = 0; i < apps.size(); i++) {
2841 LauncherActivityInfoCompat app = apps.get(i);
2842 // This builds the icon bitmaps.
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002843 mBgAllAppsList.add(new AppInfo(mContext, app, user, mIconCache));
Kenny Guyed131872014-04-30 03:02:21 +01002844 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002845
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002846 if (ADD_MANAGED_PROFILE_SHORTCUTS && !user.equals(UserHandleCompat.myUserHandle())) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002847 // Add shortcuts for packages which were installed while launcher was dead.
2848 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2849 + mUserManager.getSerialNumberForUser(user);
2850 Set<String> packagesAdded = prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET);
2851 HashSet<String> newPackageSet = new HashSet<String>();
2852
2853 for (LauncherActivityInfoCompat info : apps) {
2854 String packageName = info.getComponentName().getPackageName();
2855 if (!packagesAdded.contains(packageName)
2856 && !newPackageSet.contains(packageName)) {
2857 InstallShortcutReceiver.queueInstallShortcut(info, mContext);
2858 }
2859 newPackageSet.add(packageName);
2860 }
2861
2862 prefs.edit().putStringSet(shortcutsSetKey, newPackageSet).commit();
2863 }
Winson Chung64359a52013-07-08 17:17:08 -07002864 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01002865 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02002866 final ArrayList<AppInfo> added = mBgAllAppsList.added;
2867 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07002868
2869 // Post callback on main thread
2870 mHandler.post(new Runnable() {
2871 public void run() {
2872 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07002873 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07002874 if (callbacks != null) {
2875 callbacks.bindAllApplications(added);
2876 if (DEBUG_LOADERS) {
2877 Log.d(TAG, "bound " + added.size() + " apps in "
2878 + (SystemClock.uptimeMillis() - bindTime) + "ms");
2879 }
2880 } else {
2881 Log.i(TAG, "not binding apps: no Launcher activity");
2882 }
2883 }
2884 });
2885
Joe Onorato36115782010-06-17 13:28:48 -04002886 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07002887 Log.d(TAG, "Icons processed in "
2888 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08002889 }
2890 }
2891
2892 public void dumpState() {
Winson Chung2abf94d2012-07-18 18:16:38 -07002893 synchronized (sBgLock) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07002894 Log.d(TAG, "mLoaderTask.mContext=" + mContext);
2895 Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
2896 Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
2897 Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
2898 Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
2899 }
Joe Onorato36115782010-06-17 13:28:48 -04002900 }
2901 }
2902
2903 void enqueuePackageUpdated(PackageUpdatedTask task) {
Brad Fitzpatrick700889f2010-10-11 09:40:44 -07002904 sWorker.post(task);
Joe Onorato36115782010-06-17 13:28:48 -04002905 }
2906
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002907 private class AppsAvailabilityCheck extends BroadcastReceiver {
2908
2909 @Override
2910 public void onReceive(Context context, Intent intent) {
2911 synchronized (sBgLock) {
2912 final LauncherAppsCompat launcherApps = LauncherAppsCompat
2913 .getInstance(mApp.getContext());
Sunny Goyal1a745e82014-10-02 15:58:31 -07002914 final PackageManager manager = context.getPackageManager();
2915 final ArrayList<String> packagesRemoved = new ArrayList<String>();
2916 final ArrayList<String> packagesUnavailable = new ArrayList<String>();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002917 for (Entry<UserHandleCompat, HashSet<String>> entry : sPendingPackages.entrySet()) {
2918 UserHandleCompat user = entry.getKey();
Sunny Goyal1a745e82014-10-02 15:58:31 -07002919 packagesRemoved.clear();
2920 packagesUnavailable.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002921 for (String pkg : entry.getValue()) {
2922 if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07002923 boolean packageOnSdcard = launcherApps.isAppEnabled(
2924 manager, pkg, PackageManager.GET_UNINSTALLED_PACKAGES);
2925 if (packageOnSdcard) {
2926 Launcher.addDumpLog(TAG, "Package found on sd-card: " + pkg, true);
2927 packagesUnavailable.add(pkg);
2928 } else {
2929 Launcher.addDumpLog(TAG, "Package not found: " + pkg, true);
2930 packagesRemoved.add(pkg);
2931 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002932 }
2933 }
2934 if (!packagesRemoved.isEmpty()) {
2935 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_REMOVE,
2936 packagesRemoved.toArray(new String[packagesRemoved.size()]), user));
2937 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07002938 if (!packagesUnavailable.isEmpty()) {
2939 enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_UNAVAILABLE,
2940 packagesUnavailable.toArray(new String[packagesUnavailable.size()]), user));
2941 }
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002942 }
Sunny Goyal34942622014-08-29 17:20:55 -07002943 sPendingPackages.clear();
Sunny Goyalf599ccf2014-07-08 13:01:29 -07002944 }
2945 }
2946 }
2947
Joe Onorato36115782010-06-17 13:28:48 -04002948 private class PackageUpdatedTask implements Runnable {
2949 int mOp;
2950 String[] mPackages;
Kenny Guyed131872014-04-30 03:02:21 +01002951 UserHandleCompat mUser;
Joe Onorato36115782010-06-17 13:28:48 -04002952
2953 public static final int OP_NONE = 0;
2954 public static final int OP_ADD = 1;
2955 public static final int OP_UPDATE = 2;
2956 public static final int OP_REMOVE = 3; // uninstlled
2957 public static final int OP_UNAVAILABLE = 4; // external media unmounted
2958
2959
Kenny Guyed131872014-04-30 03:02:21 +01002960 public PackageUpdatedTask(int op, String[] packages, UserHandleCompat user) {
Joe Onorato36115782010-06-17 13:28:48 -04002961 mOp = op;
2962 mPackages = packages;
Kenny Guyed131872014-04-30 03:02:21 +01002963 mUser = user;
Joe Onorato36115782010-06-17 13:28:48 -04002964 }
2965
2966 public void run() {
Daniel Sandlercc8befa2013-06-11 14:45:48 -04002967 final Context context = mApp.getContext();
Joe Onorato36115782010-06-17 13:28:48 -04002968
2969 final String[] packages = mPackages;
2970 final int N = packages.length;
2971 switch (mOp) {
2972 case OP_ADD:
2973 for (int i=0; i<N; i++) {
2974 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08002975 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01002976 mBgAllAppsList.addPackage(context, packages[i], mUser);
Joe Onorato36115782010-06-17 13:28:48 -04002977 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08002978
2979 // Auto add shortcuts for added packages.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08002980 if (ADD_MANAGED_PROFILE_SHORTCUTS
2981 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08002982 SharedPreferences prefs = context.getSharedPreferences(
2983 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
2984 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
2985 + mUserManager.getSerialNumberForUser(mUser);
2986 Set<String> shortcutSet = new HashSet<String>(
2987 prefs.getStringSet(shortcutsSetKey,Collections.EMPTY_SET));
2988
2989 for (int i=0; i<N; i++) {
2990 if (!shortcutSet.contains(packages[i])) {
2991 shortcutSet.add(packages[i]);
2992 List<LauncherActivityInfoCompat> activities =
2993 mLauncherApps.getActivityList(packages[i], mUser);
2994 if (activities != null && !activities.isEmpty()) {
2995 InstallShortcutReceiver.queueInstallShortcut(
2996 activities.get(0), context);
2997 }
2998 }
2999 }
3000
3001 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3002 }
Joe Onorato36115782010-06-17 13:28:48 -04003003 break;
3004 case OP_UPDATE:
3005 for (int i=0; i<N; i++) {
3006 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003007 mIconCache.updateIconsForPkg(packages[i], mUser);
Kenny Guyed131872014-04-30 03:02:21 +01003008 mBgAllAppsList.updatePackage(context, packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003009 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003010 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003011 }
3012 break;
3013 case OP_REMOVE:
Sunny Goyale0f58d72014-11-10 18:05:31 -08003014 // Remove the packageName for the set of auto-installed shortcuts. This
3015 // will ensure that the shortcut when the app is installed again.
Sunny Goyal2a66bbf2014-11-20 17:01:00 -08003016 if (ADD_MANAGED_PROFILE_SHORTCUTS
3017 && !UserHandleCompat.myUserHandle().equals(mUser)) {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003018 SharedPreferences prefs = context.getSharedPreferences(
3019 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
3020 String shortcutsSetKey = INSTALLED_SHORTCUTS_SET_PREFIX
3021 + mUserManager.getSerialNumberForUser(mUser);
3022 HashSet<String> shortcutSet = new HashSet<String>(
3023 prefs.getStringSet(shortcutsSetKey, Collections.EMPTY_SET));
3024 shortcutSet.removeAll(Arrays.asList(mPackages));
3025 prefs.edit().putStringSet(shortcutsSetKey, shortcutSet).commit();
3026 }
Joe Onorato36115782010-06-17 13:28:48 -04003027 for (int i=0; i<N; i++) {
3028 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003029 mIconCache.removeIconsForPkg(packages[i], mUser);
3030 }
3031 // Fall through
3032 case OP_UNAVAILABLE:
3033 for (int i=0; i<N; i++) {
3034 if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
3035 mBgAllAppsList.removePackage(packages[i], mUser);
Michael Jurkaeb1bb922013-09-26 11:29:01 -07003036 WidgetPreviewLoader.removePackageFromDb(
Daniel Sandlere4f98912013-06-25 15:13:26 -04003037 mApp.getWidgetPreviewCacheDb(), packages[i]);
Joe Onorato36115782010-06-17 13:28:48 -04003038 }
3039 break;
3040 }
3041
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003042 ArrayList<AppInfo> added = null;
3043 ArrayList<AppInfo> modified = null;
3044 final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>();
Joe Onorato36115782010-06-17 13:28:48 -04003045
Adam Cohen487f7dd2012-06-28 18:12:10 -07003046 if (mBgAllAppsList.added.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003047 added = new ArrayList<AppInfo>(mBgAllAppsList.added);
Winson Chung5d55f332012-07-16 20:45:03 -07003048 mBgAllAppsList.added.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003049 }
Adam Cohen487f7dd2012-06-28 18:12:10 -07003050 if (mBgAllAppsList.modified.size() > 0) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003051 modified = new ArrayList<AppInfo>(mBgAllAppsList.modified);
Winson Chung5d55f332012-07-16 20:45:03 -07003052 mBgAllAppsList.modified.clear();
Joe Onorato36115782010-06-17 13:28:48 -04003053 }
Winson Chung5d55f332012-07-16 20:45:03 -07003054 if (mBgAllAppsList.removed.size() > 0) {
Winson Chung83892cc2013-05-01 16:53:33 -07003055 removedApps.addAll(mBgAllAppsList.removed);
Winson Chung5d55f332012-07-16 20:45:03 -07003056 mBgAllAppsList.removed.clear();
Winson Chungcd810732012-06-18 16:45:43 -07003057 }
3058
Sunny Goyale0f58d72014-11-10 18:05:31 -08003059 final Callbacks callbacks = getCallback();
Joe Onorato36115782010-06-17 13:28:48 -04003060 if (callbacks == null) {
3061 Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
3062 return;
3063 }
3064
Sunny Goyal4390ace2014-10-13 11:33:11 -07003065 final HashMap<ComponentName, AppInfo> addedOrUpdatedApps =
3066 new HashMap<ComponentName, AppInfo>();
3067
Joe Onorato36115782010-06-17 13:28:48 -04003068 if (added != null) {
Sunny Goyalc9acdd52015-02-26 12:34:42 -08003069 addAppsToAllApps(context, added);
Sunny Goyal4390ace2014-10-13 11:33:11 -07003070 for (AppInfo ai : added) {
3071 addedOrUpdatedApps.put(ai.componentName, ai);
3072 }
Joe Onorato36115782010-06-17 13:28:48 -04003073 }
Adam Cohen76a47a12014-02-05 11:47:43 -08003074
Joe Onorato36115782010-06-17 13:28:48 -04003075 if (modified != null) {
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003076 final ArrayList<AppInfo> modifiedFinal = modified;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003077 for (AppInfo ai : modified) {
3078 addedOrUpdatedApps.put(ai.componentName, ai);
Winson Chung64359a52013-07-08 17:17:08 -07003079 }
3080
Joe Onorato36115782010-06-17 13:28:48 -04003081 mHandler.post(new Runnable() {
3082 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003083 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003084 if (callbacks == cb && cb != null) {
Joe Onorato36115782010-06-17 13:28:48 -04003085 callbacks.bindAppsUpdated(modifiedFinal);
3086 }
3087 }
3088 });
3089 }
Winson Chung83892cc2013-05-01 16:53:33 -07003090
Sunny Goyal4390ace2014-10-13 11:33:11 -07003091 // Update shortcut infos
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003092 if (mOp == OP_ADD || mOp == OP_UPDATE) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003093 final ArrayList<ShortcutInfo> updatedShortcuts = new ArrayList<ShortcutInfo>();
3094 final ArrayList<ShortcutInfo> removedShortcuts = new ArrayList<ShortcutInfo>();
3095 final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<LauncherAppWidgetInfo>();
3096
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003097 HashSet<String> packageSet = new HashSet<String>(Arrays.asList(packages));
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003098 synchronized (sBgLock) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003099 for (ItemInfo info : sBgItemsIdMap.values()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003100 if (info instanceof ShortcutInfo && mUser.equals(info.user)) {
3101 ShortcutInfo si = (ShortcutInfo) info;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003102 boolean infoUpdated = false;
3103 boolean shortcutUpdated = false;
3104
3105 // Update shortcuts which use iconResource.
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003106 if ((si.iconResource != null)
Sunny Goyal4390ace2014-10-13 11:33:11 -07003107 && packageSet.contains(si.iconResource.packageName)) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003108 Bitmap icon = Utilities.createIconBitmap(si.iconResource.packageName,
3109 si.iconResource.resourceName, mIconCache, context);
3110 if (icon != null) {
3111 si.setIcon(icon);
3112 si.usingFallbackIcon = false;
Sunny Goyal4390ace2014-10-13 11:33:11 -07003113 infoUpdated = true;
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003114 }
3115 }
Sunny Goyal4390ace2014-10-13 11:33:11 -07003116
3117 ComponentName cn = si.getTargetComponent();
3118 if (cn != null && packageSet.contains(cn.getPackageName())) {
3119 AppInfo appInfo = addedOrUpdatedApps.get(cn);
3120
3121 if (si.isPromise()) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003122 if (si.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
3123 // Auto install icon
3124 PackageManager pm = context.getPackageManager();
3125 ResolveInfo matched = pm.resolveActivity(
3126 new Intent(Intent.ACTION_MAIN)
3127 .setComponent(cn).addCategory(Intent.CATEGORY_LAUNCHER),
3128 PackageManager.MATCH_DEFAULT_ONLY);
3129 if (matched == null) {
3130 // Try to find the best match activity.
3131 Intent intent = pm.getLaunchIntentForPackage(
3132 cn.getPackageName());
3133 if (intent != null) {
3134 cn = intent.getComponent();
3135 appInfo = addedOrUpdatedApps.get(cn);
3136 }
3137
3138 if ((intent == null) || (appInfo == null)) {
3139 removedShortcuts.add(si);
3140 continue;
3141 }
3142 si.promisedIntent = intent;
3143 }
3144 }
3145
3146 // Restore the shortcut.
3147 si.intent = si.promisedIntent;
3148 si.promisedIntent = null;
3149 si.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
3150 & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
3151 & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
3152
3153 infoUpdated = true;
3154 si.updateIcon(mIconCache);
3155 }
3156
3157 if (appInfo != null && Intent.ACTION_MAIN.equals(si.intent.getAction())
3158 && si.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
3159 si.updateIcon(mIconCache);
3160 si.title = appInfo.title.toString();
3161 si.contentDescription = appInfo.contentDescription;
3162 infoUpdated = true;
3163 }
3164
3165 if ((si.isDisabled & ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE) != 0) {
3166 // Since package was just updated, the target must be available now.
3167 si.isDisabled &= ~ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3168 shortcutUpdated = true;
3169 }
3170 }
3171
3172 if (infoUpdated || shortcutUpdated) {
3173 updatedShortcuts.add(si);
3174 }
3175 if (infoUpdated) {
3176 updateItemInDatabase(context, si);
3177 }
3178 } else if (info instanceof LauncherAppWidgetInfo) {
3179 LauncherAppWidgetInfo widgetInfo = (LauncherAppWidgetInfo) info;
3180 if (mUser.equals(widgetInfo.user)
3181 && widgetInfo.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
3182 && packageSet.contains(widgetInfo.providerName.getPackageName())) {
3183 widgetInfo.restoreStatus &= ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
3184 widgets.add(widgetInfo);
3185 updateItemInDatabase(context, widgetInfo);
3186 }
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003187 }
3188 }
3189 }
3190
Sunny Goyal4390ace2014-10-13 11:33:11 -07003191 if (!updatedShortcuts.isEmpty() || !removedShortcuts.isEmpty()) {
3192 mHandler.post(new Runnable() {
3193
3194 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003195 Callbacks cb = getCallback();
Sunny Goyal4390ace2014-10-13 11:33:11 -07003196 if (callbacks == cb && cb != null) {
3197 callbacks.bindShortcutsChanged(
3198 updatedShortcuts, removedShortcuts, mUser);
3199 }
3200 }
3201 });
3202 if (!removedShortcuts.isEmpty()) {
3203 deleteItemsFromDatabase(context, removedShortcuts);
3204 }
3205 }
3206 if (!widgets.isEmpty()) {
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003207 mHandler.post(new Runnable() {
3208 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003209 Callbacks cb = getCallback();
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003210 if (callbacks == cb && cb != null) {
Sunny Goyal4390ace2014-10-13 11:33:11 -07003211 callbacks.bindWidgetsRestored(widgets);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003212 }
3213 }
3214 });
3215 }
3216 }
3217
Winson Chungdf95eb12013-10-16 14:57:07 -07003218 final ArrayList<String> removedPackageNames =
3219 new ArrayList<String>();
Sunny Goyal1a745e82014-10-02 15:58:31 -07003220 if (mOp == OP_REMOVE || mOp == OP_UNAVAILABLE) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003221 // Mark all packages in the broadcast to be removed
3222 removedPackageNames.addAll(Arrays.asList(packages));
3223 } else if (mOp == OP_UPDATE) {
3224 // Mark disabled packages in the broadcast to be removed
Winson Chungdf95eb12013-10-16 14:57:07 -07003225 for (int i=0; i<N; i++) {
Kenny Guyed131872014-04-30 03:02:21 +01003226 if (isPackageDisabled(context, packages[i], mUser)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003227 removedPackageNames.add(packages[i]);
Winson Chung64359a52013-07-08 17:17:08 -07003228 }
3229 }
Winson Chungdf95eb12013-10-16 14:57:07 -07003230 }
Sunny Goyal1a745e82014-10-02 15:58:31 -07003231
Winson Chungdf95eb12013-10-16 14:57:07 -07003232 if (!removedPackageNames.isEmpty() || !removedApps.isEmpty()) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003233 final int removeReason;
3234 if (mOp == OP_UNAVAILABLE) {
3235 removeReason = ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
3236 } else {
3237 // Remove all the components associated with this package
3238 for (String pn : removedPackageNames) {
3239 deletePackageFromDatabase(context, pn, mUser);
3240 }
3241 // Remove all the specific components
3242 for (AppInfo a : removedApps) {
3243 ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName, mUser);
3244 deleteItemsFromDatabase(context, infos);
3245 }
3246 removeReason = 0;
3247 }
3248
Winson Chungdf95eb12013-10-16 14:57:07 -07003249 // Remove any queued items from the install queue
Sunny Goyale0f58d72014-11-10 18:05:31 -08003250 InstallShortcutReceiver.removeFromInstallQueue(context, removedPackageNames, mUser);
Winson Chungdf95eb12013-10-16 14:57:07 -07003251 // Call the components-removed callback
Joe Onorato36115782010-06-17 13:28:48 -04003252 mHandler.post(new Runnable() {
3253 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003254 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003255 if (callbacks == cb && cb != null) {
Sunny Goyal1a745e82014-10-02 15:58:31 -07003256 callbacks.bindComponentsRemoved(
3257 removedPackageNames, removedApps, mUser, removeReason);
Joe Onorato36115782010-06-17 13:28:48 -04003258 }
3259 }
3260 });
Joe Onoratobe386092009-11-17 17:32:16 -08003261 }
Winson Chung80baf5a2010-08-09 16:03:15 -07003262
Michael Jurkac402cd92013-05-20 15:49:32 +02003263 final ArrayList<Object> widgetsAndShortcuts =
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003264 getSortedWidgetsAndShortcuts(context, true /* refresh */);
Winson Chung80baf5a2010-08-09 16:03:15 -07003265 mHandler.post(new Runnable() {
3266 @Override
3267 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003268 Callbacks cb = getCallback();
Winson Chungcd2b0142011-06-08 16:02:26 -07003269 if (callbacks == cb && cb != null) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003270 callbacks.bindPackagesUpdated(widgetsAndShortcuts);
Winson Chung80baf5a2010-08-09 16:03:15 -07003271 }
3272 }
3273 });
Adam Cohen4caf2982013-08-20 18:54:31 -07003274
3275 // Write all the logs to disk
Adam Cohen4caf2982013-08-20 18:54:31 -07003276 mHandler.post(new Runnable() {
3277 public void run() {
Sunny Goyale0f58d72014-11-10 18:05:31 -08003278 Callbacks cb = getCallback();
Adam Cohen4caf2982013-08-20 18:54:31 -07003279 if (callbacks == cb && cb != null) {
Winson Chungede41292013-09-19 16:27:36 -07003280 callbacks.dumpLogsToLocalData();
Adam Cohen4caf2982013-08-20 18:54:31 -07003281 }
3282 }
3283 });
Joe Onorato9c1289c2009-08-17 11:03:03 -04003284 }
3285 }
3286
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003287 public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
3288 boolean refresh) {
Adam Cohen59400422014-03-05 18:07:04 -08003289 synchronized (sBgLock) {
Robin Lee26ace122015-03-16 19:41:43 +00003290 if (sBgWidgetProviders == null || refresh) {
3291 sBgWidgetProviders = new HashMap<>();
3292 AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
3293 LauncherAppWidgetProviderInfo info;
Adam Cohen59400422014-03-05 18:07:04 -08003294
Robin Lee26ace122015-03-16 19:41:43 +00003295 List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
3296 for (AppWidgetProviderInfo pInfo : widgets) {
3297 info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
3298 UserHandleCompat user = wm.getUser(info);
3299 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3300 }
3301
3302 Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
3303 for (CustomAppWidget widget : customWidgets) {
3304 info = new LauncherAppWidgetProviderInfo(context, widget);
3305 UserHandleCompat user = wm.getUser(info);
3306 sBgWidgetProviders.put(new ComponentKey(info.provider, user), info);
3307 }
Adam Cohen59400422014-03-05 18:07:04 -08003308 }
Adam Cohen59400422014-03-05 18:07:04 -08003309 return new ArrayList<LauncherAppWidgetProviderInfo>(sBgWidgetProviders.values());
3310 }
3311 }
3312
Robin Lee26ace122015-03-16 19:41:43 +00003313 public static LauncherAppWidgetProviderInfo getProviderInfo(Context ctx, ComponentName name,
3314 UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08003315 synchronized (sBgLock) {
3316 if (sBgWidgetProviders == null) {
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003317 getWidgetProviders(ctx, false /* refresh */);
Adam Cohen59400422014-03-05 18:07:04 -08003318 }
Robin Lee26ace122015-03-16 19:41:43 +00003319 return sBgWidgetProviders.get(new ComponentKey(name, user));
Adam Cohen59400422014-03-05 18:07:04 -08003320 }
3321 }
3322
Winson Chungb745afb2015-03-02 11:51:23 -08003323 // Returns a list of ResolveInfos/AppWidgetInfos in sorted order
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003324 public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context, boolean refresh) {
Michael Jurkac402cd92013-05-20 15:49:32 +02003325 PackageManager packageManager = context.getPackageManager();
3326 final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
Hyunyoung Song70a48be2015-03-11 16:36:52 -07003327 widgetsAndShortcuts.addAll(getWidgetProviders(context, refresh));
Michael Jurkac402cd92013-05-20 15:49:32 +02003328 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
3329 widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Sunny Goyalffe83f12014-08-14 17:39:34 -07003330 Collections.sort(widgetsAndShortcuts, new WidgetAndShortcutNameComparator(context));
Michael Jurkac402cd92013-05-20 15:49:32 +02003331 return widgetsAndShortcuts;
3332 }
3333
Kenny Guyed131872014-04-30 03:02:21 +01003334 private static boolean isPackageDisabled(Context context, String packageName,
3335 UserHandleCompat user) {
3336 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3337 return !launcherApps.isPackageEnabledForProfile(packageName, user);
Winson Chungdf95eb12013-10-16 14:57:07 -07003338 }
Adam Cohen556f6132014-01-15 15:18:08 -08003339
Kenny Guyed131872014-04-30 03:02:21 +01003340 public static boolean isValidPackageActivity(Context context, ComponentName cn,
3341 UserHandleCompat user) {
Winson Chungee055712013-07-30 14:46:24 -07003342 if (cn == null) {
3343 return false;
3344 }
Kenny Guyed131872014-04-30 03:02:21 +01003345 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3346 if (!launcherApps.isPackageEnabledForProfile(cn.getPackageName(), user)) {
Winson Chungdf95eb12013-10-16 14:57:07 -07003347 return false;
3348 }
Kenny Guyed131872014-04-30 03:02:21 +01003349 return launcherApps.isActivityEnabledForProfile(cn, user);
Winson Chungee055712013-07-30 14:46:24 -07003350 }
3351
Adam Cohena28b78e2014-05-20 17:03:04 -07003352 public static boolean isValidPackage(Context context, String packageName,
3353 UserHandleCompat user) {
3354 if (packageName == null) {
3355 return false;
3356 }
3357 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
3358 return launcherApps.isPackageEnabledForProfile(packageName, user);
3359 }
3360
Joe Onorato9c1289c2009-08-17 11:03:03 -04003361 /**
Chris Wrenf4d08112014-01-16 18:13:56 -05003362 * Make an ShortcutInfo object for a restored application or shortcut item that points
3363 * to a package that is not yet installed on the system.
3364 */
Sunny Goyal34942622014-08-29 17:20:55 -07003365 public ShortcutInfo getRestoredItemInfo(Cursor cursor, int titleIndex, Intent intent,
Sunny Goyal34b65272015-03-11 16:56:52 -07003366 int promiseType, boolean useLowResIcon) {
Chris Wrenf4d08112014-01-16 18:13:56 -05003367 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003368 info.user = UserHandleCompat.myUserHandle();
Sunny Goyal34b65272015-03-11 16:56:52 -07003369 mIconCache.getTitleAndIcon(info, intent, info.user, useLowResIcon);
Sunny Goyal34942622014-08-29 17:20:55 -07003370
3371 if ((promiseType & ShortcutInfo.FLAG_RESTORED_ICON) != 0) {
3372 String title = (cursor != null) ? cursor.getString(titleIndex) : null;
3373 if (!TextUtils.isEmpty(title)) {
3374 info.title = title;
3375 }
3376 info.status = ShortcutInfo.FLAG_RESTORED_ICON;
3377 } else if ((promiseType & ShortcutInfo.FLAG_AUTOINTALL_ICON) != 0) {
3378 if (TextUtils.isEmpty(info.title)) {
3379 info.title = (cursor != null) ? cursor.getString(titleIndex) : "";
3380 }
3381 info.status = ShortcutInfo.FLAG_AUTOINTALL_ICON;
3382 } else {
3383 throw new InvalidParameterException("Invalid restoreType " + promiseType);
3384 }
3385
Kenny Guyc2bd8102014-06-30 12:30:31 +01003386 info.contentDescription = mUserManager.getBadgedLabelForUser(
3387 info.title.toString(), info.user);
Chris Wrenf4d08112014-01-16 18:13:56 -05003388 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
Sunny Goyal34942622014-08-29 17:20:55 -07003389 info.promisedIntent = intent;
Chris Wrenf4d08112014-01-16 18:13:56 -05003390 return info;
3391 }
3392
3393 /**
3394 * Make an Intent object for a restored application or shortcut item that points
3395 * to the market page for the item.
3396 */
3397 private Intent getRestoredItemIntent(Cursor c, Context context, Intent intent) {
3398 ComponentName componentName = intent.getComponent();
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003399 return getMarketIntent(componentName.getPackageName());
3400 }
3401
3402 static Intent getMarketIntent(String packageName) {
3403 return new Intent(Intent.ACTION_VIEW)
3404 .setData(new Uri.Builder()
Chris Wrenf4d08112014-01-16 18:13:56 -05003405 .scheme("market")
3406 .authority("details")
Sunny Goyale7b8cd92014-08-27 14:04:33 -07003407 .appendQueryParameter("id", packageName)
3408 .build());
Chris Wrenf4d08112014-01-16 18:13:56 -05003409 }
3410
3411 /**
Joe Onorato56d82912010-03-07 14:32:10 -05003412 * Make an ShortcutInfo object for a shortcut that is an application.
3413 *
3414 * If c is not null, then it will be used to fill in missing data like the title and icon.
3415 */
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003416 public ShortcutInfo getAppShortcutInfo(PackageManager manager, Intent intent,
Kenny Guyed131872014-04-30 03:02:21 +01003417 UserHandleCompat user, Context context, Cursor c, int iconIndex, int titleIndex,
Sunny Goyal34b65272015-03-11 16:56:52 -07003418 boolean allowMissingTarget, boolean useLowResIcon) {
Kenny Guyed131872014-04-30 03:02:21 +01003419 if (user == null) {
3420 Log.d(TAG, "Null user found in getShortcutInfo");
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003421 return null;
3422 }
3423
Kenny Guyed131872014-04-30 03:02:21 +01003424 ComponentName componentName = intent.getComponent();
3425 if (componentName == null) {
3426 Log.d(TAG, "Missing component found in getShortcutInfo: " + componentName);
3427 return null;
3428 }
3429
3430 Intent newIntent = new Intent(intent.getAction(), null);
3431 newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
3432 newIntent.setComponent(componentName);
3433 LauncherActivityInfoCompat lai = mLauncherApps.resolveActivity(newIntent, user);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07003434 if ((lai == null) && !allowMissingTarget) {
Kenny Guyed131872014-04-30 03:02:21 +01003435 Log.d(TAG, "Missing activity found in getShortcutInfo: " + componentName);
3436 return null;
3437 }
3438
3439 final ShortcutInfo info = new ShortcutInfo();
Sunny Goyal34b65272015-03-11 16:56:52 -07003440 mIconCache.getTitleAndIcon(info, componentName, lai, user, false, useLowResIcon);
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003441 if (mIconCache.isDefaultIcon(info.getIcon(mIconCache), user) && c != null) {
3442 Bitmap icon = Utilities.createIconBitmap(c, iconIndex, context);
3443 info.setIcon(icon == null ? mIconCache.getDefaultIcon(user) : icon);
Kenny Guyed131872014-04-30 03:02:21 +01003444 }
3445
Joe Onorato56d82912010-03-07 14:32:10 -05003446 // from the db
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003447 if (TextUtils.isEmpty(info.title) && c != null) {
3448 info.title = c.getString(titleIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003449 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003450
Joe Onorato56d82912010-03-07 14:32:10 -05003451 // fall back to the class name of the activity
3452 if (info.title == null) {
3453 info.title = componentName.getClassName();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07003454 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003455
Joe Onorato9c1289c2009-08-17 11:03:03 -04003456 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
Kenny Guyed131872014-04-30 03:02:21 +01003457 info.user = user;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003458 info.contentDescription = mUserManager.getBadgedLabelForUser(
3459 info.title.toString(), info.user);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003460 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003461 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07003462
Winson Chung64359a52013-07-08 17:17:08 -07003463 static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
3464 ItemInfoFilter f) {
3465 HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
3466 for (ItemInfo i : infos) {
3467 if (i instanceof ShortcutInfo) {
3468 ShortcutInfo info = (ShortcutInfo) i;
Sunny Goyal34942622014-08-29 17:20:55 -07003469 ComponentName cn = info.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003470 if (cn != null && f.filterItem(null, info, cn)) {
3471 filtered.add(info);
3472 }
3473 } else if (i instanceof FolderInfo) {
3474 FolderInfo info = (FolderInfo) i;
3475 for (ShortcutInfo s : info.contents) {
Sunny Goyal34942622014-08-29 17:20:55 -07003476 ComponentName cn = s.getTargetComponent();
Winson Chung64359a52013-07-08 17:17:08 -07003477 if (cn != null && f.filterItem(info, s, cn)) {
3478 filtered.add(s);
Winson Chung8a435102012-08-30 17:16:53 -07003479 }
3480 }
Winson Chung64359a52013-07-08 17:17:08 -07003481 } else if (i instanceof LauncherAppWidgetInfo) {
3482 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
3483 ComponentName cn = info.providerName;
3484 if (cn != null && f.filterItem(null, info, cn)) {
3485 filtered.add(info);
3486 }
Winson Chung8a435102012-08-30 17:16:53 -07003487 }
3488 }
Winson Chung64359a52013-07-08 17:17:08 -07003489 return new ArrayList<ItemInfo>(filtered);
3490 }
3491
Kenny Guyed131872014-04-30 03:02:21 +01003492 private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname,
3493 final UserHandleCompat user) {
Winson Chung64359a52013-07-08 17:17:08 -07003494 ItemInfoFilter filter = new ItemInfoFilter() {
3495 @Override
3496 public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
Kenny Guyed131872014-04-30 03:02:21 +01003497 if (info.user == null) {
3498 return cn.equals(cname);
3499 } else {
3500 return cn.equals(cname) && info.user.equals(user);
3501 }
Winson Chung64359a52013-07-08 17:17:08 -07003502 }
3503 };
3504 return filterItemInfos(sBgItemsIdMap.values(), filter);
3505 }
3506
Sunny Goyal1a745e82014-10-02 15:58:31 -07003507 /**
Joe Onorato0589f0f2010-02-08 13:44:00 -08003508 * Make an ShortcutInfo object for a shortcut that isn't an application.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003509 */
Joe Onorato0589f0f2010-02-08 13:44:00 -08003510 private ShortcutInfo getShortcutInfo(Cursor c, Context context,
Joe Onorato56d82912010-03-07 14:32:10 -05003511 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
3512 int titleIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003513
Joe Onorato56d82912010-03-07 14:32:10 -05003514 Bitmap icon = null;
Michael Jurkac9d95c52011-08-29 14:03:34 -07003515 final ShortcutInfo info = new ShortcutInfo();
Kenny Guyed131872014-04-30 03:02:21 +01003516 // Non-app shortcuts are only supported for current user.
3517 info.user = UserHandleCompat.myUserHandle();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003518 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003519
Joe Onorato8ddc4fd2010-03-17 09:14:50 -07003520 // TODO: If there's an explicit component and we can't install that, delete it.
3521
Joe Onorato56d82912010-03-07 14:32:10 -05003522 info.title = c.getString(titleIndex);
3523
Joe Onorato9c1289c2009-08-17 11:03:03 -04003524 int iconType = c.getInt(iconTypeIndex);
3525 switch (iconType) {
3526 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
3527 String packageName = c.getString(iconPackageIndex);
3528 String resourceName = c.getString(iconResourceIndex);
Joe Onorato56d82912010-03-07 14:32:10 -05003529 info.customIcon = false;
3530 // the resource
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003531 icon = Utilities.createIconBitmap(packageName, resourceName, mIconCache, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003532 // the db
3533 if (icon == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003534 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003535 }
3536 // the fallback icon
3537 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003538 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003539 info.usingFallbackIcon = true;
3540 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003541 break;
3542 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
Sunny Goyal4fbc3822015-02-18 16:46:50 -08003543 icon = Utilities.createIconBitmap(c, iconIndex, context);
Joe Onorato56d82912010-03-07 14:32:10 -05003544 if (icon == null) {
Kenny Guyed131872014-04-30 03:02:21 +01003545 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003546 info.customIcon = false;
3547 info.usingFallbackIcon = true;
3548 } else {
3549 info.customIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003550 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04003551 break;
3552 default:
Kenny Guyed131872014-04-30 03:02:21 +01003553 icon = mIconCache.getDefaultIcon(info.user);
Joe Onorato56d82912010-03-07 14:32:10 -05003554 info.usingFallbackIcon = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -04003555 info.customIcon = false;
3556 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003557 }
Joe Onoratod8d22da2010-03-11 17:59:11 -08003558 info.setIcon(icon);
Joe Onorato9c1289c2009-08-17 11:03:03 -04003559 return info;
3560 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003561
Sunny Goyal2350bc92014-10-14 16:42:54 -07003562 ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Joe Onorato0589f0f2010-02-08 13:44:00 -08003563 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
3564 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
3565 Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
3566
Adam Cohend9198822011-11-22 16:42:47 -08003567 if (intent == null) {
3568 // If the intent is null, we can't construct a valid ShortcutInfo, so we return null
3569 Log.e(TAG, "Can't construct ShorcutInfo with null intent");
3570 return null;
3571 }
3572
Joe Onorato0589f0f2010-02-08 13:44:00 -08003573 Bitmap icon = null;
Joe Onorato0589f0f2010-02-08 13:44:00 -08003574 boolean customIcon = false;
3575 ShortcutIconResource iconResource = null;
3576
Sunny Goyal2fce90c2014-10-07 12:01:58 -07003577 if (bitmap instanceof Bitmap) {
3578 icon = Utilities.createIconBitmap((Bitmap) bitmap, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003579 customIcon = true;
3580 } else {
3581 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07003582 if (extra instanceof ShortcutIconResource) {
3583 iconResource = (ShortcutIconResource) extra;
3584 icon = Utilities.createIconBitmap(iconResource.packageName,
3585 iconResource.resourceName, mIconCache, context);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003586 }
3587 }
3588
Michael Jurkac9d95c52011-08-29 14:03:34 -07003589 final ShortcutInfo info = new ShortcutInfo();
Joe Onorato56d82912010-03-07 14:32:10 -05003590
Kenny Guyed131872014-04-30 03:02:21 +01003591 // Only support intents for current user for now. Intents sent from other
3592 // users wouldn't get here without intent forwarding anyway.
3593 info.user = UserHandleCompat.myUserHandle();
Joe Onorato56d82912010-03-07 14:32:10 -05003594 if (icon == null) {
Sunny Goyal2350bc92014-10-14 16:42:54 -07003595 icon = mIconCache.getDefaultIcon(info.user);
3596 info.usingFallbackIcon = true;
Joe Onorato56d82912010-03-07 14:32:10 -05003597 }
Joe Onorato0589f0f2010-02-08 13:44:00 -08003598 info.setIcon(icon);
Joe Onorato56d82912010-03-07 14:32:10 -05003599
Joe Onorato0589f0f2010-02-08 13:44:00 -08003600 info.title = name;
Kenny Guyc2bd8102014-06-30 12:30:31 +01003601 info.contentDescription = mUserManager.getBadgedLabelForUser(
3602 info.title.toString(), info.user);
Joe Onorato0589f0f2010-02-08 13:44:00 -08003603 info.intent = intent;
3604 info.customIcon = customIcon;
3605 info.iconResource = iconResource;
3606
3607 return info;
3608 }
3609
Joe Onorato9c1289c2009-08-17 11:03:03 -04003610 /**
Adam Cohendf2cc412011-04-27 16:56:57 -07003611 * Return an existing FolderInfo object if we have encountered this ID previously,
Joe Onorato9c1289c2009-08-17 11:03:03 -04003612 * or make a new one.
3613 */
Adam Cohendf2cc412011-04-27 16:56:57 -07003614 private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003615 // See if a placeholder was created for us already
3616 FolderInfo folderInfo = folders.get(id);
Adam Cohendf2cc412011-04-27 16:56:57 -07003617 if (folderInfo == null) {
Joe Onorato9c1289c2009-08-17 11:03:03 -04003618 // No placeholder -- create a new instance
Michael Jurkac9d95c52011-08-29 14:03:34 -07003619 folderInfo = new FolderInfo();
Joe Onorato9c1289c2009-08-17 11:03:03 -04003620 folders.put(id, folderInfo);
3621 }
Adam Cohendf2cc412011-04-27 16:56:57 -07003622 return folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003623 }
3624
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003625 public static final Comparator<AppInfo> getAppNameComparator() {
Winson Chung11904872012-09-17 16:58:46 -07003626 final Collator collator = Collator.getInstance();
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003627 return new Comparator<AppInfo>() {
3628 public final int compare(AppInfo a, AppInfo b) {
Kenny Guyed131872014-04-30 03:02:21 +01003629 if (a.user.equals(b.user)) {
3630 int result = collator.compare(a.title.toString().trim(),
3631 b.title.toString().trim());
3632 if (result == 0) {
3633 result = a.componentName.compareTo(b.componentName);
3634 }
3635 return result;
3636 } else {
3637 // TODO Need to figure out rules for sorting
3638 // profiles, this puts work second.
3639 return a.user.toString().compareTo(b.user.toString());
Winson Chung11904872012-09-17 16:58:46 -07003640 }
Michael Jurka5b1808d2011-07-11 19:59:46 -07003641 }
Winson Chung11904872012-09-17 16:58:46 -07003642 };
3643 }
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003644 public static final Comparator<AppInfo> APP_INSTALL_TIME_COMPARATOR
3645 = new Comparator<AppInfo>() {
3646 public final int compare(AppInfo a, AppInfo b) {
Winson Chung78403fe2011-01-21 15:38:02 -08003647 if (a.firstInstallTime < b.firstInstallTime) return 1;
3648 if (a.firstInstallTime > b.firstInstallTime) return -1;
3649 return 0;
3650 }
3651 };
Winson Chung5308f242011-08-18 12:12:41 -07003652 static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
3653 if (info.activityInfo != null) {
3654 return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
3655 } else {
3656 return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
3657 }
3658 }
Winson Chungc3eecff2011-07-11 17:44:15 -07003659
Winson Chung1ed747a2011-05-03 16:18:34 -07003660 public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
Sunny Goyalffe83f12014-08-14 17:39:34 -07003661 private final AppWidgetManagerCompat mManager;
3662 private final PackageManager mPackageManager;
3663 private final HashMap<Object, String> mLabelCache;
3664 private final Collator mCollator;
3665
3666 WidgetAndShortcutNameComparator(Context context) {
3667 mManager = AppWidgetManagerCompat.getInstance(context);
3668 mPackageManager = context.getPackageManager();
Winson Chung1ed747a2011-05-03 16:18:34 -07003669 mLabelCache = new HashMap<Object, String>();
Winson Chung11904872012-09-17 16:58:46 -07003670 mCollator = Collator.getInstance();
Winson Chung1ed747a2011-05-03 16:18:34 -07003671 }
3672 public final int compare(Object a, Object b) {
3673 String labelA, labelB;
Winson Chungc3eecff2011-07-11 17:44:15 -07003674 if (mLabelCache.containsKey(a)) {
3675 labelA = mLabelCache.get(a);
3676 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003677 labelA = (a instanceof LauncherAppWidgetProviderInfo)
3678 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) a)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003679 : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003680 mLabelCache.put(a, labelA);
3681 }
3682 if (mLabelCache.containsKey(b)) {
3683 labelB = mLabelCache.get(b);
3684 } else {
Adam Cohen59400422014-03-05 18:07:04 -08003685 labelB = (b instanceof LauncherAppWidgetProviderInfo)
Adam Cohenb76c165aa2015-01-30 10:28:23 -08003686 ? mManager.loadLabel((LauncherAppWidgetProviderInfo) b)
Sunny Goyalffe83f12014-08-14 17:39:34 -07003687 : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim();
Winson Chungc3eecff2011-07-11 17:44:15 -07003688 mLabelCache.put(b, labelB);
3689 }
Winson Chung11904872012-09-17 16:58:46 -07003690 return mCollator.compare(labelA, labelB);
Winson Chung1ed747a2011-05-03 16:18:34 -07003691 }
3692 };
Joe Onoratobe386092009-11-17 17:32:16 -08003693
Sunny Goyal651077b2014-06-30 14:15:31 -07003694 static boolean isValidProvider(AppWidgetProviderInfo provider) {
3695 return (provider != null) && (provider.provider != null)
3696 && (provider.provider.getPackageName() != null);
3697 }
3698
Joe Onoratobe386092009-11-17 17:32:16 -08003699 public void dumpState() {
Joe Onoratobe386092009-11-17 17:32:16 -08003700 Log.d(TAG, "mCallbacks=" + mCallbacks);
Michael Jurkaeadbfc52013-09-04 00:45:37 +02003701 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
3702 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
3703 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
3704 AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
Joe Onorato36115782010-06-17 13:28:48 -04003705 if (mLoaderTask != null) {
3706 mLoaderTask.dumpState();
3707 } else {
3708 Log.d(TAG, "mLoaderTask=null");
3709 }
Joe Onoratobe386092009-11-17 17:32:16 -08003710 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08003711
3712 public Callbacks getCallback() {
3713 return mCallbacks != null ? mCallbacks.get() : null;
3714 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003715}