blob: 8ed3314efd56dc67cdd5aabebf6a2829bb46881e [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
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080035import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070042import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080047import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080049import android.provider.BaseColumns;
Adam Cohen228da5a2011-07-27 22:23:47 -070050import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070052
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
54import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070056import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080057import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070058import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070059import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070060import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalefb7e842018-10-04 15:11:00 -070062import com.android.launcher3.util.IntArray;
63import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080064import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070065import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070066import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070067
Sunny Goyal05f30882017-05-03 12:42:18 -070068import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070071import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070072import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070073import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080074import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070077 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080078 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyal05f30882017-05-03 12:42:18 -070080 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
81
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070082 /**
83 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080084 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070085 */
Sunny Goyalc5939392018-12-07 11:43:47 -080086 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Sunny Goyal4276e7b2018-11-26 23:44:41 -080088 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070089
Sunny Goyale87e6ab2014-11-21 22:42:53 -080090 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070092 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
93
Sunny Goyalb5b55c82016-05-10 12:28:59 -070094 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
95 private Handler mListenerHandler;
96
Sunny Goyalf076eae2016-01-11 12:25:10 -080097 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Hyunyoung Song6aa37292017-02-06 10:46:24 -080099 /**
100 * $ adb shell dumpsys activity provider com.android.launcher3
101 */
102 @Override
103 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
104 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
105 if (appState == null || !appState.getModel().isModelLoaded()) {
106 return;
107 }
108 appState.getModel().dumpState("", fd, writer, args);
109 }
110
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111 @Override
112 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800113 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700114 Log.d(TAG, "Launcher process started");
115 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700116 mListenerHandler = new Handler(mListenerWrapper);
117
Sunny Goyalfdbef272017-02-01 12:52:54 -0800118 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800119 // is the first component to get created.
120 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 return true;
122 }
123
Sunny Goyald3849d12015-10-29 10:28:32 -0700124 /**
125 * Sets a provider listener.
126 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700127 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700128 Preconditions.assertUIThread();
129 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700130 }
131
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 @Override
133 public String getType(Uri uri) {
134 SqlArguments args = new SqlArguments(uri, null, null);
135 if (TextUtils.isEmpty(args.where)) {
136 return "vnd.android.cursor.dir/" + args.table;
137 } else {
138 return "vnd.android.cursor.item/" + args.table;
139 }
140 }
141
Sunny Goyalf076eae2016-01-11 12:25:10 -0800142 /**
143 * Overridden in tests
144 */
145 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700146 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700147 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700148
149 if (RestoreDbTask.isPending(getContext())) {
150 if (!RestoreDbTask.performRestore(mOpenHelper)) {
151 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
152 }
153 // Set is pending to false irrespective of the result, so that it doesn't get
154 // executed again.
155 RestoreDbTask.setPending(getContext(), false);
156 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Cursor query(Uri uri, String[] projection, String selection,
162 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
166 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
167 qb.setTables(args.table);
168
Romain Guy73b979d2009-06-09 12:57:21 -0700169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
171 result.setNotificationUri(getContext().getContentResolver(), uri);
172
173 return result;
174 }
175
Sunny Goyalefb7e842018-10-04 15:11:00 -0700176 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500178 if (values == null) {
179 throw new RuntimeException("Error: attempting to insert null values");
180 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800181 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 throw new RuntimeException("Error: attempting to add item without specifying an id");
183 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800184 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700185 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700186 }
187
Sunny Goyald1064182015-08-13 12:08:30 -0700188 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700189 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700190 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
191 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800192 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700193 }
194 }
195 }
196
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 @Override
198 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700199 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 SqlArguments args = new SqlArguments(uri);
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 // In very limited cases, we support system|signature permission apps to modify the db.
203 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700204 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700205 return null;
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700211 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800212 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
214 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700215 notifyListeners();
216
Sunny Goyalc74e4192015-09-08 14:01:03 -0700217 if (Utilities.ATLEAST_MARSHMALLOW) {
218 reloadLauncherIfExternal();
219 } else {
220 // Deprecated behavior to support legacy devices which rely on provider callbacks.
221 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
222 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800223 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700224 }
225
226 String notify = uri.getQueryParameter("notify");
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
230 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 return uri;
232 }
233
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700234 private boolean initializeExternalAdd(ContentValues values) {
235 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700236 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700237 values.put(LauncherSettings.Favorites._ID, id);
238
239 // 2. In the case of an app widget, and if no app widget id is specified, we
240 // attempt allocate and bind the widget.
241 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
242 if (itemType != null &&
243 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
244 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
245
246 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
247 ComponentName cn = ComponentName.unflattenFromString(
248 values.getAsString(Favorites.APPWIDGET_PROVIDER));
249
250 if (cn != null) {
251 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700252 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
253 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700254 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
255 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700257 return false;
258 }
259 } catch (RuntimeException e) {
260 Log.e(TAG, "Failed to initialize external widget", e);
261 return false;
262 }
263 } else {
264 return false;
265 }
266 }
267
Sunny Goyalc5939392018-12-07 11:43:47 -0800268 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700269 }
270
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800271 @Override
272 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700273 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800274 SqlArguments args = new SqlArguments(uri);
275
276 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700277 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800278 int numValues = values.length;
279 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400280 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700281 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
282 return 0;
283 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700285 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800286 }
287
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700288 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700289 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 return values.length;
291 }
292
293 @Override
Yura085c8532014-02-11 15:15:29 +0000294 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
295 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700296 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700297 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000298 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700299 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700300 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000301 return result;
Yura085c8532014-02-11 15:15:29 +0000302 }
303 }
304
305 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700307 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800308 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
309
310 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800311
Louis Begina9c21c62016-08-15 15:18:41 -0700312 if (Binder.getCallingPid() != Process.myPid()
313 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700314 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700315 }
316 int count = db.delete(args.table, args.where, args.args);
317 if (count > 0) {
318 notifyListeners();
319 reloadLauncherIfExternal();
320 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800321 return count;
322 }
323
324 @Override
325 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700326 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
328
Chris Wren1ada10d2013-09-13 18:01:38 -0400329 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
331 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700332 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333
Sunny Goyald1064182015-08-13 12:08:30 -0700334 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 return count;
336 }
337
Sunny Goyal7779d622015-06-11 16:18:39 -0700338 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700339 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700340 if (Binder.getCallingUid() != Process.myUid()) {
341 return null;
342 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700343 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700344
345 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700346 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
347 clearFlagEmptyDbCreated();
348 return null;
349 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700350 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
351 Bundle result = new Bundle();
352 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
353 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
354 return result;
355 }
Sunny Goyald2497482015-09-22 18:24:19 -0700356 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
357 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700358 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
359 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700360 return result;
361 }
362 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
363 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700364 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700365 return result;
366 }
367 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
368 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700369 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700370 return result;
371 }
372 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800373 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700374 return null;
375 }
376 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
377 loadDefaultFavoritesIfNecessary();
378 return null;
379 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700380 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
381 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
382 return null;
383 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700384 }
385 return null;
386 }
387
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700388 /**
389 * Deletes any empty folder from the DB.
390 * @return Ids of deleted folders.
391 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700392 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700393 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700394 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700395 // Select folders whose id do not match any container value.
396 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
397 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
398 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
399 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700400 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800401
402 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
403 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700404 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700405 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700406 LauncherSettings.Favorites._ID, folderIds), null);
407 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700408 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800409 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700410 } catch (SQLException ex) {
411 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800412 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700413 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700414 }
415
Sunny Goyalf076eae2016-01-11 12:25:10 -0800416 /**
417 * Overridden in tests
418 */
419 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700420 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400421 }
422
Adam Cohen091440a2015-03-18 14:16:05 -0700423 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800424 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800425 }
426
Sunny Goyald2497482015-09-22 18:24:19 -0700427 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700428 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700429 }
430
Sunny Goyal42de82f2014-09-26 22:09:29 -0700431 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700432 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700433 * 1) From the app restrictions
434 * 2) From a package provided by play store
435 * 3) From a partner configuration APK, already in the system image
436 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700437 */
Sunny Goyald2497482015-09-22 18:24:19 -0700438 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700439 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700440
Winson Chungc763c4e2013-07-19 13:49:06 -0700441 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500442 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200443
Sunny Goyal55fddc82017-04-06 15:02:52 -0700444 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700445 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700446 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700447 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700448 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700449 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700450 final Partner partner = Partner.get(getContext().getPackageManager());
451 if (partner != null && partner.hasDefaultLayout()) {
452 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700453 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700454 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700455 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700456 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700457 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700458 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700459 }
460 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700461
Sunny Goyal9d219682014-10-23 14:21:02 -0700462 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700463 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700464 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700465 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800466
467 // There might be some partially restored DB items, due to buggy restore logic in
468 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800469 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700470 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700471 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
472 && usingExternallyProvidedLayout) {
473 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800474 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700475 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700477 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700478 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700479 }
480 }
481
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700482 /**
483 * Creates workspace loader from an XML resource listed in the app restrictions.
484 *
485 * @return the loader if the restrictions are set and the resource exists; null otherwise.
486 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700487 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700488 Context ctx = getContext();
489 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
490 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700491 if (bundle == null) {
492 return null;
493 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700494
Sunny Goyal35ca8732015-04-06 10:45:31 -0700495 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700496 if (packageName != null) {
497 try {
498 Resources targetResources = ctx.getPackageManager()
499 .getResourcesForApplication(packageName);
500 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700501 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700502 } catch (NameNotFoundException e) {
503 Log.e(TAG, "Target package for restricted profile not found", e);
504 return null;
505 }
506 }
507 return null;
508 }
509
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700510 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700511 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
512 int defaultLayout = idp.defaultLayoutId;
513
514 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
515 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
516 defaultLayout = idp.demoModeLayoutId;
517 }
518
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700520 mOpenHelper, getContext().getResources(), defaultLayout);
521 }
522
Sunny Goyald3849d12015-10-29 10:28:32 -0700523 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800524 * The class is subclassed in tests to create an in-memory db.
525 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800526 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700527 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800528 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700529 private int mMaxItemId = -1;
530 private int mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800531
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700532 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
533 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700534 // Table creation sometimes fails silently, which leads to a crash loop.
535 // This way, we will try to create a table every time after crash, so the device
536 // would eventually be able to recover.
Sunny Goyalc5939392018-12-07 11:43:47 -0800537 if (!tableExists(Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700538 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
539 // This operation is a no-op if the table already exists.
540 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700541 }
542
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700543 initIds();
544 }
545
546 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700547 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700548 */
549 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800551 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700552 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700553 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700554 }
555
556 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700557 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
558 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700559 if (mMaxItemId == -1) {
560 mMaxItemId = initializeMaxItemId(getWritableDatabase());
561 }
562 if (mMaxScreenId == -1) {
563 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700564 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 }
566
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700567 private boolean tableExists(String tableName) {
568 Cursor c = getReadableDatabase().query(
569 true, "sqlite_master", new String[] {"tbl_name"},
570 "tbl_name = ?", new String[] {tableName},
571 null, null, null, null, null);
572 try {
573 return c.getCount() > 0;
574 } finally {
575 c.close();
576 }
577 }
578
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800579 @Override
580 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800581 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700582
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 mMaxItemId = 1;
584 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800588 // Fresh and clean launcher DB.
589 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800590 onEmptyDbCreated();
591 }
592
593 /**
594 * Overriden in tests.
595 */
596 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700597 // Database was just created, so wipe any previous widgets
598 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700599 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700600 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530601 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700602 }
603
Sunny Goyalf076eae2016-01-11 12:25:10 -0800604 // Set the flag for empty DB
605 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800606 }
607
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700608 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800609 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800610 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
612
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700613 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700614 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700615 }
616
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800617 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700618 public void onOpen(SQLiteDatabase db) {
619 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700620
621 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
622 if (!schemaFile.exists()) {
623 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700624 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800625 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700626 }
627
628 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700629 * One-time data updated before support of onDowngrade was added. This update is backwards
630 * compatible and can safely be run multiple times.
631 * Note: No new logic should be added here after release, as the new logic might not get
632 * executed on an existing device.
633 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700634 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700635 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
636 // Remove "profile extra"
637 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
638 for (UserHandle user : um.getUserProfiles()) {
639 long serial = um.getSerialNumberForUser(user);
640 String sql = "update favorites set intent = replace(intent, "
641 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
642 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700643 }
644 }
645
646 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700648 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800649 switch (oldVersion) {
650 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800651 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800652 case 12:
653 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800654 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700655 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800656 // Insert new column for holding widget provider name
657 db.execSQL("ALTER TABLE favorites " +
658 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700659 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800660 } catch (SQLException ex) {
661 Log.e(TAG, ex.getMessage(), ex);
662 // Old version remains, which means we wipe old data
663 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800664 }
665 }
666 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800667 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800668 // Old version remains, which means we wipe old data
669 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800670 }
671 }
672 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700673 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800674 // Old version remains, which means we wipe old data
675 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800676 }
677 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800678 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700679 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800680 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800682 case 18:
683 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800684 case 19: {
685 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800686 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800687 // Old version remains, which means we wipe old data
688 break;
689 }
690 }
691 case 20:
692 if (!updateFolderItemsRank(db, true)) {
693 break;
694 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800695 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800696 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800697 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700698 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
699 // Old version remains, which means we wipe old data
700 break;
701 }
702 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700703 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700704 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700705 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000706 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700707 case 25:
708 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700709 case 26:
710 // QSB was moved to the grid. Clear the first row on screen 0.
Ryan Lothianfa530cd2018-10-12 14:14:16 -0400711 if (FeatureFlags.QSB_ON_FIRST_SCREEN.get() &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800712 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700713 break;
714 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800715 case 27: {
716 // Update the favorites table so that the screen ids are ordered based on
717 // workspace page rank.
718 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
719 BaseColumns._ID, null, null, "screenRank");
720 int[] original = finalScreens.toArray();
721 Arrays.sort(original);
722 String updatemap = "";
723 for (int i = 0; i < original.length; i++) {
724 if (finalScreens.get(i) != original[i]) {
725 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
726 Favorites.SCREEN, finalScreens.get(i), original[i]);
727 }
728 }
729 if (!TextUtils.isEmpty(updatemap)) {
730 String query = String.format(Locale.ENGLISH,
731 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
732 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
733 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
734 db.execSQL(query);
735 }
736 db.execSQL("DROP TABLE IF EXISTS workspaceScreens");
737 }
738 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800739 // DB Upgraded successfully
740 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400741 }
742
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 // DB was not upgraded
744 Log.w(TAG, "Destroying all old data.");
745 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800746 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800747
Adam Cohen9b1d0622014-05-21 19:01:57 -0700748 @Override
749 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700750 try {
751 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
752 .onDowngrade(db, oldVersion, newVersion);
753 } catch (Exception e) {
754 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
755 ". Wiping databse.", e);
756 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700757 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700758 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700759
Sunny Goyal42de82f2014-09-26 22:09:29 -0700760 /**
761 * Clears all the data for a fresh start.
762 */
763 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700764 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800765 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
Sunny Goyalc5939392018-12-07 11:43:47 -0800766 db.execSQL("DROP TABLE IF EXISTS workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800767 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700768 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800769 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700770 }
771
Sunny Goyald2f38192015-02-25 10:46:34 -0800772 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700773 * Removes widgets which are registered to the Launcher's host, but are not present
774 * in our model.
775 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700776 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700777 public void removeGhostWidgets(SQLiteDatabase db) {
778 // Get all existing widget ids.
779 final AppWidgetHost host = newLauncherWidgetHost();
780 final int[] allWidgets;
781 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700782 // Although the method was defined in O, it has existed since the beginning of time,
783 // so it might work on older platforms as well.
784 allWidgets = host.getAppWidgetIds();
785 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700786 Log.e(TAG, "getAppWidgetIds not supported", e);
787 return;
788 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800789 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
790 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
791 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700792 for (int widgetId : allWidgets) {
793 if (!validWidgets.contains(widgetId)) {
794 try {
795 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
796 host.deleteAppWidgetId(widgetId);
797 } catch (RuntimeException e) {
798 // Ignore
799 }
800 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700801 }
802 }
803
804 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700805 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
806 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
807 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700808 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700809 try (SQLiteTransaction t = new SQLiteTransaction(db);
810 // Only consider the primary user as other users can't have a shortcut.
811 Cursor c = db.query(Favorites.TABLE_NAME,
812 new String[] { Favorites._ID, Favorites.INTENT},
813 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
814 " AND profileId=" + getDefaultUserSerial(),
815 null, null, null, null);
816 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
817 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
818 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700819 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
820 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
821
822 while (c.moveToNext()) {
823 String intentDescription = c.getString(intentIndex);
824 Intent intent;
825 try {
826 intent = Intent.parseUri(intentDescription, 0);
827 } catch (URISyntaxException e) {
828 Log.e(TAG, "Unable to parse intent", e);
829 continue;
830 }
831
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700832 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700833 continue;
834 }
835
Sunny Goyalefb7e842018-10-04 15:11:00 -0700836 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700837 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700838 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700839 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700840 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700841 } catch (SQLException ex) {
842 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 }
844 }
845
Adam Cohen091440a2015-03-18 14:16:05 -0700846 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700847 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800848 if (addRankColumn) {
849 // Insert new column for holding rank
850 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
851 }
852
853 // Get a map for folder ID to folder width
854 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
855 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
856 + " GROUP BY container;",
857 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
858
859 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800860 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
861 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800862 new Object[] {c.getLong(1) + 1, c.getLong(0)});
863 }
864
865 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700866 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800867 } catch (SQLException ex) {
868 // Old version remains, which means we wipe old data
869 Log.e(TAG, ex.getMessage(), ex);
870 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800871 }
872 return true;
873 }
874
Sunny Goyal5d85c442015-03-10 13:14:47 -0700875 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700876 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700877 db.execSQL("ALTER TABLE favorites ADD COLUMN "
878 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700879 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100880 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100881 Log.e(TAG, ex.getMessage(), ex);
882 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100883 }
884 return true;
885 }
886
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700887 // Generates a new ID to use for an object in your database. This method should be only
888 // called from the main UI thread. As an exception, we do call it when we call the
889 // constructor from the worker thread; however, this doesn't extend until after the
890 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
891 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700892 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700893 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700894 if (mMaxItemId < 0) {
895 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700896 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700897 mMaxItemId += 1;
898 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700899 }
900
Sunny Goyal55fddc82017-04-06 15:02:52 -0700901 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700902 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700903 }
904
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700905 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700906 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700907 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700908 }
909
Sunny Goyalc5939392018-12-07 11:43:47 -0800910 public void checkId(ContentValues values) {
911 int id = values.getAsInteger(Favorites._ID);
912 mMaxItemId = Math.max(id, mMaxItemId);
913
914 Integer screen = values.getAsInteger(Favorites.SCREEN);
915 Integer container = values.getAsInteger(Favorites.CONTAINER);
916 if (screen != null && container != null
917 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
918 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500919 }
920 }
921
Sunny Goyalefb7e842018-10-04 15:11:00 -0700922 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800923 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700924 }
925
926 // Generates a new ID to use for an workspace screen in your database. This method
927 // should be only called from the main UI thread. As an exception, we do call it when we
928 // call the constructor from the worker thread; however, this doesn't extend until after the
929 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
930 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700931 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700932 if (mMaxScreenId < 0) {
933 throw new RuntimeException("Error: max screen id was not initialized");
934 }
935 mMaxScreenId += 1;
936 return mMaxScreenId;
937 }
938
Sunny Goyalefb7e842018-10-04 15:11:00 -0700939 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800940 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
941 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
942 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700943 }
944
Adam Cohen091440a2015-03-18 14:16:05 -0700945 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700946 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800947 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700948
949 // Ensure that the max ids are initialized
950 mMaxItemId = initializeMaxItemId(db);
951 mMaxScreenId = initializeMaxScreenId(db);
952 return count;
953 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700954 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700955
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800956 /**
957 * @return the max _id in the provided table.
958 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800959 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
960 int max = (int) DatabaseUtils.longForQuery(db,
961 String.format(Locale.ENGLISH, query, args),
962 null);
963 if (max < 0) {
964 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800965 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800966 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800967 }
968
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800969 static class SqlArguments {
970 public final String table;
971 public final String where;
972 public final String[] args;
973
974 SqlArguments(Uri url, String where, String[] args) {
975 if (url.getPathSegments().size() == 1) {
976 this.table = url.getPathSegments().get(0);
977 this.where = where;
978 this.args = args;
979 } else if (url.getPathSegments().size() != 2) {
980 throw new IllegalArgumentException("Invalid URI: " + url);
981 } else if (!TextUtils.isEmpty(where)) {
982 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
983 } else {
984 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700985 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800986 this.args = null;
987 }
988 }
989
990 SqlArguments(Uri url) {
991 if (url.getPathSegments().size() == 1) {
992 table = url.getPathSegments().get(0);
993 where = null;
994 args = null;
995 } else {
996 throw new IllegalArgumentException("Invalid URI: " + url);
997 }
998 }
999 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001000
1001 private static class ChangeListenerWrapper implements Handler.Callback {
1002
1003 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001004 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001005
1006 private LauncherProviderChangeListener mListener;
1007
1008 @Override
1009 public boolean handleMessage(Message msg) {
1010 if (mListener != null) {
1011 switch (msg.what) {
1012 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001013 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001014 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001015 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001016 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001017 break;
1018 }
1019 }
1020 return true;
1021 }
1022 }
Adam Cohen72960972014-01-15 18:13:55 -08001023}