blob: 8e99d47d00fd556e94c63770bc225a9b9f1f5ad5 [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;
Sunny Goyal1b072632017-01-18 11:30:23 -080051import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal1acb9e92016-05-16 12:41:09 -070052import com.android.launcher3.logging.FileLog;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070053import com.android.launcher3.model.AddWorkspaceItemsTask;
Sunny Goyale9956a72016-09-01 17:24:47 -070054import com.android.launcher3.model.BgDataModel;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070055import com.android.launcher3.model.CacheDataUpdatedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080056import com.android.launcher3.model.ExtendedModelTask;
Sunny Goyalf862a262015-12-14 14:27:38 -080057import com.android.launcher3.model.GridSizeMigrationTask;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -080058import com.android.launcher3.model.LoaderCursor;
Sunny Goyal43bf11d2017-02-02 13:52:53 -080059import com.android.launcher3.model.ModelWriter;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070060import com.android.launcher3.model.PackageInstallStateChangedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080061import com.android.launcher3.model.PackageItemInfo;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070062import com.android.launcher3.model.PackageUpdatedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080063import com.android.launcher3.model.SdCardAvailableReceiver;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -070064import com.android.launcher3.model.ShortcutsChangedTask;
65import com.android.launcher3.model.UserLockStateChangedTask;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080066import com.android.launcher3.model.WidgetItem;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070067import com.android.launcher3.model.WidgetsModel;
Sunny Goyala5c8a9e2016-07-08 08:32:44 -070068import com.android.launcher3.provider.ImportDataTask;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070069import com.android.launcher3.provider.LauncherDbUtils;
Tony Wickhambfbf7f92016-05-19 11:19:39 -070070import com.android.launcher3.shortcuts.DeepShortcutManager;
71import com.android.launcher3.shortcuts.ShortcutInfoCompat;
72import com.android.launcher3.shortcuts.ShortcutKey;
Robin Lee26ace122015-03-16 19:41:43 +000073import com.android.launcher3.util.ComponentKey;
Sunny Goyal18bf8e22015-04-08 18:13:46 -070074import com.android.launcher3.util.ManagedProfileHeuristic;
Tony Wickhamd82a39d2016-07-01 15:44:13 -070075import com.android.launcher3.util.MultiHashMap;
Sunny Goyald09c3702016-04-06 16:18:20 -070076import com.android.launcher3.util.PackageManagerHelper;
Sunny Goyalaaf7d1d2016-05-17 13:38:54 -070077import com.android.launcher3.util.Preconditions;
Sunny Goyal2bcbe132016-11-16 09:23:42 -080078import com.android.launcher3.util.Provider;
Adam Cohen091440a2015-03-18 14:16:05 -070079import com.android.launcher3.util.Thunk;
Sunny Goyal527c7d32015-08-28 15:19:36 -070080import com.android.launcher3.util.ViewOnDrawExecutor;
Romain Guyedcce092010-03-04 13:03:17 -080081
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -080082import java.io.FileDescriptor;
83import java.io.PrintWriter;
Michael Jurkac2f801e2011-07-12 14:19:46 -070084import java.lang.ref.WeakReference;
Michael Jurkac2f801e2011-07-12 14:19:46 -070085import java.util.ArrayList;
86import java.util.Collections;
87import java.util.Comparator;
88import java.util.HashMap;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070089import java.util.HashSet;
Winson Chung2abf94d2012-07-18 18:16:38 -070090import java.util.Iterator;
Michael Jurkac2f801e2011-07-12 14:19:46 -070091import java.util.List;
Tony Wickhambfbf7f92016-05-19 11:19:39 -070092import java.util.Map;
Winson Chungb8b2a5a2012-07-12 17:55:31 -070093import java.util.Set;
Sunny Goyaldd96a5e2017-02-17 11:22:34 -080094import java.util.concurrent.CancellationException;
Sunny Goyal527c7d32015-08-28 15:19:36 -070095import java.util.concurrent.Executor;
Michael Jurkac2f801e2011-07-12 14:19:46 -070096
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097/**
98 * Maintains in-memory state of the Launcher. It is expected that there should be only one
99 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700100 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101 */
Kenny Guyed131872014-04-30 03:02:21 +0100102public class LauncherModel extends BroadcastReceiver
Kenny Guyc2bd8102014-06-30 12:30:31 +0100103 implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800104 static final boolean DEBUG_LOADERS = false;
Chris Wrenee523362014-09-09 10:09:02 -0400105 private static final boolean DEBUG_RECEIVER = false;
Chris Wrenb358f812014-04-16 13:37:00 -0400106
Joe Onorato9c1289c2009-08-17 11:03:03 -0400107 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700108
Joe Onorato36115782010-06-17 13:28:48 -0400109 private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
Derek Prothro7aff3992013-12-10 14:00:37 -0500110 private static final long INVALID_SCREEN_ID = -1L;
Winson Chunga6945242014-01-08 14:04:34 -0800111
Adam Cohen091440a2015-03-18 14:16:05 -0700112 @Thunk final LauncherAppState mApp;
113 @Thunk final Object mLock = new Object();
114 @Thunk DeferredHandler mHandler = new DeferredHandler();
115 @Thunk LoaderTask mLoaderTask;
116 @Thunk boolean mIsLoaderTaskRunning;
Sunny Goyal756a28a2015-04-23 17:07:55 -0700117 @Thunk boolean mHasLoaderCompletedOnce;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800118
Adam Cohen091440a2015-03-18 14:16:05 -0700119 @Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700120 static {
121 sWorkerThread.start();
122 }
Adam Cohen091440a2015-03-18 14:16:05 -0700123 @Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
Brad Fitzpatrick700889f2010-10-11 09:40:44 -0700124
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800125 // Indicates whether the current model data is valid or not.
126 // We start off with everything not loaded. After that, we assume that
Joe Onoratocc67f472010-06-08 10:54:30 -0700127 // our monitoring of the package manager provides all updates and we never
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800128 // need to do a requery. This is only ever touched from the loader thread.
129 private boolean mModelLoaded;
Hyunyoung Songe295aca2017-02-06 10:46:24 -0800130 public boolean isModelLoaded() {
131 synchronized (mLock) {
132 return mModelLoaded && mLoaderTask == null;
133 }
134 }
Joe Onoratocc67f472010-06-08 10:54:30 -0700135
Sunny Goyal756a28a2015-04-23 17:07:55 -0700136 /**
137 * Set of runnables to be called on the background thread after the workspace binding
138 * is complete.
139 */
140 static final ArrayList<Runnable> mBindCompleteRunnables = new ArrayList<Runnable>();
141
Adam Cohen091440a2015-03-18 14:16:05 -0700142 @Thunk WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800143
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700144 // < only access in worker thread >
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800145 private final AllAppsList mBgAllAppsList;
Hyunyoung Song9110d482015-05-22 14:49:23 -0700146 // Entire list of widgets.
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800147 private final WidgetsModel mBgWidgetsModel;
Joe Onorato0589f0f2010-02-08 13:44:00 -0800148
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700149 private boolean mHasShortcutHostPermission;
150 // Runnable to check if the shortcuts permission has changed.
151 private final Runnable mShortcutPermissionCheckRunnable = new Runnable() {
152 @Override
153 public void run() {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800154 if (mModelLoaded) {
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530155 boolean hasShortcutHostPermission =
156 DeepShortcutManager.getInstance(mApp.getContext()).hasHostPermission();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700157 if (hasShortcutHostPermission != mHasShortcutHostPermission) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800158 forceReload();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -0700159 }
160 }
161 }
162 };
163
Sunny Goyale9956a72016-09-01 17:24:47 -0700164 /**
165 * All the static data should be accessed on the background thread, A lock should be acquired
166 * on this object when accessing any data from this model.
167 */
168 static final BgDataModel sBgDataModel = new BgDataModel();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700169
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700170 // </ only access in worker thread >
171
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700172 private final IconCache mIconCache;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700174 private final LauncherAppsCompat mLauncherApps;
175 private final UserManagerCompat mUserManager;
Kenny Guyed131872014-04-30 03:02:21 +0100176
Joe Onorato9c1289c2009-08-17 11:03:03 -0400177 public interface Callbacks {
Joe Onoratoef2efcf2010-10-27 13:21:00 -0700178 public boolean setLoadOnResume();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400179 public int getCurrentWorkspaceScreen();
Sunny Goyal527c7d32015-08-28 15:19:36 -0700180 public void clearPendingBinds();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400181 public void startBinding();
Winson Chung64359a52013-07-08 17:17:08 -0700182 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
183 boolean forceAnimateIcons);
Adam Cohendcd297f2013-06-18 13:13:40 -0700184 public void bindScreens(ArrayList<Long> orderedScreenIds);
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700185 public void finishFirstPageBind(ViewOnDrawExecutor executor);
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800186 public void finishBindingItems();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400187 public void bindAppWidget(LauncherAppWidgetInfo info);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200188 public void bindAllApplications(ArrayList<AppInfo> apps);
Winson Chungd64d1762013-08-20 14:37:16 -0700189 public void bindAppsAdded(ArrayList<Long> newScreens,
190 ArrayList<ItemInfo> addNotAnimated,
Winson Chungc58497e2013-09-03 17:48:37 -0700191 ArrayList<ItemInfo> addAnimated,
192 ArrayList<AppInfo> addedApps);
Michael Jurkaeadbfc52013-09-04 00:45:37 +0200193 public void bindAppsUpdated(ArrayList<AppInfo> apps);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700194 public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800195 ArrayList<ShortcutInfo> removed, UserHandle user);
Sunny Goyal4390ace2014-10-13 11:33:11 -0700196 public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
Sunny Goyal756adbc2015-04-16 15:20:51 -0700197 public void bindRestoreItemsChange(HashSet<ItemInfo> updates);
Sunny Goyal3bbbabc2016-03-15 09:16:30 -0700198 public void bindWorkspaceComponentsRemoved(
199 HashSet<String> packageNames, HashSet<ComponentName> components,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800200 UserHandle user);
Sunny Goyal3bbbabc2016-03-15 09:16:30 -0700201 public void bindAppInfosRemoved(ArrayList<AppInfo> appInfos);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800202 public void notifyWidgetProvidersChanged();
Sunny Goyald164b7f2016-10-12 20:49:31 -0700203 public void bindAllWidgets(MultiHashMap<PackageItemInfo, WidgetItem> widgets);
Adam Cohen1462de32012-07-24 22:34:36 -0700204 public void onPageBoundSynchronously(int page);
Sunny Goyal527c7d32015-08-28 15:19:36 -0700205 public void executeOnNextDraw(ViewOnDrawExecutor executor);
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700206 public void bindDeepShortcutMap(MultiHashMap<ComponentKey, String> deepShortcutMap);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400207 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530209 LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
Winson Chunga6945242014-01-08 14:04:34 -0800210 Context context = app.getContext();
Daniel Sandlere4f98912013-06-25 15:13:26 -0400211 mApp = app;
Bjorn Bringert1307f632013-10-03 22:31:03 +0100212 mBgAllAppsList = new AllAppsList(iconCache, appFilter);
Sunny Goyald164b7f2016-10-12 20:49:31 -0700213 mBgWidgetsModel = new WidgetsModel(iconCache, appFilter);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800214 mIconCache = iconCache;
215
Kenny Guyed131872014-04-30 03:02:21 +0100216 mLauncherApps = LauncherAppsCompat.getInstance(context);
217 mUserManager = UserManagerCompat.getInstance(context);
Joe Onorato0589f0f2010-02-08 13:44:00 -0800218 }
219
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700220 /** Runs the specified runnable immediately if called from the main thread, otherwise it is
221 * posted on the main thread handler. */
Tony Wickham80f57872016-06-29 18:12:15 -0700222 private void runOnMainThread(Runnable r) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700223 if (sWorkerThread.getThreadId() == Process.myTid()) {
224 // If we are on the worker thread, post onto the main handler
225 mHandler.post(r);
226 } else {
227 r.run();
228 }
229 }
230
231 /** Runs the specified runnable immediately if called from the worker thread, otherwise it is
232 * posted on the worker thread handler. */
Tony Wickham80f57872016-06-29 18:12:15 -0700233 private static void runOnWorkerThread(Runnable r) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700234 if (sWorkerThread.getThreadId() == Process.myTid()) {
235 r.run();
236 } else {
237 // If we are not on the worker thread, then post to the worker handler
238 sWorker.post(r);
239 }
240 }
241
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700242 public void setPackageState(PackageInstallInfo installInfo) {
243 enqueueModelUpdateTask(new PackageInstallStateChangedTask(installInfo));
Chris Wrenaeff7ea2014-02-14 16:59:24 -0500244 }
245
Sunny Goyal756adbc2015-04-16 15:20:51 -0700246 /**
247 * Updates the icons and label of all pending icons for the provided package name.
248 */
249 public void updateSessionDisplayInfo(final String packageName) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700250 HashSet<String> packages = new HashSet<>();
251 packages.add(packageName);
252 enqueueModelUpdateTask(new CacheDataUpdatedTask(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800253 CacheDataUpdatedTask.OP_SESSION_UPDATE, Process.myUserHandle(), packages));
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800254 }
255
256 /**
257 * Adds the provided items to the workspace.
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800258 */
Sunny Goyal2bcbe132016-11-16 09:23:42 -0800259 public void addAndBindAddedWorkspaceItems(List<ItemInfo> workspaceApps) {
260 addAndBindAddedWorkspaceItems(Provider.of(workspaceApps));
261 }
262
263 /**
264 * Adds the provided items to the workspace.
265 */
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700266 public void addAndBindAddedWorkspaceItems(
Sunny Goyal2bcbe132016-11-16 09:23:42 -0800267 Provider<List<ItemInfo>> appsProvider) {
268 enqueueModelUpdateTask(new AddWorkspaceItemsTask(appsProvider));
Winson Chung64359a52013-07-08 17:17:08 -0700269 }
270
Sunny Goyal43bf11d2017-02-02 13:52:53 -0800271 public ModelWriter getWriter(boolean hasVerticalHotseat) {
272 return new ModelWriter(mApp.getContext(), sBgDataModel, hasVerticalHotseat);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800273 }
274
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700275 static void checkItemInfoLocked(
276 final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
Sunny Goyale9956a72016-09-01 17:24:47 -0700277 ItemInfo modelItem = sBgDataModel.itemsIdMap.get(itemId);
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700278 if (modelItem != null && item != modelItem) {
279 // check all the data is consistent
280 if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
281 ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
282 ShortcutInfo shortcut = (ShortcutInfo) item;
283 if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
284 modelShortcut.intent.filterEquals(shortcut.intent) &&
285 modelShortcut.id == shortcut.id &&
286 modelShortcut.itemType == shortcut.itemType &&
287 modelShortcut.container == shortcut.container &&
Adam Cohendcd297f2013-06-18 13:13:40 -0700288 modelShortcut.screenId == shortcut.screenId &&
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700289 modelShortcut.cellX == shortcut.cellX &&
290 modelShortcut.cellY == shortcut.cellY &&
291 modelShortcut.spanX == shortcut.spanX &&
Sunny Goyalaa8ef112015-06-12 20:04:41 -0700292 modelShortcut.spanY == shortcut.spanY) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700293 // For all intents and purposes, this is the same object
294 return;
295 }
296 }
297
298 // the modelItem needs to match up perfectly with item if our model is
299 // to be consistent with the database-- for now, just require
300 // modelItem == item or the equality check above
301 String msg = "item: " + ((item != null) ? item.toString() : "null") +
302 "modelItem: " +
303 ((modelItem != null) ? modelItem.toString() : "null") +
304 "Error: ItemInfo passed to checkItemInfo doesn't match original";
305 RuntimeException e = new RuntimeException(msg);
306 if (stackTrace != null) {
307 e.setStackTrace(stackTrace);
308 }
Adam Cohenb9ada652013-11-08 08:25:08 -0800309 throw e;
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700310 }
311 }
312
Michael Jurka816474f2012-06-25 14:49:02 -0700313 static void checkItemInfo(final ItemInfo item) {
314 final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
315 final long itemId = item.id;
316 Runnable r = new Runnable() {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700317 public void run() {
Sunny Goyale9956a72016-09-01 17:24:47 -0700318 synchronized (sBgDataModel) {
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700319 checkItemInfoLocked(itemId, item, stackTrace);
Michael Jurka816474f2012-06-25 14:49:02 -0700320 }
Michael Jurkab2ae8ac2012-09-21 12:06:06 -0700321 }
322 };
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700323 runOnWorkerThread(r);
Michael Jurka816474f2012-06-25 14:49:02 -0700324 }
325
Joe Onorato9c1289c2009-08-17 11:03:03 -0400326 /**
Adam Cohendcd297f2013-06-18 13:13:40 -0700327 * Update the order of the workspace screens in the database. The array list contains
328 * a list of screen ids in the order that they should appear.
329 */
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700330 public static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Winson Chung64359a52013-07-08 17:17:08 -0700331 final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
Adam Cohendcd297f2013-06-18 13:13:40 -0700332 final ContentResolver cr = context.getContentResolver();
333 final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
334
335 // Remove any negative screen ids -- these aren't persisted
Winson Chung64359a52013-07-08 17:17:08 -0700336 Iterator<Long> iter = screensCopy.iterator();
Adam Cohendcd297f2013-06-18 13:13:40 -0700337 while (iter.hasNext()) {
338 long id = iter.next();
339 if (id < 0) {
340 iter.remove();
341 }
342 }
343
344 Runnable r = new Runnable() {
345 @Override
346 public void run() {
Yura085c8532014-02-11 15:15:29 +0000347 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Adam Cohendcd297f2013-06-18 13:13:40 -0700348 // Clear the table
Yura085c8532014-02-11 15:15:29 +0000349 ops.add(ContentProviderOperation.newDelete(uri).build());
Winson Chung76828c82013-08-19 15:43:29 -0700350 int count = screensCopy.size();
Adam Cohendcd297f2013-06-18 13:13:40 -0700351 for (int i = 0; i < count; i++) {
352 ContentValues v = new ContentValues();
Winson Chung76828c82013-08-19 15:43:29 -0700353 long screenId = screensCopy.get(i);
Adam Cohendcd297f2013-06-18 13:13:40 -0700354 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
355 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Yura085c8532014-02-11 15:15:29 +0000356 ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
Adam Cohendcd297f2013-06-18 13:13:40 -0700357 }
Yura085c8532014-02-11 15:15:29 +0000358
359 try {
360 cr.applyBatch(LauncherProvider.AUTHORITY, ops);
361 } catch (Exception ex) {
362 throw new RuntimeException(ex);
363 }
Winson Chung9e6a0a22013-08-27 11:58:12 -0700364
Sunny Goyale9956a72016-09-01 17:24:47 -0700365 synchronized (sBgDataModel) {
366 sBgDataModel.workspaceScreens.clear();
367 sBgDataModel.workspaceScreens.addAll(screensCopy);
Adam Cohen4caf2982013-08-20 18:54:31 -0700368 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700369 }
370 };
371 runOnWorkerThread(r);
372 }
373
374 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400375 * Set this as the current Launcher activity object for the loader.
376 */
377 public void initialize(Callbacks callbacks) {
378 synchronized (mLock) {
Sunny Goyalaaf7d1d2016-05-17 13:38:54 -0700379 Preconditions.assertUIThread();
380 // Remove any queued UI runnables
381 mHandler.cancelAll();
382 mCallbacks = new WeakReference<>(callbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400383 }
384 }
385
Kenny Guyed131872014-04-30 03:02:21 +0100386 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800387 public void onPackageChanged(String packageName, UserHandle user) {
Kenny Guyed131872014-04-30 03:02:21 +0100388 int op = PackageUpdatedTask.OP_UPDATE;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700389 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packageName));
Kenny Guyed131872014-04-30 03:02:21 +0100390 }
391
392 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800393 public void onPackageRemoved(String packageName, UserHandle user) {
Sunny Goyalc2936bc2016-09-01 15:50:36 -0700394 onPackagesRemoved(user, packageName);
395 }
396
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800397 public void onPackagesRemoved(UserHandle user, String... packages) {
Kenny Guyed131872014-04-30 03:02:21 +0100398 int op = PackageUpdatedTask.OP_REMOVE;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700399 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packages));
Kenny Guyed131872014-04-30 03:02:21 +0100400 }
401
402 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800403 public void onPackageAdded(String packageName, UserHandle user) {
Kenny Guyed131872014-04-30 03:02:21 +0100404 int op = PackageUpdatedTask.OP_ADD;
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700405 enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packageName));
Kenny Guyed131872014-04-30 03:02:21 +0100406 }
407
408 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800409 public void onPackagesAvailable(String[] packageNames, UserHandle user,
Kenny Guyed131872014-04-30 03:02:21 +0100410 boolean replacing) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700411 enqueueModelUpdateTask(
412 new PackageUpdatedTask(PackageUpdatedTask.OP_UPDATE, user, packageNames));
Kenny Guyed131872014-04-30 03:02:21 +0100413 }
414
415 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800416 public void onPackagesUnavailable(String[] packageNames, UserHandle user,
Kenny Guyed131872014-04-30 03:02:21 +0100417 boolean replacing) {
418 if (!replacing) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700419 enqueueModelUpdateTask(new PackageUpdatedTask(
420 PackageUpdatedTask.OP_UNAVAILABLE, user, packageNames));
Kenny Guyed131872014-04-30 03:02:21 +0100421 }
Kenny Guyed131872014-04-30 03:02:21 +0100422 }
423
Kenny Guy44cba692016-01-21 19:50:02 +0000424 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800425 public void onPackagesSuspended(String[] packageNames, UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700426 enqueueModelUpdateTask(new PackageUpdatedTask(
427 PackageUpdatedTask.OP_SUSPEND, user, packageNames));
Kenny Guy44cba692016-01-21 19:50:02 +0000428 }
429
430 @Override
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800431 public void onPackagesUnsuspended(String[] packageNames, UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700432 enqueueModelUpdateTask(new PackageUpdatedTask(
433 PackageUpdatedTask.OP_UNSUSPEND, user, packageNames));
Kenny Guy44cba692016-01-21 19:50:02 +0000434 }
435
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700436 @Override
437 public void onShortcutsChanged(String packageName, List<ShortcutInfoCompat> shortcuts,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800438 UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700439 enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, true));
Sunny Goyal50941fb2016-08-04 12:03:52 -0700440 }
441
442 public void updatePinnedShortcuts(String packageName, List<ShortcutInfoCompat> shortcuts,
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800443 UserHandle user) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700444 enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, false));
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700445 }
446
Joe Onorato1d8e7bb2009-10-15 19:49:43 -0700447 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400448 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
449 * ACTION_PACKAGE_CHANGED.
450 */
Narayan Kamathcb1a4772011-06-28 13:46:59 +0100451 @Override
Joe Onoratof99f8c12009-10-31 17:27:36 -0400452 public void onReceive(Context context, Intent intent) {
Chris Wrenb358f812014-04-16 13:37:00 -0400453 if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
Winson Chungaafa03c2010-06-11 17:34:16 -0700454
Joe Onorato36115782010-06-17 13:28:48 -0400455 final String action = intent.getAction();
Kenny Guyed131872014-04-30 03:02:21 +0100456 if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
Reena Lee93f824a2011-09-23 17:20:28 -0700457 // If we have changed locale we need to clear out the labels in all apps/workspace.
458 forceReload();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700459 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
460 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
Sunny Goyal823fd502015-08-04 11:40:13 -0700461 UserManagerCompat.getInstance(context).enableAndResetCache();
Sunny Goyal957c13f2015-05-01 13:02:20 -0700462 forceReload();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700463 } else if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) ||
464 Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
465 Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800466 UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
Sunny Goyalda891c12016-03-18 18:29:24 -0700467 if (user != null) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700468 if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) ||
469 Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700470 enqueueModelUpdateTask(new PackageUpdatedTask(
471 PackageUpdatedTask.OP_USER_AVAILABILITY_CHANGE, user));
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700472 }
473
474 // ACTION_MANAGED_PROFILE_UNAVAILABLE sends the profile back to locked mode, so
475 // we need to run the state change task again.
476 if (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
477 Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -0700478 enqueueModelUpdateTask(new UserLockStateChangedTask(user));
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700479 }
Sunny Goyalda891c12016-03-18 18:29:24 -0700480 }
Tony Wickham827cef22016-03-17 15:39:39 -0700481 } else if (Intent.ACTION_WALLPAPER_CHANGED.equals(action)) {
482 ExtractionUtils.startColorExtractionServiceIfNecessary(context);
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700483 }
484 }
485
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800486 /**
487 * Reloads the workspace items from the DB and re-binds the workspace. This should generally
488 * not be called as DB updates are automatically followed by UI update
489 */
490 public void forceReload() {
491 synchronized (mLock) {
492 // Stop any existing loaders first, so they don't set mModelLoaded to true later
493 stopLoaderLocked();
494 mModelLoaded = false;
495 }
Winson Chungf0c6ae02012-03-21 16:10:31 -0700496
Reena Lee93f824a2011-09-23 17:20:28 -0700497 // Do this here because if the launcher activity is running it will be restarted.
498 // If it's not running startLoaderFromBackground will merely tell it that it needs
499 // to reload.
500 startLoaderFromBackground();
501 }
502
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700503 /**
504 * When the launcher is in the background, it's possible for it to miss paired
505 * configuration changes. So whenever we trigger the loader from the background
506 * tell the launcher that it needs to re-run the loader when it comes back instead
507 * of doing it now.
508 */
509 public void startLoaderFromBackground() {
Sunny Goyale0f58d72014-11-10 18:05:31 -0800510 Callbacks callbacks = getCallback();
511 if (callbacks != null) {
512 // Only actually run the loader if they're not paused.
513 if (!callbacks.setLoadOnResume()) {
Sunny Goyal93f878c2016-03-30 17:31:24 -0700514 startLoader(callbacks.getCurrentWorkspaceScreen());
Joe Onoratoe9ad59e2010-10-29 17:35:36 -0700515 }
516 }
Joe Onorato36115782010-06-17 13:28:48 -0400517 }
Joe Onoratof99f8c12009-10-31 17:27:36 -0400518
Sunny Goyal2bba4c32015-05-18 15:42:48 -0700519 /**
520 * If there is already a loader task running, tell it to stop.
521 */
522 private void stopLoaderLocked() {
Reena Lee93f824a2011-09-23 17:20:28 -0700523 LoaderTask oldTask = mLoaderTask;
524 if (oldTask != null) {
Reena Lee93f824a2011-09-23 17:20:28 -0700525 oldTask.stopLocked();
526 }
Reena Lee93f824a2011-09-23 17:20:28 -0700527 }
528
Adam Cohen1a85c582014-09-30 09:48:49 -0700529 public boolean isCurrentCallbacks(Callbacks callbacks) {
530 return (mCallbacks != null && mCallbacks.get() == callbacks);
531 }
532
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700533 /**
534 * Starts the loader. Tries to bind {@params synchronousBindPage} synchronously if possible.
535 * @return true if the page could be bound synchronously.
536 */
537 public boolean startLoader(int synchronousBindPage) {
Sunny Goyal756adbc2015-04-16 15:20:51 -0700538 // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
539 InstallShortcutReceiver.enableInstallQueue();
Joe Onorato36115782010-06-17 13:28:48 -0400540 synchronized (mLock) {
Joe Onorato36115782010-06-17 13:28:48 -0400541 // Don't bother to start the thread if we know it's not going to do anything
542 if (mCallbacks != null && mCallbacks.get() != null) {
Sunny Goyal527c7d32015-08-28 15:19:36 -0700543 final Callbacks oldCallbacks = mCallbacks.get();
544 // Clear any pending bind-runnables from the synchronized load process.
545 runOnMainThread(new Runnable() {
546 public void run() {
547 oldCallbacks.clearPendingBinds();
548 }
549 });
550
Joe Onorato36115782010-06-17 13:28:48 -0400551 // If there is already one running, tell it to stop.
Sunny Goyal2bba4c32015-05-18 15:42:48 -0700552 stopLoaderLocked();
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700553 mLoaderTask = new LoaderTask(mApp.getContext(), synchronousBindPage);
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800554 if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
555 && mModelLoaded && !mIsLoaderTaskRunning) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700556 mLoaderTask.runBindSynchronousPage(synchronousBindPage);
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700557 return true;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700558 } else {
559 sWorkerThread.setPriority(Thread.NORM_PRIORITY);
560 sWorker.post(mLoaderTask);
561 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400562 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400563 }
Sunny Goyalb5b9ad62016-04-02 11:23:39 -0700564 return false;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400565 }
566
Joe Onorato36115782010-06-17 13:28:48 -0400567 public void stopLoader() {
568 synchronized (mLock) {
569 if (mLoaderTask != null) {
570 mLoaderTask.stopLocked();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400571 }
572 }
Joe Onorato36115782010-06-17 13:28:48 -0400573 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400574
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800575 /**
576 * Loads the workspace screen ids in an ordered list.
577 */
Sunny Goyale5bb7052015-07-27 14:36:07 -0700578 public static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
Winson Chung76828c82013-08-19 15:43:29 -0700579 final ContentResolver contentResolver = context.getContentResolver();
580 final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
Winson Chung76828c82013-08-19 15:43:29 -0700581
Sunny Goyalc1b7c2e2015-01-16 16:19:04 -0800582 // Get screens ordered by rank.
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700583 return LauncherDbUtils.getScreenIdsFromCursor(contentResolver.query(
584 screensUri, null, null, null, LauncherSettings.WorkspaceScreens.SCREEN_RANK));
Winson Chung76828c82013-08-19 15:43:29 -0700585 }
586
Joe Onorato36115782010-06-17 13:28:48 -0400587 /**
588 * Runnable for the thread that loads the contents of the launcher:
589 * - workspace icons
590 * - widgets
591 * - all apps icons
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700592 * - deep shortcuts within apps
Joe Onorato36115782010-06-17 13:28:48 -0400593 */
594 private class LoaderTask implements Runnable {
595 private Context mContext;
Sunny Goyal93f878c2016-03-30 17:31:24 -0700596 private int mPageToBindFirst;
597
Adam Cohen091440a2015-03-18 14:16:05 -0700598 @Thunk boolean mIsLoadingAndBindingWorkspace;
Joe Onorato36115782010-06-17 13:28:48 -0400599 private boolean mStopped;
Adam Cohen091440a2015-03-18 14:16:05 -0700600 @Thunk boolean mLoadAndBindStepFinished;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700601
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700602 LoaderTask(Context context, int pageToBindFirst) {
Joe Onorato36115782010-06-17 13:28:48 -0400603 mContext = context;
Sunny Goyal93f878c2016-03-30 17:31:24 -0700604 mPageToBindFirst = pageToBindFirst;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400605 }
606
Joe Onorato36115782010-06-17 13:28:48 -0400607 private void waitForIdle() {
608 // Wait until the either we're stopped or the other threads are done.
609 // This way we don't start loading all apps until the workspace has settled
610 // down.
611 synchronized (LoaderTask.this) {
612 final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onoratocc67f472010-06-08 10:54:30 -0700613
Joe Onorato36115782010-06-17 13:28:48 -0400614 mHandler.postIdle(new Runnable() {
615 public void run() {
616 synchronized (LoaderTask.this) {
617 mLoadAndBindStepFinished = true;
618 if (DEBUG_LOADERS) {
619 Log.d(TAG, "done with previous binding step");
Daniel Sandler843e8602010-06-07 14:59:01 -0400620 }
Joe Onorato36115782010-06-17 13:28:48 -0400621 LoaderTask.this.notify();
Daniel Sandler843e8602010-06-07 14:59:01 -0400622 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400623 }
Joe Onorato36115782010-06-17 13:28:48 -0400624 });
625
Sunny Goyal71b5c0b2015-01-08 16:59:04 -0800626 while (!mStopped && !mLoadAndBindStepFinished) {
Joe Onorato36115782010-06-17 13:28:48 -0400627 try {
Michael Jurkac7700af2013-05-14 20:17:58 +0200628 // Just in case mFlushingWorkerThread changes but we aren't woken up,
629 // wait no longer than 1sec at a time
630 this.wait(1000);
Joe Onorato36115782010-06-17 13:28:48 -0400631 } catch (InterruptedException ex) {
632 // Ignore
Daniel Sandler843e8602010-06-07 14:59:01 -0400633 }
634 }
Joe Onorato36115782010-06-17 13:28:48 -0400635 if (DEBUG_LOADERS) {
636 Log.d(TAG, "waited "
Winson Chungaafa03c2010-06-11 17:34:16 -0700637 + (SystemClock.uptimeMillis()-workspaceWaitTime)
Joe Onorato36115782010-06-17 13:28:48 -0400638 + "ms for previous step to finish binding");
639 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400640 }
Joe Onorato36115782010-06-17 13:28:48 -0400641 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400642
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700643 void runBindSynchronousPage(int synchronousBindPage) {
Derek Prothro7aff3992013-12-10 14:00:37 -0500644 if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700645 // Ensure that we have a valid page index to load synchronously
646 throw new RuntimeException("Should not call runBindSynchronousPage() without " +
647 "valid page index");
648 }
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800649 if (!mModelLoaded) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700650 // Ensure that we don't try and bind a specified page when the pages have not been
651 // loaded already (we should load everything asynchronously in that case)
652 throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
653 }
654 synchronized (mLock) {
655 if (mIsLoaderTaskRunning) {
656 // Ensure that we are never running the background loading at this point since
657 // we also touch the background collections
658 throw new RuntimeException("Error! Background loading is already running");
659 }
660 }
661
662 // XXX: Throw an exception if we are already loading (since we touch the worker thread
663 // data structures, we can't allow any other thread to touch that data, but because
664 // this call is synchronous, we can get away with not locking).
665
Daniel Sandlercc8befa2013-06-11 14:45:48 -0400666 // The LauncherModel is static in the LauncherAppState and mHandler may have queued
Adam Cohena13a2f22012-07-23 14:29:15 -0700667 // operations from the previous activity. We need to ensure that all queued operations
668 // are executed before any synchronous binding work is done.
669 mHandler.flush();
670
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700671 // Divide the set of loaded items into those that we are binding synchronously, and
672 // everything else that is to be bound normally (asynchronously).
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800673 bindWorkspace(synchronousBindPage);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700674 // XXX: For now, continue posting the binding of AllApps as there are other issues that
675 // arise from that.
676 onlyBindAllApps();
Tony Wickham80f57872016-06-29 18:12:15 -0700677
678 bindDeepShortcuts();
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700679 }
680
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800681 private void verifyNotStopped() throws CancellationException {
682 synchronized (LoaderTask.this) {
683 if (mStopped) {
684 throw new CancellationException("Loader stopped");
685 }
686 }
687 }
688
Joe Onorato36115782010-06-17 13:28:48 -0400689 public void run() {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700690 synchronized (mLock) {
Sunny Goyalf5cd9982015-05-18 15:19:29 -0700691 if (mStopped) {
692 return;
693 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700694 mIsLoaderTaskRunning = true;
695 }
Daniel Sandler843e8602010-06-07 14:59:01 -0400696
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800697 try {
698 if (DEBUG_LOADERS) Log.d(TAG, "step 1.1: loading workspace");
699 // Set to false in bindWorkspace()
700 mIsLoadingAndBindingWorkspace = true;
701 loadWorkspace();
Joe Onorato36115782010-06-17 13:28:48 -0400702
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800703 verifyNotStopped();
704 if (DEBUG_LOADERS) Log.d(TAG, "step 1.2: bind workspace workspace");
705 bindWorkspace(mPageToBindFirst);
706
707 // Take a break
708 if (DEBUG_LOADERS) Log.d(TAG, "step 1 completed, wait for idle");
Joe Onorato36115782010-06-17 13:28:48 -0400709 waitForIdle();
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800710 verifyNotStopped();
Daniel Sandler843e8602010-06-07 14:59:01 -0400711
712 // second step
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800713 if (DEBUG_LOADERS) Log.d(TAG, "step 2.1: loading all apps");
714 loadAllApps();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700715
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800716 verifyNotStopped();
717 if (DEBUG_LOADERS) Log.d(TAG, "step 2.2: Update icon cache");
718 updateIconCache();
719
720 // Take a break
721 if (DEBUG_LOADERS) Log.d(TAG, "step 2 completed, wait for idle");
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700722 waitForIdle();
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800723 verifyNotStopped();
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700724
725 // third step
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800726 if (DEBUG_LOADERS) Log.d(TAG, "step 3.1: loading deep shortcuts");
727 loadDeepShortcuts();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400728
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800729 verifyNotStopped();
730 if (DEBUG_LOADERS) Log.d(TAG, "step 3.2: bind deep shortcuts");
731 bindDeepShortcuts();
Joe Onorato9c1289c2009-08-17 11:03:03 -0400732
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800733 synchronized (mLock) {
734 // Everything loaded bind the data.
735 mModelLoaded = true;
736 mHasLoaderCompletedOnce = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400737 }
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800738 } catch (CancellationException e) {
739 // Loader stopped, ignore
740 } finally {
741 // Clear out this reference, otherwise we end up holding it until all of the
742 // callback runnables are done.
743 mContext = null;
744
745 synchronized (mLock) {
746 // If we are still the last one to be scheduled, remove ourselves.
747 if (mLoaderTask == this) {
748 mLoaderTask = null;
749 }
750 mIsLoaderTaskRunning = false;
751 }
Joe Onorato36115782010-06-17 13:28:48 -0400752 }
Joe Onorato36115782010-06-17 13:28:48 -0400753 }
754
755 public void stopLocked() {
756 synchronized (LoaderTask.this) {
757 mStopped = true;
758 this.notify();
759 }
760 }
761
762 /**
763 * Gets the callbacks object. If we've been stopped, or if the launcher object
764 * has somehow been garbage collected, return null instead. Pass in the Callbacks
765 * object that was around when the deferred message was scheduled, and if there's
766 * a new Callbacks object around then also return null. This will save us from
767 * calling onto it with data that will be ignored.
768 */
769 Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
770 synchronized (mLock) {
771 if (mStopped) {
772 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -0400773 }
Joe Onorato36115782010-06-17 13:28:48 -0400774
775 if (mCallbacks == null) {
776 return null;
Daniel Sandler8802e962010-05-26 16:28:16 -0400777 }
Joe Onorato36115782010-06-17 13:28:48 -0400778
779 final Callbacks callbacks = mCallbacks.get();
780 if (callbacks != oldCallbacks) {
781 return null;
782 }
783 if (callbacks == null) {
784 Log.w(TAG, "no mCallbacks");
785 return null;
786 }
787
788 return callbacks;
789 }
790 }
791
Sunny Goyal66cfdc22015-02-02 13:01:51 -0800792 private void loadWorkspace() {
Sunny Goyale26d1002016-06-20 14:52:14 -0700793 if (LauncherAppState.PROFILE_STARTUP) {
794 Trace.beginSection("Loading Workspace");
795 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400796
Joe Onorato36115782010-06-17 13:28:48 -0400797 final Context context = mContext;
798 final ContentResolver contentResolver = context.getContentResolver();
Sunny Goyal342e4662017-02-02 15:21:08 -0800799 final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
800 final boolean isSafeMode = pmHelper.isSafeMode();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700801 final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530802 final DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(context);
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700803 final boolean isSdCardReady = Utilities.isBootCompleted();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800804 final MultiHashMap<UserHandle, String> pendingPackages = new MultiHashMap<>();
Joe Onorato3c2f7e12009-10-31 19:17:31 -0400805
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700806 boolean clearDb = false;
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700807 try {
808 ImportDataTask.performImportIfPossible(context);
809 } catch (Exception e) {
810 // Migration failed. Clear workspace.
811 clearDb = true;
812 }
813
814 if (!clearDb && GridSizeMigrationTask.ENABLED &&
Sunny Goyalf076eae2016-01-11 12:25:10 -0800815 !GridSizeMigrationTask.migrateGridIfNeeded(mContext)) {
816 // Migration failed. Clear workspace.
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700817 clearDb = true;
Sunny Goyale5bb7052015-07-27 14:36:07 -0700818 }
819
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700820 if (clearDb) {
Sunny Goyala1365452015-10-01 15:46:24 -0700821 Log.d(TAG, "loadWorkspace: resetting launcher database");
Sunny Goyald2497482015-09-22 18:24:19 -0700822 LauncherSettings.Settings.call(contentResolver,
Sunny Goyale05b08f2017-02-23 18:30:22 -0800823 LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
Dan Sandlerd5024042014-01-09 15:01:33 -0500824 }
825
Sunny Goyalded0fdb2016-05-23 15:55:41 -0700826 Log.d(TAG, "loadWorkspace: loading default favorites");
827 LauncherSettings.Settings.call(contentResolver,
828 LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES);
Adam Cohene25af792013-06-06 23:08:25 -0700829
Sunny Goyale9956a72016-09-01 17:24:47 -0700830 synchronized (sBgDataModel) {
831 sBgDataModel.clear();
832
Sunny Goyal756adbc2015-04-16 15:20:51 -0700833 final HashMap<String, Integer> installingPkgs = PackageInstallerCompat
Sunny Goyal94485362014-09-18 16:13:58 -0700834 .getInstance(mContext).updateAndGetActiveSessionCache();
Sunny Goyale9956a72016-09-01 17:24:47 -0700835 sBgDataModel.workspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
Romain Guy5c16f3e2010-01-12 17:24:58 -0800836
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700837 Map<ShortcutKey, ShortcutInfoCompat> shortcutKeyToPinnedShortcuts = new HashMap<>();
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800838 final LoaderCursor c = new LoaderCursor(contentResolver.query(
839 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null), mApp);
Daniel Sandler8802e962010-05-26 16:28:16 -0400840
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800841 HashMap<ComponentKey, AppWidgetProviderInfo> widgetProvidersMap = null;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400842
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700843 try {
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700844 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
845 LauncherSettings.Favorites.APPWIDGET_ID);
Chris Wrenc3919c02013-09-18 09:48:33 -0400846 final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
847 LauncherSettings.Favorites.APPWIDGET_PROVIDER);
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700848 final int spanXIndex = c.getColumnIndexOrThrow
849 (LauncherSettings.Favorites.SPANX);
850 final int spanYIndex = c.getColumnIndexOrThrow(
851 LauncherSettings.Favorites.SPANY);
Sunny Goyal08f72612015-01-05 13:41:43 -0800852 final int rankIndex = c.getColumnIndexOrThrow(
853 LauncherSettings.Favorites.RANK);
Sunny Goyal5d85c442015-03-10 13:14:47 -0700854 final int optionsIndex = c.getColumnIndexOrThrow(
855 LauncherSettings.Favorites.OPTIONS);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400856
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800857 final LongSparseArray<UserHandle> allUsers = c.allUsers;
Kenny Guyff05f432016-01-22 17:48:29 +0000858 final LongSparseArray<Boolean> quietMode = new LongSparseArray<>();
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700859 final LongSparseArray<Boolean> unlockedUsers = new LongSparseArray<>();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800860 for (UserHandle user : mUserManager.getUserProfiles()) {
Kenny Guyff05f432016-01-22 17:48:29 +0000861 long serialNo = mUserManager.getSerialNumberForUser(user);
862 allUsers.put(serialNo, user);
863 quietMode.put(serialNo, mUserManager.isQuietModeEnabled(user));
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700864
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700865 boolean userUnlocked = mUserManager.isUserUnlocked(user);
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700866
867 // We can only query for shortcuts when the user is unlocked.
868 if (userUnlocked) {
Sunny Goyal49f4f032016-08-01 15:45:49 -0700869 List<ShortcutInfoCompat> pinnedShortcuts =
Sunny Goyaldde4fd92016-11-21 16:02:39 +0530870 shortcutManager.queryForPinnedShortcuts(null, user);
871 if (shortcutManager.wasLastCallSuccess()) {
Sunny Goyal49f4f032016-08-01 15:45:49 -0700872 for (ShortcutInfoCompat shortcut : pinnedShortcuts) {
873 shortcutKeyToPinnedShortcuts.put(ShortcutKey.fromInfo(shortcut),
874 shortcut);
875 }
876 } else {
877 // Shortcut manager can fail due to some race condition when the
878 // lock state changes too frequently. For the purpose of the loading
879 // shortcuts, consider the user is still locked.
880 userUnlocked = false;
Sunny Goyald3b87ef2016-07-28 12:11:54 -0700881 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700882 }
Sunny Goyal49f4f032016-08-01 15:45:49 -0700883 unlockedUsers.put(serialNo, userUnlocked);
Sunny Goyal7f834d22015-04-21 10:10:23 -0700884 }
885
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700886 ShortcutInfo info;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700887 LauncherAppWidgetInfo appWidgetInfo;
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700888 Intent intent;
Sunny Goyal81e44912017-01-14 15:05:14 -0800889 String targetPkg;
Joe Onorato9c1289c2009-08-17 11:03:03 -0400890
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700891 while (!mStopped && c.moveToNext()) {
892 try {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800893 if (c.user == null) {
894 // User has been deleted, remove the item.
895 c.markDeleted("User has been deleted");
896 continue;
897 }
898
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700899 boolean allowMissingTarget = false;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800900 switch (c.itemType) {
Sunny Goyal81e44912017-01-14 15:05:14 -0800901 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
Winson Chungb8b2a5a2012-07-12 17:55:31 -0700902 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700903 case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
Sunny Goyal81e44912017-01-14 15:05:14 -0800904 intent = c.parseIntent();
905 if (intent == null) {
906 c.markDeleted("Invalid or null intent");
907 continue;
908 }
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800909
Sunny Goyal81e44912017-01-14 15:05:14 -0800910 int disabledState = quietMode.get(c.serialNumber) ?
911 ShortcutInfo.FLAG_DISABLED_QUIET_USER : 0;
912 ComponentName cn = intent.getComponent();
913 targetPkg = cn == null ? intent.getPackage() : cn.getPackageName();
Sunny Goyalf599ccf2014-07-08 13:01:29 -0700914
Sunny Goyal81e44912017-01-14 15:05:14 -0800915 if (!Process.myUserHandle().equals(c.user)) {
916 if (c.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
917 c.markDeleted("Legacy shortcuts are only allowed for default user");
918 continue;
919 } else if (c.restoreFlag != 0) {
920 // Don't restore items for other profiles.
921 c.markDeleted("Restore from managed profile not supported");
922 continue;
923 }
924 }
925 if (TextUtils.isEmpty(targetPkg) &&
926 c.itemType != LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
927 c.markDeleted("Only legacy shortcuts can have null package");
928 continue;
929 }
Sunny Goyal34942622014-08-29 17:20:55 -0700930
Sunny Goyal81e44912017-01-14 15:05:14 -0800931 // If there is no target package, its an implicit intent
932 // (legacy shortcut) which is always valid
933 boolean validTarget = TextUtils.isEmpty(targetPkg) ||
934 launcherApps.isPackageEnabledForProfile(targetPkg, c.user);
Sunny Goyal94485362014-09-18 16:13:58 -0700935
Sunny Goyal81e44912017-01-14 15:05:14 -0800936 if (cn != null && validTarget) {
937 // If the apk is present and the shortcut points to a specific
938 // component.
939
940 // If the component is already present
941 if (launcherApps.isActivityEnabledForProfile(cn, c.user)) {
942 // no special handling necessary for this item
943 c.markRestored();
944 } else {
945 if (c.hasRestoreFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
946 // We allow auto install apps to have their intent
947 // updated after an install.
Sunny Goyal342e4662017-02-02 15:21:08 -0800948 intent = pmHelper.getAppLaunchIntent(targetPkg, c.user);
Sunny Goyal81e44912017-01-14 15:05:14 -0800949 if (intent != null) {
950 c.restoreFlag = 0;
Sunny Goyalaaf86fe2017-01-05 21:50:27 -0800951 c.updater().put(
Sunny Goyal81e44912017-01-14 15:05:14 -0800952 LauncherSettings.Favorites.INTENT,
953 intent.toUri(0)).commit();
954 cn = intent.getComponent();
Sunny Goyalb05a00a2016-08-29 10:06:57 -0700955 } else {
Sunny Goyal81e44912017-01-14 15:05:14 -0800956 c.markDeleted("Unable to find a launch target");
Sunny Goyal94485362014-09-18 16:13:58 -0700957 continue;
958 }
Sunny Goyal1a745e82014-10-02 15:58:31 -0700959 } else {
Sunny Goyal81e44912017-01-14 15:05:14 -0800960 // The app is installed but the component is no
961 // longer available.
962 c.markDeleted("Invalid component removed: " + cn);
Sunny Goyal1a745e82014-10-02 15:58:31 -0700963 continue;
Winson Chungee055712013-07-30 14:46:24 -0700964 }
Winson Chungee055712013-07-30 14:46:24 -0700965 }
Sunny Goyal81e44912017-01-14 15:05:14 -0800966 }
967 // else if cn == null => can't infer much, leave it
968 // else if !validPkg => could be restored icon or missing sd-card
969
970 if (!TextUtils.isEmpty(targetPkg) && !validTarget) {
971 // Points to a valid app (superset of cn != null) but the apk
972 // is not available.
973
974 if (c.restoreFlag != 0) {
975 // Package is not yet available but might be
976 // installed later.
977 FileLog.d(TAG, "package not yet restored: " + targetPkg);
978
979 if (c.hasRestoreFlag(ShortcutInfo.FLAG_RESTORE_STARTED)) {
980 // Restore has started once.
981 } else if (installingPkgs.containsKey(targetPkg)) {
982 // App restore has started. Update the flag
983 c.restoreFlag |= ShortcutInfo.FLAG_RESTORE_STARTED;
984 c.updater().commit();
985 } else {
986 c.markDeleted("Unrestored app removed: " + targetPkg);
987 continue;
988 }
Sunny Goyalad2e91a2017-02-28 15:14:58 -0800989 } else if (pmHelper.isAppOnSdcard(targetPkg, c.user)) {
Sunny Goyal81e44912017-01-14 15:05:14 -0800990 // Package is present but not available.
991 disabledState |= ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
992 // Add the icon on the workspace anyway.
993 allowMissingTarget = true;
994 } else if (!isSdCardReady) {
995 // SdCard is not ready yet. Package might get available,
996 // once it is ready.
997 Log.d(TAG, "Missing pkg, will check later: " + targetPkg);
998 pendingPackages.addToList(c.user, targetPkg);
999 // Add the icon on the workspace anyway.
1000 allowMissingTarget = true;
1001 } else {
1002 // Do not wait for external media load anymore.
1003 c.markDeleted("Invalid package removed: " + targetPkg);
1004 continue;
1005 }
1006 }
1007
1008 if (validTarget) {
1009 // The shortcut points to a valid target (either no target
1010 // or something which is ready to be used)
1011 c.markRestored();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001012 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001013
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001014 boolean useLowResIcon = !c.isOnWorkspaceOrHotseat() &&
Sunny Goyal34b65272015-03-11 16:56:52 -07001015 c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
1016
Sunny Goyalc1ad0ce2017-01-11 14:33:38 -08001017 if (c.restoreFlag != 0) {
Sunny Goyal81e44912017-01-14 15:05:14 -08001018 // Already verified above that user is same as default user
1019 info = c.getRestoredItemInfo(intent);
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001020 } else if (c.itemType ==
Chris Wrenf4d08112014-01-16 18:13:56 -05001021 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001022 info = c.getAppShortcutInfo(
1023 intent, allowMissingTarget, useLowResIcon);
1024 } else if (c.itemType ==
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001025 LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001026
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001027 ShortcutKey key = ShortcutKey.fromIntent(intent, c.user);
1028 if (unlockedUsers.get(c.serialNumber)) {
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001029 ShortcutInfoCompat pinnedShortcut =
1030 shortcutKeyToPinnedShortcuts.get(key);
1031 if (pinnedShortcut == null) {
1032 // The shortcut is no longer valid.
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001033 c.markDeleted("Pinned shortcut not found");
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001034 continue;
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001035 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001036 info = new ShortcutInfo(pinnedShortcut, context);
Sunny Goyal1b072632017-01-18 11:30:23 -08001037 info.iconBitmap = LauncherIcons
1038 .createShortcutIcon(pinnedShortcut, context);
Charles He3ff90472017-02-15 12:22:56 +00001039 if (pmHelper.isAppSuspended(
Sunny Goyalad2e91a2017-02-28 15:14:58 -08001040 pinnedShortcut.getPackage(), info.user)) {
Charles He3ff90472017-02-15 12:22:56 +00001041 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
1042 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001043 intent = info.intent;
1044 } else {
1045 // Create a shortcut info in disabled mode for now.
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001046 info = c.loadSimpleShortcut();
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001047 info.isDisabled |= ShortcutInfo.FLAG_DISABLED_LOCKED_USER;
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001048 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001049 } else { // item type == ITEM_TYPE_SHORTCUT
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001050 info = c.loadSimpleShortcut();
Michael Jurka96879562012-03-22 05:54:33 -07001051
Sunny Goyald09c3702016-04-06 16:18:20 -07001052 // Shortcuts are only available on the primary profile
Sunny Goyalad2e91a2017-02-28 15:14:58 -08001053 if (pmHelper.isAppSuspended(targetPkg, c.user)) {
Sunny Goyald09c3702016-04-06 16:18:20 -07001054 disabledState |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
1055 }
1056
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001057 // App shortcuts that used to be automatically added to Launcher
1058 // didn't always have the correct intent flags set, so do that
1059 // here
1060 if (intent.getAction() != null &&
Michael Jurka9ad00562012-05-14 12:24:22 -07001061 intent.getCategories() != null &&
1062 intent.getAction().equals(Intent.ACTION_MAIN) &&
Michael Jurka96879562012-03-22 05:54:33 -07001063 intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001064 intent.addFlags(
1065 Intent.FLAG_ACTIVITY_NEW_TASK |
1066 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1067 }
Michael Jurka96879562012-03-22 05:54:33 -07001068 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001069
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001070 if (info != null) {
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001071 c.applyCommonProperties(info);
1072
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001073 info.intent = intent;
Sunny Goyal08f72612015-01-05 13:41:43 -08001074 info.rank = c.getInt(rankIndex);
Winson Chung5f8afe62013-08-12 16:19:28 -07001075 info.spanX = 1;
1076 info.spanY = 1;
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
Sunny Goyal317698b2015-07-29 11:45:41 -07001264 // Sort all the folder items and make sure the first 3 items are high resolution.
Sunny Goyale9956a72016-09-01 17:24:47 -07001265 for (FolderInfo folder : sBgDataModel.folders) {
Sunny Goyal317698b2015-07-29 11:45:41 -07001266 Collections.sort(folder.contents, Folder.ITEM_POS_COMPARATOR);
1267 int pos = 0;
1268 for (ShortcutInfo info : folder.contents) {
Sunny Goyal1cd01b02016-11-09 10:43:58 -08001269 if (info.usingLowResIcon &&
1270 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
Sunny Goyal3fe4a142016-12-15 17:40:07 -08001271 mIconCache.getTitleAndIcon(info, false);
Sunny Goyal317698b2015-07-29 11:45:41 -07001272 }
1273 pos ++;
1274 if (pos >= FolderIcon.NUM_ITEMS_IN_PREVIEW) {
1275 break;
1276 }
1277 }
1278 }
1279
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001280 c.commitRestoredItems();
Sunny Goyalc2936bc2016-09-01 15:50:36 -07001281 if (!isSdCardReady && !pendingPackages.isEmpty()) {
1282 context.registerReceiver(
1283 new SdCardAvailableReceiver(
1284 LauncherModel.this, mContext, pendingPackages),
Sunny Goyal25aba0a2015-07-16 15:07:47 -07001285 new IntentFilter(Intent.ACTION_BOOT_COMPLETED),
Sunny Goyalc2936bc2016-09-01 15:50:36 -07001286 null,
1287 sWorker);
Sunny Goyalf599ccf2014-07-08 13:01:29 -07001288 }
1289
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001290 // Remove any empty screens
Sunny Goyalaaf86fe2017-01-05 21:50:27 -08001291 ArrayList<Long> unusedScreens = new ArrayList<>(sBgDataModel.workspaceScreens);
Sunny Goyale9956a72016-09-01 17:24:47 -07001292 for (ItemInfo item: sBgDataModel.itemsIdMap) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001293 long screenId = item.screenId;
1294 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
1295 unusedScreens.contains(screenId)) {
1296 unusedScreens.remove(screenId);
1297 }
1298 }
1299
1300 // If there are any empty screens remove them, and update.
1301 if (unusedScreens.size() != 0) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001302 sBgDataModel.workspaceScreens.removeAll(unusedScreens);
1303 updateWorkspaceScreenOrder(context, sBgDataModel.workspaceScreens);
Adam Cohendcd297f2013-06-18 13:13:40 -07001304 }
Joe Onorato36115782010-06-17 13:28:48 -04001305 }
Sunny Goyale26d1002016-06-20 14:52:14 -07001306 if (LauncherAppState.PROFILE_STARTUP) {
1307 Trace.endSection();
1308 }
Adam Cohene25af792013-06-06 23:08:25 -07001309 }
1310
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001311 /** Filters the set of items who are directly or indirectly (via another container) on the
1312 * specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08001313 private void filterCurrentWorkspaceItems(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001314 ArrayList<ItemInfo> allWorkspaceItems,
1315 ArrayList<ItemInfo> currentScreenItems,
1316 ArrayList<ItemInfo> otherScreenItems) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001317 // Purge any null ItemInfos
1318 Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
1319 while (iter.hasNext()) {
1320 ItemInfo i = iter.next();
1321 if (i == null) {
1322 iter.remove();
1323 }
1324 }
1325
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001326 // Order the set of items by their containers first, this allows use to walk through the
1327 // list sequentially, build up a list of containers that are in the specified screen,
1328 // as well as all items in those containers.
1329 Set<Long> itemsOnScreen = new HashSet<Long>();
1330 Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
1331 @Override
1332 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson12fb9fc2015-10-01 15:34:08 -07001333 return Utilities.longCompare(lhs.container, rhs.container);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001334 }
1335 });
1336 for (ItemInfo info : allWorkspaceItems) {
1337 if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Winson Chung9b9fb962013-11-15 15:39:34 -08001338 if (info.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001339 currentScreenItems.add(info);
1340 itemsOnScreen.add(info.id);
1341 } else {
1342 otherScreenItems.add(info);
1343 }
1344 } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1345 currentScreenItems.add(info);
1346 itemsOnScreen.add(info.id);
1347 } else {
1348 if (itemsOnScreen.contains(info.container)) {
1349 currentScreenItems.add(info);
1350 itemsOnScreen.add(info.id);
1351 } else {
1352 otherScreenItems.add(info);
1353 }
1354 }
1355 }
1356 }
1357
1358 /** Filters the set of widgets which are on the specified screen. */
Winson Chung9b9fb962013-11-15 15:39:34 -08001359 private void filterCurrentAppWidgets(long currentScreenId,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001360 ArrayList<LauncherAppWidgetInfo> appWidgets,
1361 ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
1362 ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001363
1364 for (LauncherAppWidgetInfo widget : appWidgets) {
Winson Chung2abf94d2012-07-18 18:16:38 -07001365 if (widget == null) continue;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001366 if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
Winson Chung9b9fb962013-11-15 15:39:34 -08001367 widget.screenId == currentScreenId) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001368 currentScreenWidgets.add(widget);
1369 } else {
1370 otherScreenWidgets.add(widget);
1371 }
1372 }
1373 }
1374
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001375 /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
1376 * right) */
1377 private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
Sunny Goyal87f784c2017-01-11 10:48:34 -08001378 final InvariantDeviceProfile profile = mApp.getInvariantDeviceProfile();
Winson Chung882a52e2015-07-08 14:32:26 -07001379 final int screenCols = profile.numColumns;
1380 final int screenCellCount = profile.numColumns * profile.numRows;
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001381 Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
Winson Chungdb8a8942012-04-03 14:08:41 -07001382 @Override
1383 public int compare(ItemInfo lhs, ItemInfo rhs) {
Winson Chung882a52e2015-07-08 14:32:26 -07001384 if (lhs.container == rhs.container) {
1385 // Within containers, order by their spatial position in that container
1386 switch ((int) lhs.container) {
1387 case LauncherSettings.Favorites.CONTAINER_DESKTOP: {
1388 long lr = (lhs.screenId * screenCellCount +
1389 lhs.cellY * screenCols + lhs.cellX);
1390 long rr = (rhs.screenId * screenCellCount +
1391 rhs.cellY * screenCols + rhs.cellX);
Winson722e8562015-10-07 13:04:30 -07001392 return Utilities.longCompare(lr, rr);
Winson Chung882a52e2015-07-08 14:32:26 -07001393 }
1394 case LauncherSettings.Favorites.CONTAINER_HOTSEAT: {
1395 // We currently use the screen id as the rank
Winson722e8562015-10-07 13:04:30 -07001396 return Utilities.longCompare(lhs.screenId, rhs.screenId);
Winson Chung882a52e2015-07-08 14:32:26 -07001397 }
1398 default:
Sunny Goyal6c56c682015-07-16 14:09:05 -07001399 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Winson Chung882a52e2015-07-08 14:32:26 -07001400 throw new RuntimeException("Unexpected container type when " +
1401 "sorting workspace items.");
1402 }
1403 return 0;
1404 }
1405 } else {
1406 // Between containers, order by hotseat, desktop
Winson722e8562015-10-07 13:04:30 -07001407 return Utilities.longCompare(lhs.container, rhs.container);
Winson Chung882a52e2015-07-08 14:32:26 -07001408 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001409 }
1410 });
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001411 }
Winson Chungdb8a8942012-04-03 14:08:41 -07001412
Adam Cohendcd297f2013-06-18 13:13:40 -07001413 private void bindWorkspaceScreens(final Callbacks oldCallbacks,
1414 final ArrayList<Long> orderedScreens) {
Adam Cohendcd297f2013-06-18 13:13:40 -07001415 final Runnable r = new Runnable() {
1416 @Override
1417 public void run() {
1418 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1419 if (callbacks != null) {
1420 callbacks.bindScreens(orderedScreens);
1421 }
1422 }
1423 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001424 runOnMainThread(r);
Adam Cohendcd297f2013-06-18 13:13:40 -07001425 }
1426
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001427 private void bindWorkspaceItems(final Callbacks oldCallbacks,
1428 final ArrayList<ItemInfo> workspaceItems,
1429 final ArrayList<LauncherAppWidgetInfo> appWidgets,
Sunny Goyal527c7d32015-08-28 15:19:36 -07001430 final Executor executor) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001431
1432 // Bind the workspace items
Winson Chungdb8a8942012-04-03 14:08:41 -07001433 int N = workspaceItems.size();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001434 for (int i = 0; i < N; i += ITEMS_CHUNK) {
Joe Onorato36115782010-06-17 13:28:48 -04001435 final int start = i;
1436 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001437 final Runnable r = new Runnable() {
1438 @Override
Joe Onorato9c1289c2009-08-17 11:03:03 -04001439 public void run() {
Joe Onoratoc131b742010-03-11 15:45:05 -08001440 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001441 if (callbacks != null) {
Winson Chung64359a52013-07-08 17:17:08 -07001442 callbacks.bindItems(workspaceItems, start, start+chunkSize,
1443 false);
Joe Onorato9c1289c2009-08-17 11:03:03 -04001444 }
1445 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001446 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001447 executor.execute(r);
Joe Onorato36115782010-06-17 13:28:48 -04001448 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001449
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001450 // Bind the widgets, one at a time
1451 N = appWidgets.size();
1452 for (int i = 0; i < N; i++) {
1453 final LauncherAppWidgetInfo widget = appWidgets.get(i);
1454 final Runnable r = new Runnable() {
1455 public void run() {
1456 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1457 if (callbacks != null) {
1458 callbacks.bindAppWidget(widget);
1459 }
1460 }
1461 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001462 executor.execute(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001463 }
1464 }
1465
1466 /**
1467 * Binds all loaded data to actual views on the main thread.
1468 */
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001469 private void bindWorkspace(int synchronizeBindPage) {
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001470 final long t = SystemClock.uptimeMillis();
1471 Runnable r;
1472
1473 // Don't use these two variables in any of the callback runnables.
1474 // Otherwise we hold a reference to them.
1475 final Callbacks oldCallbacks = mCallbacks.get();
1476 if (oldCallbacks == null) {
1477 // This launcher has exited and nobody bothered to tell us. Just bail.
1478 Log.w(TAG, "LoaderTask running with no launcher");
1479 return;
1480 }
1481
Winson Chung9b9fb962013-11-15 15:39:34 -08001482 // Save a copy of all the bg-thread collections
Sunny Goyal44c06432016-04-02 10:56:02 -07001483 ArrayList<ItemInfo> workspaceItems = new ArrayList<>();
1484 ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<>();
1485 ArrayList<Long> orderedScreenIds = new ArrayList<>();
Sunny Goyale2df0622015-04-24 11:27:00 -07001486
Sunny Goyale9956a72016-09-01 17:24:47 -07001487 synchronized (sBgDataModel) {
1488 workspaceItems.addAll(sBgDataModel.workspaceItems);
1489 appWidgets.addAll(sBgDataModel.appWidgets);
1490 orderedScreenIds.addAll(sBgDataModel.workspaceScreens);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001491 }
1492
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001493 final int currentScreen;
1494 {
1495 int currScreen = synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE
1496 ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen();
1497 if (currScreen >= orderedScreenIds.size()) {
1498 // There may be no workspace screens (just hotseat items and an empty page).
1499 currScreen = PagedView.INVALID_RESTORE_PAGE;
1500 }
1501 currentScreen = currScreen;
Winson Chung9b9fb962013-11-15 15:39:34 -08001502 }
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001503 final boolean validFirstPage = currentScreen >= 0;
1504 final long currentScreenId =
1505 validFirstPage ? orderedScreenIds.get(currentScreen) : INVALID_SCREEN_ID;
Winson Chung9b9fb962013-11-15 15:39:34 -08001506
Winson Chung9b9fb962013-11-15 15:39:34 -08001507 // Separate the items that are on the current screen, and all the other remaining items
Sunny Goyal44c06432016-04-02 10:56:02 -07001508 ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
1509 ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
1510 ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
1511 ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001512
Winson Chung9b9fb962013-11-15 15:39:34 -08001513 filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001514 otherWorkspaceItems);
Winson Chung9b9fb962013-11-15 15:39:34 -08001515 filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001516 otherAppWidgets);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001517 sortWorkspaceItemsSpatially(currentWorkspaceItems);
1518 sortWorkspaceItemsSpatially(otherWorkspaceItems);
1519
1520 // Tell the workspace that we're about to start binding items
1521 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001522 public void run() {
1523 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1524 if (callbacks != null) {
Sunny Goyal527c7d32015-08-28 15:19:36 -07001525 callbacks.clearPendingBinds();
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001526 callbacks.startBinding();
Joe Onorato36115782010-06-17 13:28:48 -04001527 }
1528 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001529 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001530 runOnMainThread(r);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001531
Adam Cohendcd297f2013-06-18 13:13:40 -07001532 bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
1533
Sunny Goyal527c7d32015-08-28 15:19:36 -07001534 Executor mainExecutor = new DeferredMainThreadExecutor();
1535 // Load items on the current page.
Sunny Goyal44c06432016-04-02 10:56:02 -07001536 bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, mainExecutor);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001537
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001538 // In case of validFirstPage, only bind the first screen, and defer binding the
1539 // remaining screens after first onDraw (and an optional the fade animation whichever
1540 // happens later).
1541 // This ensures that the first screen is immediately visible (eg. during rotation)
1542 // In case of !validFirstPage, bind all pages one after other.
1543 final Executor deferredExecutor =
1544 validFirstPage ? new ViewOnDrawExecutor(mHandler) : mainExecutor;
1545
1546 mainExecutor.execute(new Runnable() {
1547 @Override
1548 public void run() {
1549 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1550 if (callbacks != null) {
1551 callbacks.finishFirstPageBind(
1552 validFirstPage ? (ViewOnDrawExecutor) deferredExecutor : null);
1553 }
1554 }
1555 });
Sunny Goyal527c7d32015-08-28 15:19:36 -07001556
Sunny Goyal44c06432016-04-02 10:56:02 -07001557 bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, deferredExecutor);
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001558
1559 // Tell the workspace that we're done binding items
1560 r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001561 public void run() {
1562 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1563 if (callbacks != null) {
Sunny Goyal66cfdc22015-02-02 13:01:51 -08001564 callbacks.finishBindingItems();
Joe Onorato36115782010-06-17 13:28:48 -04001565 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001566
Sunny Goyal639e9062015-08-19 19:17:06 -07001567 mIsLoadingAndBindingWorkspace = false;
1568
1569 // Run all the bind complete runnables after workspace is bound.
1570 if (!mBindCompleteRunnables.isEmpty()) {
1571 synchronized (mBindCompleteRunnables) {
1572 for (final Runnable r : mBindCompleteRunnables) {
1573 runOnWorkerThread(r);
1574 }
1575 mBindCompleteRunnables.clear();
1576 }
1577 }
1578
Winson Chung98e030b2012-05-07 16:01:11 -07001579 // If we're profiling, ensure this is the last thing in the queue.
Joe Onorato36115782010-06-17 13:28:48 -04001580 if (DEBUG_LOADERS) {
1581 Log.d(TAG, "bound workspace in "
1582 + (SystemClock.uptimeMillis()-t) + "ms");
1583 }
Winson Chung36a62fe2012-05-06 18:04:42 -07001584
Joe Onorato36115782010-06-17 13:28:48 -04001585 }
Winson Chungb8b2a5a2012-07-12 17:55:31 -07001586 };
Sunny Goyal527c7d32015-08-28 15:19:36 -07001587 deferredExecutor.execute(r);
1588
Sunny Goyalb5b9ad62016-04-02 11:23:39 -07001589 if (validFirstPage) {
Sunny Goyal527c7d32015-08-28 15:19:36 -07001590 r = new Runnable() {
1591 public void run() {
1592 Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1593 if (callbacks != null) {
1594 // We are loading synchronously, which means, some of the pages will be
1595 // bound after first draw. Inform the callbacks that page binding is
1596 // not complete, and schedule the remaining pages.
1597 if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
1598 callbacks.onPageBoundSynchronously(currentScreen);
1599 }
1600 callbacks.executeOnNextDraw((ViewOnDrawExecutor) deferredExecutor);
1601 }
1602 }
1603 };
Sunny Goyald33860f2015-04-23 16:02:20 -07001604 runOnMainThread(r);
Winson Chung4a2afa32012-07-19 14:53:05 -07001605 }
Joe Onorato36115782010-06-17 13:28:48 -04001606 }
Joe Onoratocc67f472010-06-08 10:54:30 -07001607
Sunny Goyal4e5cc642015-06-25 16:37:44 -07001608 private void updateIconCache() {
1609 // Ignore packages which have a promise icon.
1610 HashSet<String> packagesToIgnore = new HashSet<>();
Sunny Goyale9956a72016-09-01 17:24:47 -07001611 synchronized (sBgDataModel) {
1612 for (ItemInfo info : sBgDataModel.itemsIdMap) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -07001613 if (info instanceof ShortcutInfo) {
1614 ShortcutInfo si = (ShortcutInfo) info;
1615 if (si.isPromise() && si.getTargetComponent() != null) {
1616 packagesToIgnore.add(si.getTargetComponent().getPackageName());
1617 }
1618 } else if (info instanceof LauncherAppWidgetInfo) {
1619 LauncherAppWidgetInfo lawi = (LauncherAppWidgetInfo) info;
1620 if (lawi.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)) {
1621 packagesToIgnore.add(lawi.providerName.getPackageName());
1622 }
1623 }
1624 }
1625 }
1626 mIconCache.updateDbIcons(packagesToIgnore);
1627 }
1628
Joe Onorato36115782010-06-17 13:28:48 -04001629 private void onlyBindAllApps() {
1630 final Callbacks oldCallbacks = mCallbacks.get();
1631 if (oldCallbacks == null) {
1632 // This launcher has exited and nobody bothered to tell us. Just bail.
1633 Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
1634 return;
1635 }
1636
1637 // shallow copy
Winson Chungc208ff92012-03-29 17:37:41 -07001638 @SuppressWarnings("unchecked")
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001639 final ArrayList<AppInfo> list
1640 = (ArrayList<AppInfo>) mBgAllAppsList.data.clone();
Winson Chungc93e5ae2012-07-23 20:48:26 -07001641 Runnable r = new Runnable() {
Joe Onorato36115782010-06-17 13:28:48 -04001642 public void run() {
1643 final long t = SystemClock.uptimeMillis();
1644 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
1645 if (callbacks != null) {
1646 callbacks.bindAllApplications(list);
1647 }
1648 if (DEBUG_LOADERS) {
1649 Log.d(TAG, "bound all " + list.size() + " apps from cache in "
Hyunyoung Song747a5bc2016-02-08 11:31:33 -08001650 + (SystemClock.uptimeMillis() - t) + "ms");
Joe Onorato36115782010-06-17 13:28:48 -04001651 }
1652 }
Winson Chungc93e5ae2012-07-23 20:48:26 -07001653 };
Tony Wickham80f57872016-06-29 18:12:15 -07001654 runOnMainThread(r);
Joe Onorato36115782010-06-17 13:28:48 -04001655 }
1656
Winson Chung64359a52013-07-08 17:17:08 -07001657 private void loadAllApps() {
1658 final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Joe Onorato36115782010-06-17 13:28:48 -04001659
Joe Onorato36115782010-06-17 13:28:48 -04001660 final Callbacks oldCallbacks = mCallbacks.get();
1661 if (oldCallbacks == null) {
1662 // This launcher has exited and nobody bothered to tell us. Just bail.
Winson Chung64359a52013-07-08 17:17:08 -07001663 Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
Joe Onorato36115782010-06-17 13:28:48 -04001664 return;
1665 }
1666
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001667 final List<UserHandle> profiles = mUserManager.getUserProfiles();
Kenny Guyed131872014-04-30 03:02:21 +01001668
Winson Chung64359a52013-07-08 17:17:08 -07001669 // Clear the list of apps
1670 mBgAllAppsList.clear();
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001671 for (UserHandle user : profiles) {
Kenny Guyed131872014-04-30 03:02:21 +01001672 // Query for the set of apps
1673 final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Sunny Goyal3e9be432017-01-05 15:22:41 -08001674 final List<LauncherActivityInfo> apps = mLauncherApps.getActivityList(null, user);
Kenny Guyed131872014-04-30 03:02:21 +01001675 if (DEBUG_LOADERS) {
1676 Log.d(TAG, "getActivityList took "
1677 + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
1678 Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
1679 }
1680 // Fail if we don't have any apps
Sunny Goyale0f58d72014-11-10 18:05:31 -08001681 // TODO: Fix this. Only fail for the current user.
Kenny Guyed131872014-04-30 03:02:21 +01001682 if (apps == null || apps.isEmpty()) {
1683 return;
1684 }
Kenny Guyff05f432016-01-22 17:48:29 +00001685 boolean quietMode = mUserManager.isQuietModeEnabled(user);
Kenny Guyed131872014-04-30 03:02:21 +01001686 // Create the ApplicationInfos
1687 for (int i = 0; i < apps.size(); i++) {
Sunny Goyal3e9be432017-01-05 15:22:41 -08001688 LauncherActivityInfo app = apps.get(i);
Kenny Guyed131872014-04-30 03:02:21 +01001689 // This builds the icon bitmaps.
Sunny Goyal24bb66a2017-03-21 15:12:01 -07001690 mBgAllAppsList.add(new AppInfo(app, user, quietMode), app);
Kenny Guyed131872014-04-30 03:02:21 +01001691 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08001692
Sunny Goyal756a28a2015-04-23 17:07:55 -07001693 final ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
1694 if (heuristic != null) {
Sunny Goyal639e9062015-08-19 19:17:06 -07001695 final Runnable r = new Runnable() {
Sunny Goyal756a28a2015-04-23 17:07:55 -07001696
1697 @Override
1698 public void run() {
1699 heuristic.processUserApps(apps);
1700 }
Sunny Goyal639e9062015-08-19 19:17:06 -07001701 };
1702 runOnMainThread(new Runnable() {
1703
1704 @Override
1705 public void run() {
1706 // Check isLoadingWorkspace on the UI thread, as it is updated on
1707 // the UI thread.
1708 if (mIsLoadingAndBindingWorkspace) {
1709 synchronized (mBindCompleteRunnables) {
1710 mBindCompleteRunnables.add(r);
1711 }
1712 } else {
1713 runOnWorkerThread(r);
1714 }
1715 }
Sunny Goyal756a28a2015-04-23 17:07:55 -07001716 });
Sunny Goyale0f58d72014-11-10 18:05:31 -08001717 }
Winson Chung64359a52013-07-08 17:17:08 -07001718 }
Bjorn Bringert85f418d2013-09-06 12:50:05 +01001719 // Huh? Shouldn't this be inside the Runnable below?
Michael Jurkaeadbfc52013-09-04 00:45:37 +02001720 final ArrayList<AppInfo> added = mBgAllAppsList.added;
1721 mBgAllAppsList.added = new ArrayList<AppInfo>();
Winson Chung64359a52013-07-08 17:17:08 -07001722
1723 // Post callback on main thread
1724 mHandler.post(new Runnable() {
1725 public void run() {
Hyunyoung Song9892e582015-05-05 10:07:23 -07001726
Winson Chung64359a52013-07-08 17:17:08 -07001727 final long bindTime = SystemClock.uptimeMillis();
Winson Chung11a1a532013-09-13 11:14:45 -07001728 final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
Winson Chung64359a52013-07-08 17:17:08 -07001729 if (callbacks != null) {
1730 callbacks.bindAllApplications(added);
1731 if (DEBUG_LOADERS) {
1732 Log.d(TAG, "bound " + added.size() + " apps in "
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001733 + (SystemClock.uptimeMillis() - bindTime) + "ms");
Winson Chung64359a52013-07-08 17:17:08 -07001734 }
1735 } else {
1736 Log.i(TAG, "not binding apps: no Launcher activity");
1737 }
1738 }
1739 });
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001740 // Cleanup any data stored for a deleted user.
1741 ManagedProfileHeuristic.processAllUsers(profiles, mContext);
Joe Onorato36115782010-06-17 13:28:48 -04001742 if (DEBUG_LOADERS) {
Winson Chung64359a52013-07-08 17:17:08 -07001743 Log.d(TAG, "Icons processed in "
1744 + (SystemClock.uptimeMillis() - loadTime) + "ms");
Joe Onoratobe386092009-11-17 17:32:16 -08001745 }
1746 }
1747
Sunny Goyaldd96a5e2017-02-17 11:22:34 -08001748 private void loadDeepShortcuts() {
1749 if (!mModelLoaded) {
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001750 sBgDataModel.deepShortcutMap.clear();
Sunny Goyaldde4fd92016-11-21 16:02:39 +05301751 DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(mContext);
1752 mHasShortcutHostPermission = shortcutManager.hasHostPermission();
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001753 if (mHasShortcutHostPermission) {
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001754 for (UserHandle user : mUserManager.getUserProfiles()) {
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001755 if (mUserManager.isUserUnlocked(user)) {
Sunny Goyaldde4fd92016-11-21 16:02:39 +05301756 List<ShortcutInfoCompat> shortcuts =
1757 shortcutManager.queryForAllShortcuts(user);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001758 sBgDataModel.updateDeepShortcutMap(null, user, shortcuts);
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001759 }
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001760 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001761 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001762 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001763 }
Joe Onorato36115782010-06-17 13:28:48 -04001764 }
1765
Tony Wickham80f57872016-06-29 18:12:15 -07001766 public void bindDeepShortcuts() {
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001767 final MultiHashMap<ComponentKey, String> shortcutMapCopy =
1768 sBgDataModel.deepShortcutMap.clone();
Tony Wickham80f57872016-06-29 18:12:15 -07001769 Runnable r = new Runnable() {
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001770 @Override
1771 public void run() {
1772 Callbacks callbacks = getCallback();
1773 if (callbacks != null) {
1774 callbacks.bindDeepShortcutMap(shortcutMapCopy);
1775 }
1776 }
Tony Wickham80f57872016-06-29 18:12:15 -07001777 };
1778 runOnMainThread(r);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001779 }
1780
Sunny Goyal75b0f552015-05-20 21:57:06 -07001781 /**
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001782 * Refreshes the cached shortcuts if the shortcut permission has changed.
1783 * Current implementation simply reloads the workspace, but it can be optimized to
1784 * use partial updates similar to {@link UserManagerCompat}
1785 */
1786 public void refreshShortcutsIfRequired() {
Sunny Goyalf5e37442016-11-02 10:31:24 -07001787 if (Utilities.ATLEAST_NOUGAT_MR1) {
Sunny Goyal95f3d6b2016-08-10 16:09:29 -07001788 sWorker.removeCallbacks(mShortcutPermissionCheckRunnable);
1789 sWorker.post(mShortcutPermissionCheckRunnable);
1790 }
1791 }
1792
1793 /**
Sunny Goyal75b0f552015-05-20 21:57:06 -07001794 * Called when the icons for packages have been updated in the icon cache.
1795 */
Sunny Goyal7c74e4a2016-12-15 15:53:17 -08001796 public void onPackageIconsUpdated(HashSet<String> updatedPackages, UserHandle user) {
Sunny Goyal75b0f552015-05-20 21:57:06 -07001797 // If any package icon has changed (app was updated while launcher was dead),
1798 // update the corresponding shortcuts.
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001799 enqueueModelUpdateTask(new CacheDataUpdatedTask(
1800 CacheDataUpdatedTask.OP_CACHE_UPDATE, user, updatedPackages));
Sunny Goyal75b0f552015-05-20 21:57:06 -07001801 }
1802
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001803 void enqueueModelUpdateTask(BaseModelUpdateTask task) {
Jon Mirandaf28629a2017-02-23 15:12:42 -08001804 if (!mModelLoaded && mLoaderTask == null) {
1805 if (DEBUG_LOADERS) {
1806 Log.d(TAG, "enqueueModelUpdateTask Ignoring task since loader is pending=" + task);
1807 }
1808 return;
1809 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001810 task.init(this);
1811 runOnWorkerThread(task);
Sunny Goyald3b87ef2016-07-28 12:11:54 -07001812 }
1813
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001814 /**
1815 * A task to be executed on the current callbacks on the UI thread.
1816 * If there is no current callbacks, the task is ignored.
1817 */
1818 public interface CallbackTask {
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001819
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001820 void execute(Callbacks callbacks);
Tony Wickhambfbf7f92016-05-19 11:19:39 -07001821 }
1822
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001823 /**
1824 * A runnable which changes/updates the data model of the launcher based on certain events.
1825 */
1826 public static abstract class BaseModelUpdateTask implements Runnable {
Joe Onorato36115782010-06-17 13:28:48 -04001827
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001828 private LauncherModel mModel;
1829 private DeferredHandler mUiHandler;
Joe Onorato36115782010-06-17 13:28:48 -04001830
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001831 /* package private */
1832 void init(LauncherModel model) {
1833 mModel = model;
1834 mUiHandler = mModel.mHandler;
Joe Onorato36115782010-06-17 13:28:48 -04001835 }
1836
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001837 @Override
Joe Onorato36115782010-06-17 13:28:48 -04001838 public void run() {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001839 if (!mModel.mHasLoaderCompletedOnce) {
Sunny Goyalc905efc2015-05-06 09:54:53 -07001840 // Loader has not yet run.
1841 return;
1842 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001843 execute(mModel.mApp, sBgDataModel, mModel.mBgAllAppsList);
1844 }
Joe Onorato36115782010-06-17 13:28:48 -04001845
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001846 /**
1847 * Execute the actual task. Called on the worker thread.
1848 */
1849 public abstract void execute(
1850 LauncherAppState app, BgDataModel dataModel, AllAppsList apps);
Sunny Goyale0f58d72014-11-10 18:05:31 -08001851
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001852 /**
1853 * Schedules a {@param task} to be executed on the current callbacks.
1854 */
1855 public final void scheduleCallbackTask(final CallbackTask task) {
1856 final Callbacks callbacks = mModel.getCallback();
1857 mUiHandler.post(new Runnable() {
1858 public void run() {
1859 Callbacks cb = mModel.getCallback();
1860 if (callbacks == cb && cb != null) {
1861 task.execute(callbacks);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -07001862 }
1863 }
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001864 });
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001865 }
Sunny Goyal43bf11d2017-02-02 13:52:53 -08001866
1867 public ModelWriter getModelWriter() {
1868 // Updates from model task, do not deal with icon position in hotseat.
1869 return mModel.getWriter(false /* hasVerticalHotseat */);
1870 }
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001871 }
1872
Sunny Goyal1b072632017-01-18 11:30:23 -08001873 public void updateAndBindShortcutInfo(final ShortcutInfo si, final ShortcutInfoCompat info) {
1874 updateAndBindShortcutInfo(new Provider<ShortcutInfo>() {
1875 @Override
1876 public ShortcutInfo get() {
1877 si.updateFromDeepShortcutInfo(info, mApp.getContext());
1878 si.iconBitmap = LauncherIcons.createShortcutIcon(info, mApp.getContext());
1879 return si;
1880 }
1881 });
1882 }
1883
Sunny Goyal10923b32016-07-20 15:42:44 -07001884 /**
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001885 * Utility method to update a shortcut on the background thread.
Sunny Goyal10923b32016-07-20 15:42:44 -07001886 */
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001887 public void updateAndBindShortcutInfo(final Provider<ShortcutInfo> shortcutProvider) {
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001888 enqueueModelUpdateTask(new ExtendedModelTask() {
Sunny Goyal10923b32016-07-20 15:42:44 -07001889 @Override
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001890 public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001891 ShortcutInfo info = shortcutProvider.get();
Sunny Goyalf0ba8b72016-09-09 15:47:55 -07001892 ArrayList<ShortcutInfo> update = new ArrayList<>();
Sunny Goyal10923b32016-07-20 15:42:44 -07001893 update.add(info);
Sunny Goyal1cc1c9a2017-01-06 16:32:57 -08001894 bindUpdatedShortcuts(update, info.user);
Sunny Goyal10923b32016-07-20 15:42:44 -07001895 }
1896 });
1897 }
1898
Sunny Goyald164b7f2016-10-12 20:49:31 -07001899 private void bindWidgetsModel(final Callbacks callbacks) {
1900 final MultiHashMap<PackageItemInfo, WidgetItem> widgets
1901 = mBgWidgetsModel.getWidgetsMap().clone();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001902 mHandler.post(new Runnable() {
1903 @Override
1904 public void run() {
1905 Callbacks cb = getCallback();
1906 if (callbacks == cb && cb != null) {
Sunny Goyald164b7f2016-10-12 20:49:31 -07001907 callbacks.bindAllWidgets(widgets);
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001908 }
Hyunyoung Songd4af1482015-04-20 20:40:03 -07001909 }
1910 });
1911 }
1912
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001913 public void refreshAndBindWidgetsAndShortcuts(
1914 final Callbacks callbacks, final boolean bindFirst) {
1915 runOnWorkerThread(new Runnable() {
1916 @Override
1917 public void run() {
1918 if (bindFirst && !mBgWidgetsModel.isEmpty()) {
Sunny Goyald164b7f2016-10-12 20:49:31 -07001919 bindWidgetsModel(callbacks);
Sunny Goyal31860582015-09-18 08:38:57 -07001920 }
Sunny Goyald164b7f2016-10-12 20:49:31 -07001921 ArrayList<WidgetItem> allWidgets = mBgWidgetsModel.update(mApp.getContext());
1922 bindWidgetsModel(callbacks);
1923
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001924 // update the Widget entries inside DB on the worker thread.
Sunny Goyal87f784c2017-01-11 10:48:34 -08001925 mApp.getWidgetCache().removeObsoletePreviews(allWidgets);
Sunny Goyal31860582015-09-18 08:38:57 -07001926 }
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001927 });
Michael Jurkac402cd92013-05-20 15:49:32 +02001928 }
1929
Sunny Goyal651077b2014-06-30 14:15:31 -07001930 static boolean isValidProvider(AppWidgetProviderInfo provider) {
1931 return (provider != null) && (provider.provider != null)
1932 && (provider.provider.getPackageName() != null);
1933 }
1934
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -08001935 public void dumpState(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
1936 if (args.length > 0 && TextUtils.equals(args[0], "--all")) {
1937 writer.println(prefix + "All apps list: size=" + mBgAllAppsList.data.size());
1938 for (AppInfo info : mBgAllAppsList.data) {
1939 writer.println(prefix + " title=\"" + info.title + "\" iconBitmap=" + info.iconBitmap
1940 + " componentName=" + info.componentName.getPackageName());
1941 }
Joe Onorato36115782010-06-17 13:28:48 -04001942 }
Hyunyoung Song3c7d9cb2017-01-30 15:11:27 -08001943 sBgDataModel.dump(prefix, fd, writer, args);
Joe Onoratobe386092009-11-17 17:32:16 -08001944 }
Sunny Goyale0f58d72014-11-10 18:05:31 -08001945
1946 public Callbacks getCallback() {
1947 return mCallbacks != null ? mCallbacks.get() : null;
1948 }
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001949
1950 /**
1951 * @return {@link FolderInfo} if its already loaded.
1952 */
1953 public FolderInfo findFolderById(Long folderId) {
Sunny Goyale9956a72016-09-01 17:24:47 -07001954 synchronized (sBgDataModel) {
1955 return sBgDataModel.folders.get(folderId);
Sunny Goyal18bf8e22015-04-08 18:13:46 -07001956 }
1957 }
Sunny Goyal756adbc2015-04-16 15:20:51 -07001958
Sunny Goyal527c7d32015-08-28 15:19:36 -07001959 @Thunk class DeferredMainThreadExecutor implements Executor {
1960
1961 @Override
1962 public void execute(Runnable command) {
1963 runOnMainThread(command);
1964 }
1965 }
1966
Sunny Goyal756adbc2015-04-16 15:20:51 -07001967 /**
1968 * @return the looper for the worker thread which can be used to start background tasks.
1969 */
1970 public static Looper getWorkerLooper() {
1971 return sWorkerThread.getLooper();
1972 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001973}