blob: 845fdbfebc9811fe7b2df5035d7783e8c67d5def [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
Romain Guy629de3e2010-01-13 12:20:59 -080019import android.appwidget.AppWidgetProviderInfo;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070020import android.content.BroadcastReceiver;
21import android.content.ComponentName;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070022import android.content.ContentProviderOperation;
23import android.content.ContentResolver;
24import android.content.ContentValues;
25import android.content.Context;
26import android.content.Intent;
Sunny Goyalf599ccf2014-07-08 13:01:29 -070027import android.content.IntentFilter;
Sunny Goyal3e9be432017-01-05 15:22:41 -080028import android.content.pm.LauncherActivityInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080029import android.net.Uri;
Joe Onorato36115782010-06-17 13:28:48 -040030import android.os.Handler;
31import android.os.HandlerThread;
Sunny Goyal756adbc2015-04-16 15:20:51 -070032import android.os.Looper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080033import android.os.Process;
Joe Onorato9c1289c2009-08-17 11:03:03 -040034import android.os.SystemClock;
Sunny Goyale26d1002016-06-20 14:52:14 -070035import android.os.Trace;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080036import android.os.UserHandle;
Winson Chunga90303b2013-11-15 13:05:06 -080037import android.text.TextUtils;
Winson Chungaafa03c2010-06-11 17:34:16 -070038import android.util.Log;
Sunny Goyal71b5c0b2015-01-08 16:59:04 -080039import android.util.LongSparseArray;
Tony Wickhambfbf7f92016-05-19 11:19:39 -070040import android.util.MutableInt;
Michael Jurka34c2e6c2013-12-13 16:07:45 +010041
Sunny Goyalffe83f12014-08-14 17:39:34 -070042import com.android.launcher3.compat.AppWidgetManagerCompat;
Kenny Guyed131872014-04-30 03:02:21 +010043import com.android.launcher3.compat.LauncherAppsCompat;
Sunny Goyal34942622014-08-29 17:20:55 -070044import com.android.launcher3.compat.PackageInstallerCompat;
Sunny Goyale755d462014-07-22 13:48:29 -070045import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
Kenny Guyed131872014-04-30 03:02:21 +010046import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal6c56c682015-07-16 14:09:05 -070047import com.android.launcher3.config.ProviderConfig;
Tony Wickham827cef22016-03-17 15:39:39 -070048import com.android.launcher3.dynamicui.ExtractionUtils;
Sunny Goyal26119432016-02-18 22:09:23 +000049import com.android.launcher3.folder.Folder;
50import com.android.launcher3.folder.FolderIcon;
Jon Miranda655ec422017-02-07 11:40:22 -080051import com.android.launcher3.folder.FolderIconPreviewVerifier;
Sunny Goyal1b072632017-01-18 11:30:23 -080052import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal1acb9e92016-05-16 12:41:09 -070053import com.android.launcher3.logging.FileLog;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070054import com.android.launcher3.model.AddWorkspaceItemsTask;
Sunny Goyale9956a72016-09-01 17:24:47 -070055import com.android.launcher3.model.BgDataModel;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070056import com.android.launcher3.model.CacheDataUpdatedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080057import com.android.launcher3.model.ExtendedModelTask;
Sunny Goyalf862a262015-12-14 14:27:38 -080058import com.android.launcher3.model.GridSizeMigrationTask;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -080059import com.android.launcher3.model.LoaderCursor;
Sunny Goyal43bf11d2017-02-02 13:52:53 -080060import com.android.launcher3.model.ModelWriter;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070061import com.android.launcher3.model.PackageInstallStateChangedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080062import com.android.launcher3.model.PackageItemInfo;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070063import com.android.launcher3.model.PackageUpdatedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080064import com.android.launcher3.model.SdCardAvailableReceiver;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070065import com.android.launcher3.model.ShortcutsChangedTask;
66import com.android.launcher3.model.UserLockStateChangedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080067import com.android.launcher3.model.WidgetItem;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070068import com.android.launcher3.model.WidgetsModel;
Sunny Goyala5c8a9e2016-07-08 08:32:44 -070069import com.android.launcher3.provider.ImportDataTask;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070070import com.android.launcher3.provider.LauncherDbUtils;
Tony Wickhambfbf7f92016-05-19 11:19:39 -070071import com.android.launcher3.shortcuts.DeepShortcutManager;
72import com.android.launcher3.shortcuts.ShortcutInfoCompat;
73import com.android.launcher3.shortcuts.ShortcutKey;
Robin Lee26ace122015-03-16 19:41:43 +000074import com.android.launcher3.util.ComponentKey;
Sunny Goyal18bf8e22015-04-08 18:13:46 -070075import com.android.launcher3.util.ManagedProfileHeuristic;
Tony Wickhamd82a39d2016-07-01 15:44:13 -070076import com.android.launcher3.util.MultiHashMap;
Sunny Goyald09c3702016-04-06 16:18:20 -070077import com.android.launcher3.util.PackageManagerHelper;
Sunny Goyalaaf7d1d2016-05-17 13:38:54 -070078import com.android.launcher3.util.Preconditions;
Sunny Goyal2bcbe132016-11-16 09:23:42 -080079import com.android.launcher3.util.Provider;
Adam Cohen091440a2015-03-18 14:16:05 -070080import com.android.launcher3.util.Thunk;
Sunny Goyal527c7d32015-08-28 15:19:36 -070081import com.android.launcher3.util.ViewOnDrawExecutor;
Romain Guyedcce092010-03-04 13:03:17 -080082
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -080083import java.io.FileDescriptor;
84import java.io.PrintWriter;
Michael Jurkac2f801e2011-07-12 14:19:46 -070085import java.lang.ref.WeakReference;
Michael Jurkac2f801e2011-07-12 14:19:46 -070086import java.util.ArrayList;
87import java.util.Collections;
88import java.util.Comparator;
89import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070090import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070091import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070092import java.util.List;
Tony Wickhambfbf7f92016-05-19 11:19:39 -070093import java.util.Map;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070094import java.util.Set;
Sunny Goyaldd96a5e2017-02-17 11:22:34 -080095import java.util.concurrent.CancellationException;
Sunny Goyal527c7d32015-08-28 15:19:36 -070096import java.util.concurrent.Executor;
Michael Jurkac2f801e2011-07-12 14:19:46 -070097
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098/**
99 * Maintains in-memory state of the Launcher. It is expected that there should be only one
100 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700101 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102 */
Kenny Guyed131872014-04-30 03:02:21 +0100103public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +0100104 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800105 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -0400106 private static final boolean DEBUG_RECEIVER = false;
Chris Wrenb358f812014-04-16 13:37:00 -0400107
Joe Onorato9c1289c2009-08-17 11:03:03 -0400108 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700109
Joe Onorato36115782010-06-17 13:28:48 -0400110 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500111 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800112
Adam Cohen091440a2015-03-18 14:16:05 -0700113 @Thunk final LauncherAppState mApp;
114 @Thunk final Object mLock = new Object();
115 @Thunk DeferredHandler mHandler = new DeferredHandler();
116 @Thunk LoaderTask mLoaderTask;
117 @Thunk boolean mIsLoaderTaskRunning;
Sunny Goyal756a28a2015-04-23 17:07:55 -0700118 @Thunk boolean mHasLoaderCompletedOnce;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119
Adam Cohen091440a2015-03-18 14:16:05 -0700120 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700121 static {
122 sWorkerThread.start();
123 }
Adam Cohen091440a2015-03-18 14:16:05 -0700124 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700125
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800126 // Indicates whether the current model data is valid or not.
127 // We start off with everything not loaded. After that, we assume that
Joe Onoratocc67f472010-06-08 10:54:30 -0700128 // our monitoring of the package manager provides all updates and we never
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800129 // need to do a requery. This is only ever touched from the loader thread.
130 private boolean mModelLoaded;
Joe Onoratocc67f472010-06-08 10:54:30 -0700131
Sunny Goyal756a28a2015-04-23 17:07:55 -0700132 /**
133 * Set of runnables to be called on the background thread after the workspace binding
134 * is complete.
135 */
136 static final ArrayList<Runnable> mBindCompleteRunnables = new ArrayList<Runnable>();
137
Adam Cohen091440a2015-03-18 14:16:05 -0700138 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700140 // < only access in worker thread >
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800141 private final AllAppsList mBgAllAppsList;
Hyunyoung Song9110d482015-05-22 14:49:23 -0700142 // Entire list of widgets.
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800143 private final WidgetsModel mBgWidgetsModel;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800144
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700145 private boolean mHasShortcutHostPermission;
146 // Runnable to check if the shortcuts permission has changed.
147 private final Runnable mShortcutPermissionCheckRunnable = new Runnable() {
148 @Override
149 public void run() {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800150 if (mModelLoaded) {
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530151 boolean hasShortcutHostPermission =
152 DeepShortcutManager.getInstance(mApp.getContext()).hasHostPermission();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700153 if (hasShortcutHostPermission != mHasShortcutHostPermission) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800154 forceReload();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700155 }
156 }
157 }
158 };
159
Sunny Goyale9956a72016-09-01 17:24:47 -0700160 /**
161 * All the static data should be accessed on the background thread, A lock should be acquired
162 * on this object when accessing any data from this model.
163 */
164 static final BgDataModel sBgDataModel = new BgDataModel();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700165
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700166 // </ only access in worker thread >
167
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700168 private final IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800169
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700170 private final LauncherAppsCompat mLauncherApps;
171 private final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100172
Joe Onorato9c1289c2009-08-17 11:03:03 -0400173 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700174 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400175 public int getCurrentWorkspaceScreen();
Sunny Goyal527c7d32015-08-28 15:19:36 -0700176 public void clearPendingBinds();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400177 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700178 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
179 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700180 public void bindScreens(ArrayList<Long> orderedScreenIds);
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700181 public void finishFirstPageBind(ViewOnDrawExecutor executor);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800182 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400183 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200184 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700185 public void bindAppsAdded(ArrayList<Long> newScreens,
186 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700187 ArrayList<ItemInfo> addAnimated,
188 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200189 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700190 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800191 ArrayList<ShortcutInfo> removed, UserHandle user);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700192 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyal756adbc2015-04-16 15:20:51 -0700193 public void bindRestoreItemsChange(HashSet<ItemInfo> updates);
Sunny Goyal3bbbabc2016-03-15 09:16:30 -0700194 public void bindWorkspaceComponentsRemoved(
195 HashSet<String> packageNames, HashSet<ComponentName> components,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800196 UserHandle user);
Sunny Goyal3bbbabc2016-03-15 09:16:30 -0700197 public void bindAppInfosRemoved(ArrayList<AppInfo> appInfos);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800198 public void notifyWidgetProvidersChanged();
Sunny Goyald164b7f2016-10-12 20:49:31 -0700199 public void bindAllWidgets(MultiHashMap<PackageItemInfo, WidgetItem> widgets);
Adam Cohen1462de32012-07-24 22:34:36 -0700200 public void onPageBoundSynchronously(int page);
Sunny Goyal527c7d32015-08-28 15:19:36 -0700201 public void executeOnNextDraw(ViewOnDrawExecutor executor);
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700202 public void bindDeepShortcutMap(MultiHashMap<ComponentKey, String> deepShortcutMap);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400203 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530205 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800206 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400207 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100208 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Sunny Goyald164b7f2016-10-12 20:49:31 -0700209 mBgWidgetsModel = new WidgetsModel(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800210 mIconCache = iconCache;
211
Kenny Guyed131872014-04-30 03:02:21 +0100212 mLauncherApps = LauncherAppsCompat.getInstance(context);
213 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800214 }
215
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700216 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
217 * posted on the main thread handler. */
Tony Wickham80f57872016-06-29 18:12:15 -0700218 private void runOnMainThread(Runnable r) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700219 if (sWorkerThread.getThreadId() == Process.myTid()) {
220 // If we are on the worker thread, post onto the main handler
221 mHandler.post(r);
222 } else {
223 r.run();
224 }
225 }
226
227 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
228 * posted on the worker thread handler. */
Tony Wickham80f57872016-06-29 18:12:15 -0700229 private static void runOnWorkerThread(Runnable r) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700230 if (sWorkerThread.getThreadId() == Process.myTid()) {
231 r.run();
232 } else {
233 // If we are not on the worker thread, then post to the worker handler
234 sWorker.post(r);
235 }
236 }
237
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700238 public void setPackageState(PackageInstallInfo installInfo) {
239 enqueueModelUpdateTask(new PackageInstallStateChangedTask(installInfo));
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500240 }
241
Sunny Goyal756adbc2015-04-16 15:20:51 -0700242 /**
243 * Updates the icons and label of all pending icons for the provided package name.
244 */
245 public void updateSessionDisplayInfo(final String packageName) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700246 HashSet<String> packages = new HashSet<>();
247 packages.add(packageName);
248 enqueueModelUpdateTask(new CacheDataUpdatedTask(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800249 CacheDataUpdatedTask.OP_SESSION_UPDATE, Process.myUserHandle(), packages));
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800250 }
251
252 /**
253 * Adds the provided items to the workspace.
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800254 */
Sunny Goyal2bcbe132016-11-16 09:23:42 -0800255 public void addAndBindAddedWorkspaceItems(List<ItemInfo> workspaceApps) {
256 addAndBindAddedWorkspaceItems(Provider.of(workspaceApps));
257 }
258
259 /**
260 * Adds the provided items to the workspace.
261 */
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700262 public void addAndBindAddedWorkspaceItems(
Sunny Goyal2bcbe132016-11-16 09:23:42 -0800263 Provider<List<ItemInfo>> appsProvider) {
264 enqueueModelUpdateTask(new AddWorkspaceItemsTask(appsProvider));
Winson Chung64359a52013-07-08 17:17:08 -0700265 }
266
Sunny Goyal43bf11d2017-02-02 13:52:53 -0800267 public ModelWriter getWriter(boolean hasVerticalHotseat) {
268 return new ModelWriter(mApp.getContext(), sBgDataModel, hasVerticalHotseat);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800269 }
270
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700271 static void checkItemInfoLocked(
272 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
Sunny Goyale9956a72016-09-01 17:24:47 -0700273 ItemInfo modelItem = sBgDataModel.itemsIdMap.get(itemId);
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700274 if (modelItem != null && item != modelItem) {
275 // check all the data is consistent
276 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
277 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
278 ShortcutInfo shortcut = (ShortcutInfo) item;
279 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
280 modelShortcut.intent.filterEquals(shortcut.intent) &&
281 modelShortcut.id == shortcut.id &&
282 modelShortcut.itemType == shortcut.itemType &&
283 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700284 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700285 modelShortcut.cellX == shortcut.cellX &&
286 modelShortcut.cellY == shortcut.cellY &&
287 modelShortcut.spanX == shortcut.spanX &&
Sunny Goyalaa8ef112015-06-12 20:04:41 -0700288 modelShortcut.spanY == shortcut.spanY) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700289 // For all intents and purposes, this is the same object
290 return;
291 }
292 }
293
294 // the modelItem needs to match up perfectly with item if our model is
295 // to be consistent with the database-- for now, just require
296 // modelItem == item or the equality check above
297 String msg = "item: " + ((item != null) ? item.toString() : "null") +
298 "modelItem: " +
299 ((modelItem != null) ? modelItem.toString() : "null") +
300 "Error: ItemInfo passed to checkItemInfo doesn't match original";
301 RuntimeException e = new RuntimeException(msg);
302 if (stackTrace != null) {
303 e.setStackTrace(stackTrace);
304 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800305 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700306 }
307 }
308
Michael Jurka816474f2012-06-25 14:49:02 -0700309 static void checkItemInfo(final ItemInfo item) {
310 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
311 final long itemId = item.id;
312 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700313 public void run() {
Sunny Goyale9956a72016-09-01 17:24:47 -0700314 synchronized (sBgDataModel) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700315 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700316 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700317 }
318 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700319 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700320 }
321
Joe Onorato9c1289c2009-08-17 11:03:03 -0400322 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700323 * Update the order of the workspace screens in the database. The array list contains
324 * a list of screen ids in the order that they should appear.
325 */
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700326 public static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700327 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700328 final ContentResolver cr = context.getContentResolver();
329 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
330
331 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700332 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700333 while (iter.hasNext()) {
334 long id = iter.next();
335 if (id < 0) {
336 iter.remove();
337 }
338 }
339
340 Runnable r = new Runnable() {
341 @Override
342 public void run() {
Yura085c8532014-02-11 15:15:29 +0000343 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700344 // Clear the table
Yura085c8532014-02-11 15:15:29 +0000345 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -0700346 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -0700347 for (int i = 0; i < count; i++) {
348 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -0700349 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -0700350 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
351 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +0000352 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -0700353 }
Yura085c8532014-02-11 15:15:29 +0000354
355 try {
356 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
357 } catch (Exception ex) {
358 throw new RuntimeException(ex);
359 }
Winson Chung9e6a0a22013-08-27 11:58:12 -0700360
Sunny Goyale9956a72016-09-01 17:24:47 -0700361 synchronized (sBgDataModel) {
362 sBgDataModel.workspaceScreens.clear();
363 sBgDataModel.workspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -0700364 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700365 }
366 };
367 runOnWorkerThread(r);
368 }
369
370 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400371 * Set this as the current Launcher activity object for the loader.
372 */
373 public void initialize(Callbacks callbacks) {
374 synchronized (mLock) {
Sunny Goyalaaf7d1d2016-05-17 13:38:54 -0700375 Preconditions.assertUIThread();
376 // Remove any queued UI runnables
377 mHandler.cancelAll();
378 mCallbacks = new WeakReference<>(callbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400379 }
380 }
381
Kenny Guyed131872014-04-30 03:02:21 +0100382 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800383 public void onPackageChanged(String packageName, UserHandle user) {
Kenny Guyed131872014-04-30 03:02:21 +0100384 int op = PackageUpdatedTask.OP_UPDATE;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700385 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packageName));
Kenny Guyed131872014-04-30 03:02:21 +0100386 }
387
388 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800389 public void onPackageRemoved(String packageName, UserHandle user) {
Sunny Goyalc2936bc2016-09-01 15:50:36 -0700390 onPackagesRemoved(user, packageName);
391 }
392
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800393 public void onPackagesRemoved(UserHandle user, String... packages) {
Kenny Guyed131872014-04-30 03:02:21 +0100394 int op = PackageUpdatedTask.OP_REMOVE;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700395 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packages));
Kenny Guyed131872014-04-30 03:02:21 +0100396 }
397
398 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800399 public void onPackageAdded(String packageName, UserHandle user) {
Kenny Guyed131872014-04-30 03:02:21 +0100400 int op = PackageUpdatedTask.OP_ADD;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700401 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packageName));
Kenny Guyed131872014-04-30 03:02:21 +0100402 }
403
404 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800405 public void onPackagesAvailable(String[] packageNames, UserHandle user,
Kenny Guyed131872014-04-30 03:02:21 +0100406 boolean replacing) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700407 enqueueModelUpdateTask(
408 new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE, user, packageNames));
Kenny Guyed131872014-04-30 03:02:21 +0100409 }
410
411 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800412 public void onPackagesUnavailable(String[] packageNames, UserHandle user,
Kenny Guyed131872014-04-30 03:02:21 +0100413 boolean replacing) {
414 if (!replacing) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700415 enqueueModelUpdateTask(new PackageUpdatedTask(
416 PackageUpdatedTask.OP_UNAVAILABLE, user, packageNames));
Kenny Guyed131872014-04-30 03:02:21 +0100417 }
Kenny Guyed131872014-04-30 03:02:21 +0100418 }
419
Kenny Guy44cba692016-01-21 19:50:02 +0000420 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800421 public void onPackagesSuspended(String[] packageNames, UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700422 enqueueModelUpdateTask(new PackageUpdatedTask(
423 PackageUpdatedTask.OP_SUSPEND, user, packageNames));
Kenny Guy44cba692016-01-21 19:50:02 +0000424 }
425
426 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800427 public void onPackagesUnsuspended(String[] packageNames, UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700428 enqueueModelUpdateTask(new PackageUpdatedTask(
429 PackageUpdatedTask.OP_UNSUSPEND, user, packageNames));
Kenny Guy44cba692016-01-21 19:50:02 +0000430 }
431
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700432 @Override
433 public void onShortcutsChanged(String packageName, List<ShortcutInfoCompat> shortcuts,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800434 UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700435 enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, true));
Sunny Goyal50941fb2016-08-04 12:03:52 -0700436 }
437
438 public void updatePinnedShortcuts(String packageName, List<ShortcutInfoCompat> shortcuts,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800439 UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700440 enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, false));
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700441 }
442
Joe Onorato1d8e7bb2009-10-15 19:49:43 -0700443 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400444 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
445 * ACTION_PACKAGE_CHANGED.
446 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100447 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -0400448 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -0400449 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -0700450
Joe Onorato36115782010-06-17 13:28:48 -0400451 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +0100452 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -0700453 // If we have changed locale we need to clear out the labels in all apps/workspace.
454 forceReload();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700455 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
456 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
Sunny Goyal823fd502015-08-04 11:40:13 -0700457 UserManagerCompat.getInstance(context).enableAndResetCache();
Sunny Goyal957c13f2015-05-01 13:02:20 -0700458 forceReload();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700459 } else if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) ||
460 Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
461 Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800462 UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
Sunny Goyalda891c12016-03-18 18:29:24 -0700463 if (user != null) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700464 if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) ||
465 Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700466 enqueueModelUpdateTask(new PackageUpdatedTask(
467 PackageUpdatedTask.OP_USER_AVAILABILITY_CHANGE, user));
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700468 }
469
470 // ACTION_MANAGED_PROFILE_UNAVAILABLE sends the profile back to locked mode, so
471 // we need to run the state change task again.
472 if (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
473 Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700474 enqueueModelUpdateTask(new UserLockStateChangedTask(user));
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700475 }
Sunny Goyalda891c12016-03-18 18:29:24 -0700476 }
Tony Wickham827cef22016-03-17 15:39:39 -0700477 } else if (Intent.ACTION_WALLPAPER_CHANGED.equals(action)) {
478 ExtractionUtils.startColorExtractionServiceIfNecessary(context);
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700479 }
480 }
481
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800482 /**
483 * Reloads the workspace items from the DB and re-binds the workspace. This should generally
484 * not be called as DB updates are automatically followed by UI update
485 */
486 public void forceReload() {
487 synchronized (mLock) {
488 // Stop any existing loaders first, so they don't set mModelLoaded to true later
489 stopLoaderLocked();
490 mModelLoaded = false;
491 }
Winson Chungf0c6ae02012-03-21 16:10:31 -0700492
Reena Lee93f824a2011-09-23 17:20:28 -0700493 // Do this here because if the launcher activity is running it will be restarted.
494 // If it's not running startLoaderFromBackground will merely tell it that it needs
495 // to reload.
496 startLoaderFromBackground();
497 }
498
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700499 /**
500 * When the launcher is in the background, it's possible for it to miss paired
501 * configuration changes. So whenever we trigger the loader from the background
502 * tell the launcher that it needs to re-run the loader when it comes back instead
503 * of doing it now.
504 */
505 public void startLoaderFromBackground() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800506 Callbacks callbacks = getCallback();
507 if (callbacks != null) {
508 // Only actually run the loader if they're not paused.
509 if (!callbacks.setLoadOnResume()) {
Sunny Goyal93f878c2016-03-30 17:31:24 -0700510 startLoader(callbacks.getCurrentWorkspaceScreen());
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700511 }
512 }
Joe Onorato36115782010-06-17 13:28:48 -0400513 }
Joe Onoratof99f8c12009-10-31 17:27:36 -0400514
Sunny Goyal2bba4c32015-05-18 15:42:48 -0700515 /**
516 * If there is already a loader task running, tell it to stop.
517 */
518 private void stopLoaderLocked() {
Reena Lee93f824a2011-09-23 17:20:28 -0700519 LoaderTask oldTask = mLoaderTask;
520 if (oldTask != null) {
Reena Lee93f824a2011-09-23 17:20:28 -0700521 oldTask.stopLocked();
522 }
Reena Lee93f824a2011-09-23 17:20:28 -0700523 }
524
Adam Cohen1a85c582014-09-30 09:48:49 -0700525 public boolean isCurrentCallbacks(Callbacks callbacks) {
526 return (mCallbacks != null && mCallbacks.get() == callbacks);
527 }
528
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700529 /**
530 * Starts the loader. Tries to bind {@params synchronousBindPage} synchronously if possible.
531 * @return true if the page could be bound synchronously.
532 */
533 public boolean startLoader(int synchronousBindPage) {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700534 // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
535 InstallShortcutReceiver.enableInstallQueue();
Joe Onorato36115782010-06-17 13:28:48 -0400536 synchronized (mLock) {
Joe Onorato36115782010-06-17 13:28:48 -0400537 // Don't bother to start the thread if we know it's not going to do anything
538 if (mCallbacks != null && mCallbacks.get() != null) {
Sunny Goyal527c7d32015-08-28 15:19:36 -0700539 final Callbacks oldCallbacks = mCallbacks.get();
540 // Clear any pending bind-runnables from the synchronized load process.
541 runOnMainThread(new Runnable() {
542 public void run() {
543 oldCallbacks.clearPendingBinds();
544 }
545 });
546
Joe Onorato36115782010-06-17 13:28:48 -0400547 // If there is already one running, tell it to stop.
Sunny Goyal2bba4c32015-05-18 15:42:48 -0700548 stopLoaderLocked();
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700549 mLoaderTask = new LoaderTask(mApp.getContext(), synchronousBindPage);
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800550 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
551 && mModelLoaded && !mIsLoaderTaskRunning) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700552 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700553 return true;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700554 } else {
555 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
556 sWorker.post(mLoaderTask);
557 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400558 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400559 }
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700560 return false;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400561 }
562
Joe Onorato36115782010-06-17 13:28:48 -0400563 public void stopLoader() {
564 synchronized (mLock) {
565 if (mLoaderTask != null) {
566 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400567 }
568 }
Joe Onorato36115782010-06-17 13:28:48 -0400569 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400570
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800571 /**
572 * Loads the workspace screen ids in an ordered list.
573 */
Sunny Goyale5bb7052015-07-27 14:36:07 -0700574 public static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -0700575 final ContentResolver contentResolver = context.getContentResolver();
576 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -0700577
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800578 // Get screens ordered by rank.
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700579 return LauncherDbUtils.getScreenIdsFromCursor(contentResolver.query(
580 screensUri, null, null, null, LauncherSettings.WorkspaceScreens.SCREEN_RANK));
Winson Chung76828c82013-08-19 15:43:29 -0700581 }
582
Joe Onorato36115782010-06-17 13:28:48 -0400583 /**
584 * Runnable for the thread that loads the contents of the launcher:
585 * - workspace icons
586 * - widgets
587 * - all apps icons
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700588 * - deep shortcuts within apps
Joe Onorato36115782010-06-17 13:28:48 -0400589 */
590 private class LoaderTask implements Runnable {
591 private Context mContext;
Sunny Goyal93f878c2016-03-30 17:31:24 -0700592 private int mPageToBindFirst;
593
Adam Cohen091440a2015-03-18 14:16:05 -0700594 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -0400595 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -0700596 @Thunk boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700597
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700598 LoaderTask(Context context, int pageToBindFirst) {
Joe Onorato36115782010-06-17 13:28:48 -0400599 mContext = context;
Sunny Goyal93f878c2016-03-30 17:31:24 -0700600 mPageToBindFirst = pageToBindFirst;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400601 }
602
Joe Onorato36115782010-06-17 13:28:48 -0400603 private void waitForIdle() {
604 // Wait until the either we're stopped or the other threads are done.
605 // This way we don't start loading all apps until the workspace has settled
606 // down.
607 synchronized (LoaderTask.this) {
608 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -0700609
Joe Onorato36115782010-06-17 13:28:48 -0400610 mHandler.postIdle(new Runnable() {
611 public void run() {
612 synchronized (LoaderTask.this) {
613 mLoadAndBindStepFinished = true;
614 if (DEBUG_LOADERS) {
615 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -0400616 }
Joe Onorato36115782010-06-17 13:28:48 -0400617 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -0400618 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400619 }
Joe Onorato36115782010-06-17 13:28:48 -0400620 });
621
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800622 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -0400623 try {
Michael Jurkac7700af2013-05-14 20:17:58 +0200624 // Just in case mFlushingWorkerThread changes but we aren't woken up,
625 // wait no longer than 1sec at a time
626 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -0400627 } catch (InterruptedException ex) {
628 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -0400629 }
630 }
Joe Onorato36115782010-06-17 13:28:48 -0400631 if (DEBUG_LOADERS) {
632 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -0700633 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -0400634 + "ms for previous step to finish binding");
635 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400636 }
Joe Onorato36115782010-06-17 13:28:48 -0400637 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400638
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700639 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -0500640 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700641 // Ensure that we have a valid page index to load synchronously
642 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
643 "valid page index");
644 }
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800645 if (!mModelLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700646 // Ensure that we don't try and bind a specified page when the pages have not been
647 // loaded already (we should load everything asynchronously in that case)
648 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
649 }
650 synchronized (mLock) {
651 if (mIsLoaderTaskRunning) {
652 // Ensure that we are never running the background loading at this point since
653 // we also touch the background collections
654 throw new RuntimeException("Error! Background loading is already running");
655 }
656 }
657
658 // XXX: Throw an exception if we are already loading (since we touch the worker thread
659 // data structures, we can't allow any other thread to touch that data, but because
660 // this call is synchronous, we can get away with not locking).
661
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400662 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -0700663 // operations from the previous activity. We need to ensure that all queued operations
664 // are executed before any synchronous binding work is done.
665 mHandler.flush();
666
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700667 // Divide the set of loaded items into those that we are binding synchronously, and
668 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800669 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700670 // XXX: For now, continue posting the binding of AllApps as there are other issues that
671 // arise from that.
672 onlyBindAllApps();
Tony Wickham80f57872016-06-29 18:12:15 -0700673
674 bindDeepShortcuts();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700675 }
676
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800677 private void verifyNotStopped() throws CancellationException {
678 synchronized (LoaderTask.this) {
679 if (mStopped) {
680 throw new CancellationException("Loader stopped");
681 }
682 }
683 }
684
Joe Onorato36115782010-06-17 13:28:48 -0400685 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700686 synchronized (mLock) {
Sunny Goyalf5cd9982015-05-18 15:19:29 -0700687 if (mStopped) {
688 return;
689 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700690 mIsLoaderTaskRunning = true;
691 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400692
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800693 try {
694 if (DEBUG_LOADERS) Log.d(TAG, "step 1.1: loading workspace");
695 // Set to false in bindWorkspace()
696 mIsLoadingAndBindingWorkspace = true;
697 loadWorkspace();
Joe Onorato36115782010-06-17 13:28:48 -0400698
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800699 verifyNotStopped();
700 if (DEBUG_LOADERS) Log.d(TAG, "step 1.2: bind workspace workspace");
701 bindWorkspace(mPageToBindFirst);
702
703 // Take a break
704 if (DEBUG_LOADERS) Log.d(TAG, "step 1 completed, wait for idle");
Joe Onorato36115782010-06-17 13:28:48 -0400705 waitForIdle();
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800706 verifyNotStopped();
Daniel Sandler843e8602010-06-07 14:59:01 -0400707
708 // second step
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800709 if (DEBUG_LOADERS) Log.d(TAG, "step 2.1: loading all apps");
710 loadAllApps();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700711
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800712 verifyNotStopped();
713 if (DEBUG_LOADERS) Log.d(TAG, "step 2.2: Update icon cache");
714 updateIconCache();
715
716 // Take a break
717 if (DEBUG_LOADERS) Log.d(TAG, "step 2 completed, wait for idle");
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700718 waitForIdle();
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800719 verifyNotStopped();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700720
721 // third step
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800722 if (DEBUG_LOADERS) Log.d(TAG, "step 3.1: loading deep shortcuts");
723 loadDeepShortcuts();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400724
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800725 verifyNotStopped();
726 if (DEBUG_LOADERS) Log.d(TAG, "step 3.2: bind deep shortcuts");
727 bindDeepShortcuts();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400728
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800729 synchronized (mLock) {
730 // Everything loaded bind the data.
731 mModelLoaded = true;
732 mHasLoaderCompletedOnce = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400733 }
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800734 } catch (CancellationException e) {
735 // Loader stopped, ignore
736 } finally {
737 // Clear out this reference, otherwise we end up holding it until all of the
738 // callback runnables are done.
739 mContext = null;
740
741 synchronized (mLock) {
742 // If we are still the last one to be scheduled, remove ourselves.
743 if (mLoaderTask == this) {
744 mLoaderTask = null;
745 }
746 mIsLoaderTaskRunning = false;
747 }
Joe Onorato36115782010-06-17 13:28:48 -0400748 }
Joe Onorato36115782010-06-17 13:28:48 -0400749 }
750
751 public void stopLocked() {
752 synchronized (LoaderTask.this) {
753 mStopped = true;
754 this.notify();
755 }
756 }
757
758 /**
759 * Gets the callbacks object. If we've been stopped, or if the launcher object
760 * has somehow been garbage collected, return null instead. Pass in the Callbacks
761 * object that was around when the deferred message was scheduled, and if there's
762 * a new Callbacks object around then also return null. This will save us from
763 * calling onto it with data that will be ignored.
764 */
765 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
766 synchronized (mLock) {
767 if (mStopped) {
768 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -0400769 }
Joe Onorato36115782010-06-17 13:28:48 -0400770
771 if (mCallbacks == null) {
772 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -0400773 }
Joe Onorato36115782010-06-17 13:28:48 -0400774
775 final Callbacks callbacks = mCallbacks.get();
776 if (callbacks != oldCallbacks) {
777 return null;
778 }
779 if (callbacks == null) {
780 Log.w(TAG, "no mCallbacks");
781 return null;
782 }
783
784 return callbacks;
785 }
786 }
787
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800788 private void loadWorkspace() {
Sunny Goyale26d1002016-06-20 14:52:14 -0700789 if (LauncherAppState.PROFILE_STARTUP) {
790 Trace.beginSection("Loading Workspace");
791 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400792
Joe Onorato36115782010-06-17 13:28:48 -0400793 final Context context = mContext;
794 final ContentResolver contentResolver = context.getContentResolver();
Sunny Goyal342e4662017-02-02 15:21:08 -0800795 final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
796 final boolean isSafeMode = pmHelper.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700797 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530798 final DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(context);
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700799 final boolean isSdCardReady = Utilities.isBootCompleted();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800800 final MultiHashMap<UserHandle, String> pendingPackages = new MultiHashMap<>();
Joe Onorato3c2f7e12009-10-31 19:17:31 -0400801
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700802 boolean clearDb = false;
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700803 try {
804 ImportDataTask.performImportIfPossible(context);
805 } catch (Exception e) {
806 // Migration failed. Clear workspace.
807 clearDb = true;
808 }
809
810 if (!clearDb && GridSizeMigrationTask.ENABLED &&
Sunny Goyalf076eae2016-01-11 12:25:10 -0800811 !GridSizeMigrationTask.migrateGridIfNeeded(mContext)) {
812 // Migration failed. Clear workspace.
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700813 clearDb = true;
Sunny Goyale5bb7052015-07-27 14:36:07 -0700814 }
815
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700816 if (clearDb) {
Sunny Goyala1365452015-10-01 15:46:24 -0700817 Log.d(TAG, "loadWorkspace: resetting launcher database");
Sunny Goyald2497482015-09-22 18:24:19 -0700818 LauncherSettings.Settings.call(contentResolver,
Sunny Goyale05b08f2017-02-23 18:30:22 -0800819 LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
Dan Sandlerd5024042014-01-09 15:01:33 -0500820 }
821
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700822 Log.d(TAG, "loadWorkspace: loading default favorites");
823 LauncherSettings.Settings.call(contentResolver,
824 LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES);
Adam Cohene25af792013-06-06 23:08:25 -0700825
Sunny Goyale9956a72016-09-01 17:24:47 -0700826 synchronized (sBgDataModel) {
827 sBgDataModel.clear();
828
Sunny Goyal756adbc2015-04-16 15:20:51 -0700829 final HashMap<String, Integer> installingPkgs = PackageInstallerCompat
Sunny Goyal94485362014-09-18 16:13:58 -0700830 .getInstance(mContext).updateAndGetActiveSessionCache();
Sunny Goyale9956a72016-09-01 17:24:47 -0700831 sBgDataModel.workspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
Romain Guy5c16f3e2010-01-12 17:24:58 -0800832
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700833 Map<ShortcutKey, ShortcutInfoCompat> shortcutKeyToPinnedShortcuts = new HashMap<>();
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800834 final LoaderCursor c = new LoaderCursor(contentResolver.query(
835 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null), mApp);
Daniel Sandler8802e962010-05-26 16:28:16 -0400836
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800837 HashMap<ComponentKey, AppWidgetProviderInfo> widgetProvidersMap = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400838
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700839 try {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700840 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
841 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -0400842 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
843 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700844 final int spanXIndex = c.getColumnIndexOrThrow
845 (LauncherSettings.Favorites.SPANX);
846 final int spanYIndex = c.getColumnIndexOrThrow(
847 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800848 final int rankIndex = c.getColumnIndexOrThrow(
849 LauncherSettings.Favorites.RANK);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700850 final int optionsIndex = c.getColumnIndexOrThrow(
851 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400852
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800853 final LongSparseArray<UserHandle> allUsers = c.allUsers;
Kenny Guyff05f432016-01-22 17:48:29 +0000854 final LongSparseArray<Boolean> quietMode = new LongSparseArray<>();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700855 final LongSparseArray<Boolean> unlockedUsers = new LongSparseArray<>();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800856 for (UserHandle user : mUserManager.getUserProfiles()) {
Kenny Guyff05f432016-01-22 17:48:29 +0000857 long serialNo = mUserManager.getSerialNumberForUser(user);
858 allUsers.put(serialNo, user);
859 quietMode.put(serialNo, mUserManager.isQuietModeEnabled(user));
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700860
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700861 boolean userUnlocked = mUserManager.isUserUnlocked(user);
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700862
863 // We can only query for shortcuts when the user is unlocked.
864 if (userUnlocked) {
Sunny Goyal49f4f032016-08-01 15:45:49 -0700865 List<ShortcutInfoCompat> pinnedShortcuts =
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530866 shortcutManager.queryForPinnedShortcuts(null, user);
867 if (shortcutManager.wasLastCallSuccess()) {
Sunny Goyal49f4f032016-08-01 15:45:49 -0700868 for (ShortcutInfoCompat shortcut : pinnedShortcuts) {
869 shortcutKeyToPinnedShortcuts.put(ShortcutKey.fromInfo(shortcut),
870 shortcut);
871 }
872 } else {
873 // Shortcut manager can fail due to some race condition when the
874 // lock state changes too frequently. For the purpose of the loading
875 // shortcuts, consider the user is still locked.
876 userUnlocked = false;
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700877 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700878 }
Sunny Goyal49f4f032016-08-01 15:45:49 -0700879 unlockedUsers.put(serialNo, userUnlocked);
Sunny Goyal7f834d22015-04-21 10:10:23 -0700880 }
881
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700882 ShortcutInfo info;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700883 LauncherAppWidgetInfo appWidgetInfo;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700884 Intent intent;
Sunny Goyal81e44912017-01-14 15:05:14 -0800885 String targetPkg;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400886
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700887 while (!mStopped && c.moveToNext()) {
888 try {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800889 if (c.user == null) {
890 // User has been deleted, remove the item.
891 c.markDeleted("User has been deleted");
892 continue;
893 }
894
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700895 boolean allowMissingTarget = false;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800896 switch (c.itemType) {
Sunny Goyal81e44912017-01-14 15:05:14 -0800897 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700898 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700899 case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
Sunny Goyal81e44912017-01-14 15:05:14 -0800900 intent = c.parseIntent();
901 if (intent == null) {
902 c.markDeleted("Invalid or null intent");
903 continue;
904 }
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800905
Sunny Goyal81e44912017-01-14 15:05:14 -0800906 int disabledState = quietMode.get(c.serialNumber) ?
907 ShortcutInfo.FLAG_DISABLED_QUIET_USER : 0;
908 ComponentName cn = intent.getComponent();
909 targetPkg = cn == null ? intent.getPackage() : cn.getPackageName();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700910
Sunny Goyal81e44912017-01-14 15:05:14 -0800911 if (!Process.myUserHandle().equals(c.user)) {
912 if (c.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
913 c.markDeleted("Legacy shortcuts are only allowed for default user");
914 continue;
915 } else if (c.restoreFlag != 0) {
916 // Don't restore items for other profiles.
917 c.markDeleted("Restore from managed profile not supported");
918 continue;
919 }
920 }
921 if (TextUtils.isEmpty(targetPkg) &&
922 c.itemType != LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
923 c.markDeleted("Only legacy shortcuts can have null package");
924 continue;
925 }
Sunny Goyal34942622014-08-29 17:20:55 -0700926
Sunny Goyal81e44912017-01-14 15:05:14 -0800927 // If there is no target package, its an implicit intent
928 // (legacy shortcut) which is always valid
929 boolean validTarget = TextUtils.isEmpty(targetPkg) ||
930 launcherApps.isPackageEnabledForProfile(targetPkg, c.user);
Sunny Goyal94485362014-09-18 16:13:58 -0700931
Sunny Goyal81e44912017-01-14 15:05:14 -0800932 if (cn != null && validTarget) {
933 // If the apk is present and the shortcut points to a specific
934 // component.
935
936 // If the component is already present
937 if (launcherApps.isActivityEnabledForProfile(cn, c.user)) {
938 // no special handling necessary for this item
939 c.markRestored();
940 } else {
941 if (c.hasRestoreFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
942 // We allow auto install apps to have their intent
943 // updated after an install.
Sunny Goyal342e4662017-02-02 15:21:08 -0800944 intent = pmHelper.getAppLaunchIntent(targetPkg, c.user);
Sunny Goyal81e44912017-01-14 15:05:14 -0800945 if (intent != null) {
946 c.restoreFlag = 0;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800947 c.updater().put(
Sunny Goyal81e44912017-01-14 15:05:14 -0800948 LauncherSettings.Favorites.INTENT,
949 intent.toUri(0)).commit();
950 cn = intent.getComponent();
Sunny Goyalb05a00a2016-08-29 10:06:57 -0700951 } else {
Sunny Goyal81e44912017-01-14 15:05:14 -0800952 c.markDeleted("Unable to find a launch target");
Sunny Goyal94485362014-09-18 16:13:58 -0700953 continue;
954 }
Sunny Goyal1a745e82014-10-02 15:58:31 -0700955 } else {
Sunny Goyal81e44912017-01-14 15:05:14 -0800956 // The app is installed but the component is no
957 // longer available.
958 c.markDeleted("Invalid component removed: " + cn);
Sunny Goyal1a745e82014-10-02 15:58:31 -0700959 continue;
Winson Chungee055712013-07-30 14:46:24 -0700960 }
Winson Chungee055712013-07-30 14:46:24 -0700961 }
Sunny Goyal81e44912017-01-14 15:05:14 -0800962 }
963 // else if cn == null => can't infer much, leave it
964 // else if !validPkg => could be restored icon or missing sd-card
965
966 if (!TextUtils.isEmpty(targetPkg) && !validTarget) {
967 // Points to a valid app (superset of cn != null) but the apk
968 // is not available.
969
970 if (c.restoreFlag != 0) {
971 // Package is not yet available but might be
972 // installed later.
973 FileLog.d(TAG, "package not yet restored: " + targetPkg);
974
975 if (c.hasRestoreFlag(ShortcutInfo.FLAG_RESTORE_STARTED)) {
976 // Restore has started once.
977 } else if (installingPkgs.containsKey(targetPkg)) {
978 // App restore has started. Update the flag
979 c.restoreFlag |= ShortcutInfo.FLAG_RESTORE_STARTED;
980 c.updater().commit();
981 } else {
982 c.markDeleted("Unrestored app removed: " + targetPkg);
983 continue;
984 }
Sunny Goyal342e4662017-02-02 15:21:08 -0800985 } else if (pmHelper.isAppOnSdcard(targetPkg)) {
Sunny Goyal81e44912017-01-14 15:05:14 -0800986 // Package is present but not available.
987 disabledState |= ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
988 // Add the icon on the workspace anyway.
989 allowMissingTarget = true;
990 } else if (!isSdCardReady) {
991 // SdCard is not ready yet. Package might get available,
992 // once it is ready.
993 Log.d(TAG, "Missing pkg, will check later: " + targetPkg);
994 pendingPackages.addToList(c.user, targetPkg);
995 // Add the icon on the workspace anyway.
996 allowMissingTarget = true;
997 } else {
998 // Do not wait for external media load anymore.
999 c.markDeleted("Invalid package removed: " + targetPkg);
1000 continue;
1001 }
1002 }
1003
1004 if (validTarget) {
1005 // The shortcut points to a valid target (either no target
1006 // or something which is ready to be used)
1007 c.markRestored();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001008 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001009
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001010 boolean useLowResIcon = !c.isOnWorkspaceOrHotseat() &&
Sunny Goyal34b65272015-03-11 16:56:52 -07001011 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
1012
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001013 if (c.restoreFlag != 0) {
Sunny Goyal81e44912017-01-14 15:05:14 -08001014 // Already verified above that user is same as default user
1015 info = c.getRestoredItemInfo(intent);
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001016 } else if (c.itemType ==
Chris Wrenf4d08112014-01-16 18:13:56 -05001017 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001018 info = c.getAppShortcutInfo(
1019 intent, allowMissingTarget, useLowResIcon);
1020 } else if (c.itemType ==
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001021 LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001022
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001023 ShortcutKey key = ShortcutKey.fromIntent(intent, c.user);
1024 if (unlockedUsers.get(c.serialNumber)) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001025 ShortcutInfoCompat pinnedShortcut =
1026 shortcutKeyToPinnedShortcuts.get(key);
1027 if (pinnedShortcut == null) {
1028 // The shortcut is no longer valid.
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001029 c.markDeleted("Pinned shortcut not found");
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001030 continue;
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001031 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001032 info = new ShortcutInfo(pinnedShortcut, context);
Sunny Goyal1b072632017-01-18 11:30:23 -08001033 info.iconBitmap = LauncherIcons
1034 .createShortcutIcon(pinnedShortcut, context);
Charles He3ff90472017-02-15 12:22:56 +00001035 if (pmHelper.isAppSuspended(
1036 info.getTargetComponent().getPackageName(),
1037 info.user)) {
1038 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
1039 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001040 intent = info.intent;
1041 } else {
1042 // Create a shortcut info in disabled mode for now.
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001043 info = c.loadSimpleShortcut();
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001044 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_LOCKED_USER;
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001045 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001046 } else { // item type == ITEM_TYPE_SHORTCUT
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001047 info = c.loadSimpleShortcut();
Michael Jurka96879562012-03-22 05:54:33 -07001048
Sunny Goyald09c3702016-04-06 16:18:20 -07001049 // Shortcuts are only available on the primary profile
Sunny Goyal342e4662017-02-02 15:21:08 -08001050 if (pmHelper.isAppSuspended(targetPkg)) {
Sunny Goyald09c3702016-04-06 16:18:20 -07001051 disabledState |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
1052 }
1053
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001054 // App shortcuts that used to be automatically added to Launcher
1055 // didn't always have the correct intent flags set, so do that
1056 // here
1057 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001058 intent.getCategories() != null &&
1059 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001060 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001061 intent.addFlags(
1062 Intent.FLAG_ACTIVITY_NEW_TASK |
1063 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1064 }
Michael Jurka96879562012-03-22 05:54:33 -07001065 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001066
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001067 if (info != null) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001068 c.applyCommonProperties(info);
1069
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001070 info.intent = intent;
Sunny Goyal08f72612015-01-05 13:41:43 -08001071 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001072 info.spanX = 1;
1073 info.spanY = 1;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001074 // TODO: Remove this extra. Instead we should be using
1075 // itemInfo#user.
1076 info.intent.putExtra(ItemInfo.EXTRA_PROFILE, c.serialNumber);
Sunny Goyald09c3702016-04-06 16:18:20 -07001077 info.isDisabled |= disabledState;
Sunny Goyal1a745e82014-10-02 15:58:31 -07001078 if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
1079 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
1080 }
Adam Cohenae4409d2013-11-26 10:34:59 -08001081
Sunny Goyal81e44912017-01-14 15:05:14 -08001082 if (c.restoreFlag != 0 && !TextUtils.isEmpty(targetPkg)) {
1083 Integer progress = installingPkgs.get(targetPkg);
1084 if (progress != null) {
1085 info.setInstallProgress(progress);
1086 } else {
1087 info.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
Sunny Goyal756adbc2015-04-16 15:20:51 -07001088 }
1089 }
1090
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001091 c.checkAndAddItem(info, sBgDataModel);
Winson Chung1323b482013-08-05 12:41:55 -07001092 } else {
1093 throw new RuntimeException("Unexpected null ShortcutInfo");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001094 }
1095 break;
1096
1097 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001098 FolderInfo folderInfo = sBgDataModel.findOrMakeFolder(c.id);
1099 c.applyCommonProperties(folderInfo);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001100
Sunny Goyala508e4f2015-05-21 09:33:57 -07001101 // Do not trim the folder label, as is was set by the user.
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001102 folderInfo.title = c.getString(c.titleIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001103 folderInfo.spanX = 1;
1104 folderInfo.spanY = 1;
Sunny Goyal5d85c442015-03-10 13:14:47 -07001105 folderInfo.options = c.getInt(optionsIndex);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001106
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001107 // no special handling required for restored folders
1108 c.markRestored();
Chris Wrenf4d08112014-01-16 18:13:56 -05001109
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001110 c.checkAndAddItem(folderInfo, sBgDataModel);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001111 break;
1112
1113 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
Adam Cohen59400422014-03-05 18:07:04 -08001114 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001115 // Read all Launcher-specific widget details
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001116 boolean customWidget = c.itemType ==
Adam Cohen59400422014-03-05 18:07:04 -08001117 LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
1118
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001119 int appWidgetId = c.getInt(appWidgetIdIndex);
Chris Wrenc3919c02013-09-18 09:48:33 -04001120 String savedProvider = c.getString(appWidgetProviderIndex);
Sunny Goyal7f834d22015-04-21 10:10:23 -07001121
Sunny Goyalff572272014-07-23 13:58:07 -07001122 final ComponentName component =
1123 ComponentName.unflattenFromString(savedProvider);
Joe Onorato36115782010-06-17 13:28:48 -04001124
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001125 final boolean isIdValid = !c.hasRestoreFlag(
1126 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID);
1127 final boolean wasProviderReady = !c.hasRestoreFlag(
1128 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY);
Sunny Goyal651077b2014-06-30 14:15:31 -07001129
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001130 if (widgetProvidersMap == null) {
1131 widgetProvidersMap = AppWidgetManagerCompat
1132 .getInstance(mContext).getAllProvidersMap();
1133 }
1134 final AppWidgetProviderInfo provider = widgetProvidersMap.get(
1135 new ComponentKey(
Robin Lee26ace122015-03-16 19:41:43 +00001136 ComponentName.unflattenFromString(savedProvider),
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001137 c.user));
Sunny Goyalff572272014-07-23 13:58:07 -07001138
1139 final boolean isProviderReady = isValidProvider(provider);
Adam Cohen59400422014-03-05 18:07:04 -08001140 if (!isSafeMode && !customWidget &&
1141 wasProviderReady && !isProviderReady) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001142 c.markDeleted(
1143 "Deleting widget that isn't installed anymore: "
Sunny Goyala1365452015-10-01 15:46:24 -07001144 + provider);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001145 } else {
Sunny Goyalff572272014-07-23 13:58:07 -07001146 if (isProviderReady) {
Sunny Goyal651077b2014-06-30 14:15:31 -07001147 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
1148 provider.provider);
Adam Cohen59400422014-03-05 18:07:04 -08001149
Sunny Goyal53f96722015-07-13 19:54:53 -07001150 // The provider is available. So the widget is either
1151 // available or not available. We do not need to track
1152 // any future restore updates.
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001153 int status = c.restoreFlag &
Sunny Goyal53f96722015-07-13 19:54:53 -07001154 ~LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyalff572272014-07-23 13:58:07 -07001155 if (!wasProviderReady) {
1156 // If provider was not previously ready, update the
1157 // status and UI flag.
1158
1159 // Id would be valid only if the widget restore broadcast was received.
1160 if (isIdValid) {
Sunny Goyal86df1382016-08-10 15:03:22 -07001161 status |= LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
Sunny Goyalff572272014-07-23 13:58:07 -07001162 } else {
1163 status &= ~LauncherAppWidgetInfo
1164 .FLAG_PROVIDER_NOT_READY;
1165 }
1166 }
1167 appWidgetInfo.restoreStatus = status;
Sunny Goyal651077b2014-06-30 14:15:31 -07001168 } else {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001169 Log.v(TAG, "Widget restore pending id=" + c.id
Sunny Goyal651077b2014-06-30 14:15:31 -07001170 + " appWidgetId=" + appWidgetId
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001171 + " status =" + c.restoreFlag);
Sunny Goyal651077b2014-06-30 14:15:31 -07001172 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
Sunny Goyalff572272014-07-23 13:58:07 -07001173 component);
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001174 appWidgetInfo.restoreStatus = c.restoreFlag;
Sunny Goyal756adbc2015-04-16 15:20:51 -07001175 Integer installProgress = installingPkgs.get(component.getPackageName());
Sunny Goyal94485362014-09-18 16:13:58 -07001176
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001177 if (c.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_RESTORE_STARTED)) {
Sunny Goyal94485362014-09-18 16:13:58 -07001178 // Restore has started once.
Sunny Goyal756adbc2015-04-16 15:20:51 -07001179 } else if (installProgress != null) {
Sunny Goyal94485362014-09-18 16:13:58 -07001180 // App restore has started. Update the flag
1181 appWidgetInfo.restoreStatus |=
1182 LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
Sunny Goyalb05a00a2016-08-29 10:06:57 -07001183 } else if (!isSafeMode) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001184 c.markDeleted("Unrestored widget removed: " + component);
Sunny Goyal94485362014-09-18 16:13:58 -07001185 continue;
1186 }
Sunny Goyal756adbc2015-04-16 15:20:51 -07001187
1188 appWidgetInfo.installProgress =
1189 installProgress == null ? 0 : installProgress;
Sunny Goyal651077b2014-06-30 14:15:31 -07001190 }
Sunny Goyal86df1382016-08-10 15:03:22 -07001191 if (appWidgetInfo.hasRestoreFlag(
1192 LauncherAppWidgetInfo.FLAG_DIRECT_CONFIG)) {
Sunny Goyal81e44912017-01-14 15:05:14 -08001193 appWidgetInfo.bindOptions = c.parseIntent();
Sunny Goyal86df1382016-08-10 15:03:22 -07001194 }
Sunny Goyalff572272014-07-23 13:58:07 -07001195
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001196 c.applyCommonProperties(appWidgetInfo);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001197 appWidgetInfo.spanX = c.getInt(spanXIndex);
1198 appWidgetInfo.spanY = c.getInt(spanYIndex);
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001199 appWidgetInfo.user = c.user;
Joe Onorato36115782010-06-17 13:28:48 -04001200
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001201 if (!c.isOnWorkspaceOrHotseat()) {
1202 c.markDeleted("Widget found where container != " +
Sunny Goyal41cdc8d2015-09-04 12:53:04 -07001203 "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001204 continue;
1205 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001206
Adam Cohen59400422014-03-05 18:07:04 -08001207 if (!customWidget) {
1208 String providerName =
1209 appWidgetInfo.providerName.flattenToString();
1210 if (!providerName.equals(savedProvider) ||
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001211 (appWidgetInfo.restoreStatus != c.restoreFlag)) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001212 c.updater()
1213 .put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
1214 providerName)
1215 .put(LauncherSettings.Favorites.RESTORED,
1216 appWidgetInfo.restoreStatus)
1217 .commit();
Adam Cohen59400422014-03-05 18:07:04 -08001218 }
Chris Wrenc3919c02013-09-18 09:48:33 -04001219 }
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001220 c.checkAndAddItem(appWidgetInfo, sBgDataModel);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001221 }
Joe Onorato36115782010-06-17 13:28:48 -04001222 break;
1223 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001224 } catch (Exception e) {
Sunny Goyala1365452015-10-01 15:46:24 -07001225 Log.e(TAG, "Desktop items loading interrupted", e);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001226 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001227 }
1228 } finally {
Sunny Goyal713edfc2016-05-06 09:58:34 -07001229 Utilities.closeSilently(c);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001230 }
1231
Winson Chungba9c37f2013-08-30 14:11:37 -07001232 // Break early if we've stopped loading
1233 if (mStopped) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001234 sBgDataModel.clear();
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001235 return;
Winson Chungba9c37f2013-08-30 14:11:37 -07001236 }
1237
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001238 // Remove dead items
1239 if (c.commitDeleted()) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -07001240 // Remove any empty folder
Sunny Goyald2497482015-09-22 18:24:19 -07001241 ArrayList<Long> deletedFolderIds = (ArrayList<Long>) LauncherSettings.Settings
1242 .call(contentResolver,
1243 LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS)
1244 .getSerializable(LauncherSettings.Settings.EXTRA_VALUE);
1245 for (long folderId : deletedFolderIds) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001246 sBgDataModel.workspaceItems.remove(sBgDataModel.folders.get(folderId));
1247 sBgDataModel.folders.remove(folderId);
1248 sBgDataModel.itemsIdMap.remove(folderId);
Romain Guy5c16f3e2010-01-12 17:24:58 -08001249 }
1250 }
1251
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001252 // Unpin shortcuts that don't exist on the workspace.
Sunny Goyalf75baa92016-11-22 03:23:51 +05301253 HashSet<ShortcutKey> pendingShortcuts =
1254 InstallShortcutReceiver.getPendingShortcuts(context);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001255 for (ShortcutKey key : shortcutKeyToPinnedShortcuts.keySet()) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001256 MutableInt numTimesPinned = sBgDataModel.pinnedShortcutCounts.get(key);
Sunny Goyalf75baa92016-11-22 03:23:51 +05301257 if ((numTimesPinned == null || numTimesPinned.value == 0)
1258 && !pendingShortcuts.contains(key)) {
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001259 // Shortcut is pinned but doesn't exist on the workspace; unpin it.
Sunny Goyaldde4fd92016-11-21 16:02:39 +05301260 shortcutManager.unpinShortcut(key);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001261 }
1262 }
1263
Jon Miranda655ec422017-02-07 11:40:22 -08001264 FolderIconPreviewVerifier verifier =
1265 new FolderIconPreviewVerifier(mApp.getInvariantDeviceProfile());
1266 // Sort the folder items and make sure all items in the preview are high resolution.
Sunny Goyale9956a72016-09-01 17:24:47 -07001267 for (FolderInfo folder : sBgDataModel.folders) {
Sunny Goyal317698b2015-07-29 11:45:41 -07001268 Collections.sort(folder.contents, Folder.ITEM_POS_COMPARATOR);
Jon Miranda655ec422017-02-07 11:40:22 -08001269 verifier.setFolderInfo(folder);
1270
1271 int numItemsInPreview = 0;
Sunny Goyal317698b2015-07-29 11:45:41 -07001272 for (ShortcutInfo info : folder.contents) {
Jon Miranda655ec422017-02-07 11:40:22 -08001273 if (info.usingLowResIcon
1274 && info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
1275 && verifier.isItemInPreview(info.rank)) {
Sunny Goyal3fe4a142016-12-15 17:40:07 -08001276 mIconCache.getTitleAndIcon(info, false);
Jon Miranda655ec422017-02-07 11:40:22 -08001277 numItemsInPreview++;
Sunny Goyal317698b2015-07-29 11:45:41 -07001278 }
Jon Miranda655ec422017-02-07 11:40:22 -08001279
1280 if (numItemsInPreview >= FolderIcon.NUM_ITEMS_IN_PREVIEW) {
Sunny Goyal317698b2015-07-29 11:45:41 -07001281 break;
1282 }
1283 }
1284 }
1285
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001286 c.commitRestoredItems();
Sunny Goyalc2936bc2016-09-01 15:50:36 -07001287 if (!isSdCardReady && !pendingPackages.isEmpty()) {
1288 context.registerReceiver(
1289 new SdCardAvailableReceiver(
1290 LauncherModel.this, mContext, pendingPackages),
Sunny Goyal25aba0a2015-07-16 15:07:47 -07001291 new IntentFilter(Intent.ACTION_BOOT_COMPLETED),
Sunny Goyalc2936bc2016-09-01 15:50:36 -07001292 null,
1293 sWorker);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001294 }
1295
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001296 // Remove any empty screens
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001297 ArrayList<Long> unusedScreens = new ArrayList<>(sBgDataModel.workspaceScreens);
Sunny Goyale9956a72016-09-01 17:24:47 -07001298 for (ItemInfo item: sBgDataModel.itemsIdMap) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001299 long screenId = item.screenId;
1300 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1301 unusedScreens.contains(screenId)) {
1302 unusedScreens.remove(screenId);
1303 }
1304 }
1305
1306 // If there are any empty screens remove them, and update.
1307 if (unusedScreens.size() != 0) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001308 sBgDataModel.workspaceScreens.removeAll(unusedScreens);
1309 updateWorkspaceScreenOrder(context, sBgDataModel.workspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001310 }
Joe Onorato36115782010-06-17 13:28:48 -04001311 }
Sunny Goyale26d1002016-06-20 14:52:14 -07001312 if (LauncherAppState.PROFILE_STARTUP) {
1313 Trace.endSection();
1314 }
Adam Cohene25af792013-06-06 23:08:25 -07001315 }
1316
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001317 /** Filters the set of items who are directly or indirectly (via another container) on the
1318 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08001319 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001320 ArrayList<ItemInfo> allWorkspaceItems,
1321 ArrayList<ItemInfo> currentScreenItems,
1322 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001323 // Purge any null ItemInfos
1324 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1325 while (iter.hasNext()) {
1326 ItemInfo i = iter.next();
1327 if (i == null) {
1328 iter.remove();
1329 }
1330 }
1331
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001332 // Order the set of items by their containers first, this allows use to walk through the
1333 // list sequentially, build up a list of containers that are in the specified screen,
1334 // as well as all items in those containers.
1335 Set<Long> itemsOnScreen = new HashSet<Long>();
1336 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1337 @Override
1338 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson12fb9fc2015-10-01 15:34:08 -07001339 return Utilities.longCompare(lhs.container, rhs.container);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001340 }
1341 });
1342 for (ItemInfo info : allWorkspaceItems) {
1343 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08001344 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001345 currentScreenItems.add(info);
1346 itemsOnScreen.add(info.id);
1347 } else {
1348 otherScreenItems.add(info);
1349 }
1350 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1351 currentScreenItems.add(info);
1352 itemsOnScreen.add(info.id);
1353 } else {
1354 if (itemsOnScreen.contains(info.container)) {
1355 currentScreenItems.add(info);
1356 itemsOnScreen.add(info.id);
1357 } else {
1358 otherScreenItems.add(info);
1359 }
1360 }
1361 }
1362 }
1363
1364 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08001365 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001366 ArrayList<LauncherAppWidgetInfo> appWidgets,
1367 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1368 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001369
1370 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001371 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001372 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08001373 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001374 currentScreenWidgets.add(widget);
1375 } else {
1376 otherScreenWidgets.add(widget);
1377 }
1378 }
1379 }
1380
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1382 * right) */
1383 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Sunny Goyal87f784c2017-01-11 10:48:34 -08001384 final InvariantDeviceProfile profile = mApp.getInvariantDeviceProfile();
Winson Chung882a52e2015-07-08 14:32:26 -07001385 final int screenCols = profile.numColumns;
1386 final int screenCellCount = profile.numColumns * profile.numRows;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001387 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001388 @Override
1389 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung882a52e2015-07-08 14:32:26 -07001390 if (lhs.container == rhs.container) {
1391 // Within containers, order by their spatial position in that container
1392 switch ((int) lhs.container) {
1393 case LauncherSettings.Favorites.CONTAINER_DESKTOP: {
1394 long lr = (lhs.screenId * screenCellCount +
1395 lhs.cellY * screenCols + lhs.cellX);
1396 long rr = (rhs.screenId * screenCellCount +
1397 rhs.cellY * screenCols + rhs.cellX);
Winson722e8562015-10-07 13:04:30 -07001398 return Utilities.longCompare(lr, rr);
Winson Chung882a52e2015-07-08 14:32:26 -07001399 }
1400 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: {
1401 // We currently use the screen id as the rank
Winson722e8562015-10-07 13:04:30 -07001402 return Utilities.longCompare(lhs.screenId, rhs.screenId);
Winson Chung882a52e2015-07-08 14:32:26 -07001403 }
1404 default:
Sunny Goyal6c56c682015-07-16 14:09:05 -07001405 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Winson Chung882a52e2015-07-08 14:32:26 -07001406 throw new RuntimeException("Unexpected container type when " +
1407 "sorting workspace items.");
1408 }
1409 return 0;
1410 }
1411 } else {
1412 // Between containers, order by hotseat, desktop
Winson722e8562015-10-07 13:04:30 -07001413 return Utilities.longCompare(lhs.container, rhs.container);
Winson Chung882a52e2015-07-08 14:32:26 -07001414 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001415 }
1416 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001417 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001418
Adam Cohendcd297f2013-06-18 13:13:40 -07001419 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
1420 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001421 final Runnable r = new Runnable() {
1422 @Override
1423 public void run() {
1424 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1425 if (callbacks != null) {
1426 callbacks.bindScreens(orderedScreens);
1427 }
1428 }
1429 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001430 runOnMainThread(r);
Adam Cohendcd297f2013-06-18 13:13:40 -07001431 }
1432
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001433 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1434 final ArrayList<ItemInfo> workspaceItems,
1435 final ArrayList<LauncherAppWidgetInfo> appWidgets,
Sunny Goyal527c7d32015-08-28 15:19:36 -07001436 final Executor executor) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001437
1438 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001439 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001440 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001441 final int start = i;
1442 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001443 final Runnable r = new Runnable() {
1444 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001445 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001446 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001447 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07001448 callbacks.bindItems(workspaceItems, start, start+chunkSize,
1449 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001450 }
1451 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001452 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001453 executor.execute(r);
Joe Onorato36115782010-06-17 13:28:48 -04001454 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001455
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001456 // Bind the widgets, one at a time
1457 N = appWidgets.size();
1458 for (int i = 0; i < N; i++) {
1459 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1460 final Runnable r = new Runnable() {
1461 public void run() {
1462 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1463 if (callbacks != null) {
1464 callbacks.bindAppWidget(widget);
1465 }
1466 }
1467 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001468 executor.execute(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001469 }
1470 }
1471
1472 /**
1473 * Binds all loaded data to actual views on the main thread.
1474 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001475 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001476 final long t = SystemClock.uptimeMillis();
1477 Runnable r;
1478
1479 // Don't use these two variables in any of the callback runnables.
1480 // Otherwise we hold a reference to them.
1481 final Callbacks oldCallbacks = mCallbacks.get();
1482 if (oldCallbacks == null) {
1483 // This launcher has exited and nobody bothered to tell us. Just bail.
1484 Log.w(TAG, "LoaderTask running with no launcher");
1485 return;
1486 }
1487
Winson Chung9b9fb962013-11-15 15:39:34 -08001488 // Save a copy of all the bg-thread collections
Sunny Goyal44c06432016-04-02 10:56:02 -07001489 ArrayList<ItemInfo> workspaceItems = new ArrayList<>();
1490 ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<>();
1491 ArrayList<Long> orderedScreenIds = new ArrayList<>();
Sunny Goyale2df0622015-04-24 11:27:00 -07001492
Sunny Goyale9956a72016-09-01 17:24:47 -07001493 synchronized (sBgDataModel) {
1494 workspaceItems.addAll(sBgDataModel.workspaceItems);
1495 appWidgets.addAll(sBgDataModel.appWidgets);
1496 orderedScreenIds.addAll(sBgDataModel.workspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001497 }
1498
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001499 final int currentScreen;
1500 {
1501 int currScreen = synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE
1502 ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen();
1503 if (currScreen >= orderedScreenIds.size()) {
1504 // There may be no workspace screens (just hotseat items and an empty page).
1505 currScreen = PagedView.INVALID_RESTORE_PAGE;
1506 }
1507 currentScreen = currScreen;
Winson Chung9b9fb962013-11-15 15:39:34 -08001508 }
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001509 final boolean validFirstPage = currentScreen >= 0;
1510 final long currentScreenId =
1511 validFirstPage ? orderedScreenIds.get(currentScreen) : INVALID_SCREEN_ID;
Winson Chung9b9fb962013-11-15 15:39:34 -08001512
Winson Chung9b9fb962013-11-15 15:39:34 -08001513 // Separate the items that are on the current screen, and all the other remaining items
Sunny Goyal44c06432016-04-02 10:56:02 -07001514 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
1515 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
1516 ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
1517 ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001518
Winson Chung9b9fb962013-11-15 15:39:34 -08001519 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001520 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08001521 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001522 otherAppWidgets);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001523 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1524 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1525
1526 // Tell the workspace that we're about to start binding items
1527 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001528 public void run() {
1529 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1530 if (callbacks != null) {
Sunny Goyal527c7d32015-08-28 15:19:36 -07001531 callbacks.clearPendingBinds();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001532 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001533 }
1534 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001535 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001536 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001537
Adam Cohendcd297f2013-06-18 13:13:40 -07001538 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
1539
Sunny Goyal527c7d32015-08-28 15:19:36 -07001540 Executor mainExecutor = new DeferredMainThreadExecutor();
1541 // Load items on the current page.
Sunny Goyal44c06432016-04-02 10:56:02 -07001542 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, mainExecutor);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001543
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001544 // In case of validFirstPage, only bind the first screen, and defer binding the
1545 // remaining screens after first onDraw (and an optional the fade animation whichever
1546 // happens later).
1547 // This ensures that the first screen is immediately visible (eg. during rotation)
1548 // In case of !validFirstPage, bind all pages one after other.
1549 final Executor deferredExecutor =
1550 validFirstPage ? new ViewOnDrawExecutor(mHandler) : mainExecutor;
1551
1552 mainExecutor.execute(new Runnable() {
1553 @Override
1554 public void run() {
1555 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1556 if (callbacks != null) {
1557 callbacks.finishFirstPageBind(
1558 validFirstPage ? (ViewOnDrawExecutor) deferredExecutor : null);
1559 }
1560 }
1561 });
Sunny Goyal527c7d32015-08-28 15:19:36 -07001562
Sunny Goyal44c06432016-04-02 10:56:02 -07001563 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, deferredExecutor);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001564
1565 // Tell the workspace that we're done binding items
1566 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001567 public void run() {
1568 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1569 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001570 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04001571 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001572
Sunny Goyal639e9062015-08-19 19:17:06 -07001573 mIsLoadingAndBindingWorkspace = false;
1574
1575 // Run all the bind complete runnables after workspace is bound.
1576 if (!mBindCompleteRunnables.isEmpty()) {
1577 synchronized (mBindCompleteRunnables) {
1578 for (final Runnable r : mBindCompleteRunnables) {
1579 runOnWorkerThread(r);
1580 }
1581 mBindCompleteRunnables.clear();
1582 }
1583 }
1584
Winson Chung98e030b2012-05-07 16:01:11 -07001585 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001586 if (DEBUG_LOADERS) {
1587 Log.d(TAG, "bound workspace in "
1588 + (SystemClock.uptimeMillis()-t) + "ms");
1589 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001590
Joe Onorato36115782010-06-17 13:28:48 -04001591 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001592 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001593 deferredExecutor.execute(r);
1594
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001595 if (validFirstPage) {
Sunny Goyal527c7d32015-08-28 15:19:36 -07001596 r = new Runnable() {
1597 public void run() {
1598 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1599 if (callbacks != null) {
1600 // We are loading synchronously, which means, some of the pages will be
1601 // bound after first draw. Inform the callbacks that page binding is
1602 // not complete, and schedule the remaining pages.
1603 if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
1604 callbacks.onPageBoundSynchronously(currentScreen);
1605 }
1606 callbacks.executeOnNextDraw((ViewOnDrawExecutor) deferredExecutor);
1607 }
1608 }
1609 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001610 runOnMainThread(r);
Winson Chung4a2afa32012-07-19 14:53:05 -07001611 }
Joe Onorato36115782010-06-17 13:28:48 -04001612 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001613
Sunny Goyal4e5cc642015-06-25 16:37:44 -07001614 private void updateIconCache() {
1615 // Ignore packages which have a promise icon.
1616 HashSet<String> packagesToIgnore = new HashSet<>();
Sunny Goyale9956a72016-09-01 17:24:47 -07001617 synchronized (sBgDataModel) {
1618 for (ItemInfo info : sBgDataModel.itemsIdMap) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -07001619 if (info instanceof ShortcutInfo) {
1620 ShortcutInfo si = (ShortcutInfo) info;
1621 if (si.isPromise() && si.getTargetComponent() != null) {
1622 packagesToIgnore.add(si.getTargetComponent().getPackageName());
1623 }
1624 } else if (info instanceof LauncherAppWidgetInfo) {
1625 LauncherAppWidgetInfo lawi = (LauncherAppWidgetInfo) info;
1626 if (lawi.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)) {
1627 packagesToIgnore.add(lawi.providerName.getPackageName());
1628 }
1629 }
1630 }
1631 }
1632 mIconCache.updateDbIcons(packagesToIgnore);
1633 }
1634
Joe Onorato36115782010-06-17 13:28:48 -04001635 private void onlyBindAllApps() {
1636 final Callbacks oldCallbacks = mCallbacks.get();
1637 if (oldCallbacks == null) {
1638 // This launcher has exited and nobody bothered to tell us. Just bail.
1639 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1640 return;
1641 }
1642
1643 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001644 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001645 final ArrayList<AppInfo> list
1646 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07001647 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001648 public void run() {
1649 final long t = SystemClock.uptimeMillis();
1650 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1651 if (callbacks != null) {
1652 callbacks.bindAllApplications(list);
1653 }
1654 if (DEBUG_LOADERS) {
1655 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
Hyunyoung Song747a5bc2016-02-08 11:31:33 -08001656 + (SystemClock.uptimeMillis() - t) + "ms");
Joe Onorato36115782010-06-17 13:28:48 -04001657 }
1658 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07001659 };
Tony Wickham80f57872016-06-29 18:12:15 -07001660 runOnMainThread(r);
Joe Onorato36115782010-06-17 13:28:48 -04001661 }
1662
Winson Chung64359a52013-07-08 17:17:08 -07001663 private void loadAllApps() {
1664 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04001665
Joe Onorato36115782010-06-17 13:28:48 -04001666 final Callbacks oldCallbacks = mCallbacks.get();
1667 if (oldCallbacks == null) {
1668 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07001669 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04001670 return;
1671 }
1672
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001673 final List<UserHandle> profiles = mUserManager.getUserProfiles();
Kenny Guyed131872014-04-30 03:02:21 +01001674
Winson Chung64359a52013-07-08 17:17:08 -07001675 // Clear the list of apps
1676 mBgAllAppsList.clear();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001677 for (UserHandle user : profiles) {
Kenny Guyed131872014-04-30 03:02:21 +01001678 // Query for the set of apps
1679 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Sunny Goyal3e9be432017-01-05 15:22:41 -08001680 final List<LauncherActivityInfo> apps = mLauncherApps.getActivityList(null, user);
Kenny Guyed131872014-04-30 03:02:21 +01001681 if (DEBUG_LOADERS) {
1682 Log.d(TAG, "getActivityList took "
1683 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
1684 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
1685 }
1686 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08001687 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01001688 if (apps == null || apps.isEmpty()) {
1689 return;
1690 }
Kenny Guyff05f432016-01-22 17:48:29 +00001691 boolean quietMode = mUserManager.isQuietModeEnabled(user);
Kenny Guyed131872014-04-30 03:02:21 +01001692 // Create the ApplicationInfos
1693 for (int i = 0; i < apps.size(); i++) {
Sunny Goyal3e9be432017-01-05 15:22:41 -08001694 LauncherActivityInfo app = apps.get(i);
Kenny Guyed131872014-04-30 03:02:21 +01001695 // This builds the icon bitmaps.
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001696 mBgAllAppsList.add(new AppInfo(mContext, app, user, quietMode), app);
Kenny Guyed131872014-04-30 03:02:21 +01001697 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08001698
Sunny Goyal756a28a2015-04-23 17:07:55 -07001699 final ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
1700 if (heuristic != null) {
Sunny Goyal639e9062015-08-19 19:17:06 -07001701 final Runnable r = new Runnable() {
Sunny Goyal756a28a2015-04-23 17:07:55 -07001702
1703 @Override
1704 public void run() {
1705 heuristic.processUserApps(apps);
1706 }
Sunny Goyal639e9062015-08-19 19:17:06 -07001707 };
1708 runOnMainThread(new Runnable() {
1709
1710 @Override
1711 public void run() {
1712 // Check isLoadingWorkspace on the UI thread, as it is updated on
1713 // the UI thread.
1714 if (mIsLoadingAndBindingWorkspace) {
1715 synchronized (mBindCompleteRunnables) {
1716 mBindCompleteRunnables.add(r);
1717 }
1718 } else {
1719 runOnWorkerThread(r);
1720 }
1721 }
Sunny Goyal756a28a2015-04-23 17:07:55 -07001722 });
Sunny Goyale0f58d72014-11-10 18:05:31 -08001723 }
Winson Chung64359a52013-07-08 17:17:08 -07001724 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01001725 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001726 final ArrayList<AppInfo> added = mBgAllAppsList.added;
1727 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07001728
1729 // Post callback on main thread
1730 mHandler.post(new Runnable() {
1731 public void run() {
Hyunyoung Song9892e582015-05-05 10:07:23 -07001732
Winson Chung64359a52013-07-08 17:17:08 -07001733 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07001734 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07001735 if (callbacks != null) {
1736 callbacks.bindAllApplications(added);
1737 if (DEBUG_LOADERS) {
1738 Log.d(TAG, "bound " + added.size() + " apps in "
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001739 + (SystemClock.uptimeMillis() - bindTime) + "ms");
Winson Chung64359a52013-07-08 17:17:08 -07001740 }
1741 } else {
1742 Log.i(TAG, "not binding apps: no Launcher activity");
1743 }
1744 }
1745 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001746 // Cleanup any data stored for a deleted user.
1747 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Joe Onorato36115782010-06-17 13:28:48 -04001748 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07001749 Log.d(TAG, "Icons processed in "
1750 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08001751 }
1752 }
1753
Sunny Goyaldd96a5e2017-02-17 11:22:34 -08001754 private void loadDeepShortcuts() {
1755 if (!mModelLoaded) {
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001756 sBgDataModel.deepShortcutMap.clear();
Sunny Goyaldde4fd92016-11-21 16:02:39 +05301757 DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(mContext);
1758 mHasShortcutHostPermission = shortcutManager.hasHostPermission();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001759 if (mHasShortcutHostPermission) {
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001760 for (UserHandle user : mUserManager.getUserProfiles()) {
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001761 if (mUserManager.isUserUnlocked(user)) {
Sunny Goyaldde4fd92016-11-21 16:02:39 +05301762 List<ShortcutInfoCompat> shortcuts =
1763 shortcutManager.queryForAllShortcuts(user);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001764 sBgDataModel.updateDeepShortcutMap(null, user, shortcuts);
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001765 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001766 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001767 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001768 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001769 }
Joe Onorato36115782010-06-17 13:28:48 -04001770 }
1771
Tony Wickham80f57872016-06-29 18:12:15 -07001772 public void bindDeepShortcuts() {
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001773 final MultiHashMap<ComponentKey, String> shortcutMapCopy =
1774 sBgDataModel.deepShortcutMap.clone();
Tony Wickham80f57872016-06-29 18:12:15 -07001775 Runnable r = new Runnable() {
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001776 @Override
1777 public void run() {
1778 Callbacks callbacks = getCallback();
1779 if (callbacks != null) {
1780 callbacks.bindDeepShortcutMap(shortcutMapCopy);
1781 }
1782 }
Tony Wickham80f57872016-06-29 18:12:15 -07001783 };
1784 runOnMainThread(r);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001785 }
1786
Sunny Goyal75b0f552015-05-20 21:57:06 -07001787 /**
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001788 * Refreshes the cached shortcuts if the shortcut permission has changed.
1789 * Current implementation simply reloads the workspace, but it can be optimized to
1790 * use partial updates similar to {@link UserManagerCompat}
1791 */
1792 public void refreshShortcutsIfRequired() {
Sunny Goyalf5e37442016-11-02 10:31:24 -07001793 if (Utilities.ATLEAST_NOUGAT_MR1) {
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001794 sWorker.removeCallbacks(mShortcutPermissionCheckRunnable);
1795 sWorker.post(mShortcutPermissionCheckRunnable);
1796 }
1797 }
1798
1799 /**
Sunny Goyal75b0f552015-05-20 21:57:06 -07001800 * Called when the icons for packages have been updated in the icon cache.
1801 */
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001802 public void onPackageIconsUpdated(HashSet<String> updatedPackages, UserHandle user) {
Sunny Goyal75b0f552015-05-20 21:57:06 -07001803 // If any package icon has changed (app was updated while launcher was dead),
1804 // update the corresponding shortcuts.
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001805 enqueueModelUpdateTask(new CacheDataUpdatedTask(
1806 CacheDataUpdatedTask.OP_CACHE_UPDATE, user, updatedPackages));
Sunny Goyal75b0f552015-05-20 21:57:06 -07001807 }
1808
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001809 void enqueueModelUpdateTask(BaseModelUpdateTask task) {
Jon Mirandaf28629a2017-02-23 15:12:42 -08001810 if (!mModelLoaded && mLoaderTask == null) {
1811 if (DEBUG_LOADERS) {
1812 Log.d(TAG, "enqueueModelUpdateTask Ignoring task since loader is pending=" + task);
1813 }
1814 return;
1815 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001816 task.init(this);
1817 runOnWorkerThread(task);
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001818 }
1819
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001820 /**
1821 * A task to be executed on the current callbacks on the UI thread.
1822 * If there is no current callbacks, the task is ignored.
1823 */
1824 public interface CallbackTask {
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001825
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001826 void execute(Callbacks callbacks);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001827 }
1828
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001829 /**
1830 * A runnable which changes/updates the data model of the launcher based on certain events.
1831 */
1832 public static abstract class BaseModelUpdateTask implements Runnable {
Joe Onorato36115782010-06-17 13:28:48 -04001833
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001834 private LauncherModel mModel;
1835 private DeferredHandler mUiHandler;
Joe Onorato36115782010-06-17 13:28:48 -04001836
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001837 /* package private */
1838 void init(LauncherModel model) {
1839 mModel = model;
1840 mUiHandler = mModel.mHandler;
Joe Onorato36115782010-06-17 13:28:48 -04001841 }
1842
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001843 @Override
Joe Onorato36115782010-06-17 13:28:48 -04001844 public void run() {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001845 if (!mModel.mHasLoaderCompletedOnce) {
Sunny Goyalc905efc2015-05-06 09:54:53 -07001846 // Loader has not yet run.
1847 return;
1848 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001849 execute(mModel.mApp, sBgDataModel, mModel.mBgAllAppsList);
1850 }
Joe Onorato36115782010-06-17 13:28:48 -04001851
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001852 /**
1853 * Execute the actual task. Called on the worker thread.
1854 */
1855 public abstract void execute(
1856 LauncherAppState app, BgDataModel dataModel, AllAppsList apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08001857
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001858 /**
1859 * Schedules a {@param task} to be executed on the current callbacks.
1860 */
1861 public final void scheduleCallbackTask(final CallbackTask task) {
1862 final Callbacks callbacks = mModel.getCallback();
1863 mUiHandler.post(new Runnable() {
1864 public void run() {
1865 Callbacks cb = mModel.getCallback();
1866 if (callbacks == cb && cb != null) {
1867 task.execute(callbacks);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07001868 }
1869 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001870 });
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001871 }
Sunny Goyal43bf11d2017-02-02 13:52:53 -08001872
1873 public ModelWriter getModelWriter() {
1874 // Updates from model task, do not deal with icon position in hotseat.
1875 return mModel.getWriter(false /* hasVerticalHotseat */);
1876 }
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001877 }
1878
Sunny Goyal1b072632017-01-18 11:30:23 -08001879 public void updateAndBindShortcutInfo(final ShortcutInfo si, final ShortcutInfoCompat info) {
1880 updateAndBindShortcutInfo(new Provider<ShortcutInfo>() {
1881 @Override
1882 public ShortcutInfo get() {
1883 si.updateFromDeepShortcutInfo(info, mApp.getContext());
1884 si.iconBitmap = LauncherIcons.createShortcutIcon(info, mApp.getContext());
1885 return si;
1886 }
1887 });
1888 }
1889
Sunny Goyal10923b32016-07-20 15:42:44 -07001890 /**
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001891 * Utility method to update a shortcut on the background thread.
Sunny Goyal10923b32016-07-20 15:42:44 -07001892 */
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001893 public void updateAndBindShortcutInfo(final Provider<ShortcutInfo> shortcutProvider) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001894 enqueueModelUpdateTask(new ExtendedModelTask() {
Sunny Goyal10923b32016-07-20 15:42:44 -07001895 @Override
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001896 public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001897 ShortcutInfo info = shortcutProvider.get();
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001898 ArrayList<ShortcutInfo> update = new ArrayList<>();
Sunny Goyal10923b32016-07-20 15:42:44 -07001899 update.add(info);
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001900 bindUpdatedShortcuts(update, info.user);
Sunny Goyal10923b32016-07-20 15:42:44 -07001901 }
1902 });
1903 }
1904
Sunny Goyald164b7f2016-10-12 20:49:31 -07001905 private void bindWidgetsModel(final Callbacks callbacks) {
1906 final MultiHashMap<PackageItemInfo, WidgetItem> widgets
1907 = mBgWidgetsModel.getWidgetsMap().clone();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001908 mHandler.post(new Runnable() {
1909 @Override
1910 public void run() {
1911 Callbacks cb = getCallback();
1912 if (callbacks == cb && cb != null) {
Sunny Goyald164b7f2016-10-12 20:49:31 -07001913 callbacks.bindAllWidgets(widgets);
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001914 }
Hyunyoung Songd4af1482015-04-20 20:40:03 -07001915 }
1916 });
1917 }
1918
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001919 public void refreshAndBindWidgetsAndShortcuts(
1920 final Callbacks callbacks, final boolean bindFirst) {
1921 runOnWorkerThread(new Runnable() {
1922 @Override
1923 public void run() {
1924 if (bindFirst && !mBgWidgetsModel.isEmpty()) {
Sunny Goyald164b7f2016-10-12 20:49:31 -07001925 bindWidgetsModel(callbacks);
Sunny Goyal31860582015-09-18 08:38:57 -07001926 }
Sunny Goyald164b7f2016-10-12 20:49:31 -07001927 ArrayList<WidgetItem> allWidgets = mBgWidgetsModel.update(mApp.getContext());
1928 bindWidgetsModel(callbacks);
1929
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001930 // update the Widget entries inside DB on the worker thread.
Sunny Goyal87f784c2017-01-11 10:48:34 -08001931 mApp.getWidgetCache().removeObsoletePreviews(allWidgets);
Sunny Goyal31860582015-09-18 08:38:57 -07001932 }
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001933 });
Michael Jurkac402cd92013-05-20 15:49:32 +02001934 }
1935
Sunny Goyal651077b2014-06-30 14:15:31 -07001936 static boolean isValidProvider(AppWidgetProviderInfo provider) {
1937 return (provider != null) && (provider.provider != null)
1938 && (provider.provider.getPackageName() != null);
1939 }
1940
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -08001941 public void dumpState(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1942 if (args.length > 0 && TextUtils.equals(args[0], "--all")) {
1943 writer.println(prefix + "All apps list: size=" + mBgAllAppsList.data.size());
1944 for (AppInfo info : mBgAllAppsList.data) {
1945 writer.println(prefix + " title=\"" + info.title + "\" iconBitmap=" + info.iconBitmap
1946 + " componentName=" + info.componentName.getPackageName());
1947 }
Joe Onorato36115782010-06-17 13:28:48 -04001948 }
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -08001949 sBgDataModel.dump(prefix, fd, writer, args);
Joe Onoratobe386092009-11-17 17:32:16 -08001950 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08001951
1952 public Callbacks getCallback() {
1953 return mCallbacks != null ? mCallbacks.get() : null;
1954 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001955
1956 /**
1957 * @return {@link FolderInfo} if its already loaded.
1958 */
1959 public FolderInfo findFolderById(Long folderId) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001960 synchronized (sBgDataModel) {
1961 return sBgDataModel.folders.get(folderId);
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001962 }
1963 }
Sunny Goyal756adbc2015-04-16 15:20:51 -07001964
Sunny Goyal527c7d32015-08-28 15:19:36 -07001965 @Thunk class DeferredMainThreadExecutor implements Executor {
1966
1967 @Override
1968 public void execute(Runnable command) {
1969 runOnMainThread(command);
1970 }
1971 }
1972
Sunny Goyal756adbc2015-04-16 15:20:51 -07001973 /**
1974 * @return the looper for the worker thread which can be used to start background tasks.
1975 */
1976 public static Looper getWorkerLooper() {
1977 return sWorkerThread.getLooper();
1978 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001979}