blob: 308d84f77c365c202b3a471ec2d2b33047d092c7 [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
Tracy Zhou7df93d22020-01-27 13:44:06 -080019import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
Tracy Zhouf6018722020-02-06 16:37:16 -080020import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
Sunny Goyal161a2142018-10-29 14:02:20 -070021import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
22import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
Pinyao Tingad5f2402019-12-10 14:56:34 -080023import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
Sunny Goyal161a2142018-10-29 14:02:20 -070024
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070025import android.annotation.TargetApi;
Jon Miranda2bc6b932019-03-07 15:24:46 -080026import android.app.backup.BackupManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070027import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070028import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080029import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070030import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000031import android.content.ContentProviderOperation;
32import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.ContentUris;
34import android.content.ContentValues;
35import android.content.Context;
36import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000037import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070038import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070039import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080042import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070045import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070046import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070047import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070048import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070049import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070050import android.os.Bundle;
Pinyao Tingad5f2402019-12-10 14:56:34 -080051import android.os.Handler;
Sunny Goyal7779d622015-06-11 16:18:39 -070052import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080053import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080054import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080055import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070056import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070057import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080058import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070059import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070060
Sunny Goyal0fe505b2014-08-06 09:55:36 -070061import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
62import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070063import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080064import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070065import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyal337c81f2019-12-10 12:19:13 -080066import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070067import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070068import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070069import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070070import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070071import com.android.launcher3.util.IntArray;
72import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080073import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070074import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070075import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070076
Sunny Goyalc0f03d92019-03-22 14:13:36 -070077import org.xmlpull.v1.XmlPullParser;
78
Sunny Goyal05f30882017-05-03 12:42:18 -070079import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080080import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070081import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080082import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070083import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070084import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070085import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070086import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080087import java.util.Locale;
Tracy Zhouc0000452020-03-17 18:28:38 -070088import java.util.function.Supplier;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070091 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080092 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Sunny Goyal05f30882017-05-03 12:42:18 -070094 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Tingad5f2402019-12-10 14:56:34 -080095 private static final String TOKEN_RESTORE_BACKUP_TABLE = "restore_backup_table";
96 private static final long RESTORE_BACKUP_TABLE_DELAY = 60000;
Sunny Goyal05f30882017-05-03 12:42:18 -070097
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070098 /**
99 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -0800100 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700101 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800102 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800104 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -0700105
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800106 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
Sunny Goyalf076eae2016-01-11 12:25:10 -0800108 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800110 /**
111 * $ adb shell dumpsys activity provider com.android.launcher3
112 */
113 @Override
114 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
115 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
116 if (appState == null || !appState.getModel().isModelLoaded()) {
117 return;
118 }
119 appState.getModel().dumpState("", fd, writer, args);
120 }
121
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800122 @Override
123 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800124 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700125 Log.d(TAG, "Launcher process started");
126 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700127
Sunny Goyalfdbef272017-02-01 12:52:54 -0800128 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800129 // is the first component to get created.
130 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131 return true;
132 }
133
134 @Override
135 public String getType(Uri uri) {
136 SqlArguments args = new SqlArguments(uri, null, null);
137 if (TextUtils.isEmpty(args.where)) {
138 return "vnd.android.cursor.dir/" + args.table;
139 } else {
140 return "vnd.android.cursor.item/" + args.table;
141 }
142 }
143
Sunny Goyalf076eae2016-01-11 12:25:10 -0800144 /**
145 * Overridden in tests
146 */
147 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700148 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700149 mOpenHelper = DatabaseHelper.createDatabaseHelper(
150 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700151
152 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700153 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
154 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700155 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
156 }
157 // Set is pending to false irrespective of the result, so that it doesn't get
158 // executed again.
159 RestoreDbTask.setPending(getContext(), false);
160 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700161 }
162 }
163
Tracy Zhouc0000452020-03-17 18:28:38 -0700164 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
165 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
166 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800167 return false;
168 }
169
Tracy Zhouc0000452020-03-17 18:28:38 -0700170 final DatabaseHelper helper = src.get();
171 mOpenHelper = dst.get();
172 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
173 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
174 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800175 return true;
176 }
177
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178 @Override
179 public Cursor query(Uri uri, String[] projection, String selection,
180 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700181 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182
183 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
184 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
185 qb.setTables(args.table);
186
Romain Guy73b979d2009-06-09 12:57:21 -0700187 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800188 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
189 result.setNotificationUri(getContext().getContentResolver(), uri);
190
191 return result;
192 }
193
Sunny Goyalefb7e842018-10-04 15:11:00 -0700194 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700195 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500196 if (values == null) {
197 throw new RuntimeException("Error: attempting to insert null values");
198 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800199 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700200 throw new RuntimeException("Error: attempting to add item without specifying an id");
201 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800202 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700203 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700204 }
205
Sunny Goyald1064182015-08-13 12:08:30 -0700206 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800207 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700208 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
209 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800210 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700211 }
212 }
213 }
214
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215 @Override
216 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700217 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218 SqlArguments args = new SqlArguments(uri);
219
Sunny Goyald1064182015-08-13 12:08:30 -0700220 // In very limited cases, we support system|signature permission apps to modify the db.
221 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700222 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700223 return null;
224 }
225 }
226
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400228 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700229 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800230 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800231 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232
233 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800234 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 return uri;
236 }
237
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700238 private boolean initializeExternalAdd(ContentValues values) {
239 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700240 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700241 values.put(LauncherSettings.Favorites._ID, id);
242
243 // 2. In the case of an app widget, and if no app widget id is specified, we
244 // attempt allocate and bind the widget.
245 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
246 if (itemType != null &&
247 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
248 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
249
250 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
251 ComponentName cn = ComponentName.unflattenFromString(
252 values.getAsString(Favorites.APPWIDGET_PROVIDER));
253
254 if (cn != null) {
255 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
257 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700258 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
259 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700260 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700261 return false;
262 }
263 } catch (RuntimeException e) {
264 Log.e(TAG, "Failed to initialize external widget", e);
265 return false;
266 }
267 } else {
268 return false;
269 }
270 }
271
Sunny Goyalc5939392018-12-07 11:43:47 -0800272 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700273 }
274
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 @Override
276 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700277 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800278 SqlArguments args = new SqlArguments(uri);
279
280 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700281 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800282 int numValues = values.length;
283 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400284 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700285 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
286 return 0;
287 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800289 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700290 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 }
292
Sunny Goyald1064182015-08-13 12:08:30 -0700293 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 return values.length;
295 }
296
Sunny Goyal161a2142018-10-29 14:02:20 -0700297 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800298 @Override
Yura085c8532014-02-11 15:15:29 +0000299 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
300 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700301 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700302 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800303 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700304
305 final int numOperations = operations.size();
306 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
307 for (int i = 0; i < numOperations; i++) {
308 ContentProviderOperation op = operations.get(i);
309 results[i] = op.apply(this, results, i);
310
311 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
312 results[i].count != null && results[i].count > 0;
313 }
314 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800315 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700316 }
317
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700318 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700319 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700320 return results;
Yura085c8532014-02-11 15:15:29 +0000321 }
322 }
323
324 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800325 public int delete(Uri uri, 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
329 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330
Louis Begina9c21c62016-08-15 15:18:41 -0700331 if (Binder.getCallingPid() != Process.myPid()
332 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700333 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700334 }
335 int count = db.delete(args.table, args.where, args.args);
336 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800337 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700338 reloadLauncherIfExternal();
339 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340 return count;
341 }
342
343 @Override
344 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700345 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800346 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
347
Chris Wren1ada10d2013-09-13 18:01:38 -0400348 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
350 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700351 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 return count;
353 }
354
Sunny Goyal7779d622015-06-11 16:18:39 -0700355 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700356 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700357 if (Binder.getCallingUid() != Process.myUid()) {
358 return null;
359 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700360 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700361
362 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700363 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
364 clearFlagEmptyDbCreated();
365 return null;
366 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700367 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
368 Bundle result = new Bundle();
369 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
370 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
371 return result;
372 }
Sunny Goyald2497482015-09-22 18:24:19 -0700373 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
374 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700375 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
376 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700377 return result;
378 }
379 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
380 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800381 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
382 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700383 return result;
384 }
385 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
386 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800387 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
388 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700389 return result;
390 }
391 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800392 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700393 return null;
394 }
395 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
396 loadDefaultFavoritesIfNecessary();
397 return null;
398 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700399 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
400 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
401 return null;
402 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700403 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
404 Bundle result = new Bundle();
405 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
406 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
407 return result;
408 }
409 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800410 // TODO(pinyaoting): Update the behavior here.
411 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
412 mOpenHelper.mBackupTableExists =
413 tableExists(mOpenHelper.getReadableDatabase(),
414 Favorites.BACKUP_TABLE_NAME);
415 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700416 return null;
417 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700418 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Tingad5f2402019-12-10 14:56:34 -0800419 final Handler handler = MODEL_EXECUTOR.getHandler();
420 handler.removeCallbacksAndMessages(TOKEN_RESTORE_BACKUP_TABLE);
421 handler.postDelayed(() -> RestoreDbTask.restoreIfPossible(
422 getContext(), mOpenHelper, new BackupManager(getContext())),
423 TOKEN_RESTORE_BACKUP_TABLE, RESTORE_BACKUP_TABLE_DELAY);
Pinyao Tingba9c5572019-09-24 14:25:46 -0700424 return null;
425 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800426 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
427 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
428 Bundle result = new Bundle();
429 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Tracy Zhouc0000452020-03-17 18:28:38 -0700430 prepForMigration(
431 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
432 Favorites.TMP_TABLE,
433 () -> mOpenHelper,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700434 () -> DatabaseHelper.createDatabaseHelper(
435 getContext(), true /* forMigration */)));
Tracy Zhouc0000452020-03-17 18:28:38 -0700436 return result;
437 }
438 }
439 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
440 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
441 Bundle result = new Bundle();
442 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
443 prepForMigration(
444 arg /* dbFile */,
445 Favorites.PREVIEW_TABLE_NAME,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700446 () -> DatabaseHelper.createDatabaseHelper(
447 getContext(), arg, true /* forMigration */),
Tracy Zhouc0000452020-03-17 18:28:38 -0700448 () -> mOpenHelper));
Tracy Zhou7df93d22020-01-27 13:44:06 -0800449 return result;
450 }
451 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700452 }
453 return null;
454 }
455
Tracy Zhou7df93d22020-01-27 13:44:06 -0800456 private void onAddOrDeleteOp(SQLiteDatabase db) {
457 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
458 // TODO(pingyaoting): Implement the behavior here.
459 } else {
460 mOpenHelper.onAddOrDeleteOp(db);
461 }
462 }
463
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700464 /**
465 * Deletes any empty folder from the DB.
466 * @return Ids of deleted folders.
467 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700468 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700469 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700470 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700471 // Select folders whose id do not match any container value.
472 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
473 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
474 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
475 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800477
478 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
479 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700480 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700481 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700482 LauncherSettings.Favorites._ID, folderIds), null);
483 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700484 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800485 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700486 } catch (SQLException ex) {
487 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800488 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700489 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700490 }
491
Adam Cohen091440a2015-03-18 14:16:05 -0700492 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800493 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494 }
495
Sunny Goyald2497482015-09-22 18:24:19 -0700496 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700497 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700498 }
499
Sunny Goyal42de82f2014-09-26 22:09:29 -0700500 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700501 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700502 * 1) From the app restrictions
503 * 2) From a package provided by play store
504 * 3) From a partner configuration APK, already in the system image
505 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700506 */
Sunny Goyald2497482015-09-22 18:24:19 -0700507 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700508 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700509
Winson Chungc763c4e2013-07-19 13:49:06 -0700510 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500511 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200512
Sunny Goyal55fddc82017-04-06 15:02:52 -0700513 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700514 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700515 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700516 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700517 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700518 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700519 final Partner partner = Partner.get(getContext().getPackageManager());
520 if (partner != null && partner.hasDefaultLayout()) {
521 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700522 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700523 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700524 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700525 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700526 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700527 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700528 }
529 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700530
Sunny Goyal9d219682014-10-23 14:21:02 -0700531 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700532 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700533 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700534 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800535
536 // There might be some partially restored DB items, due to buggy restore logic in
537 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800538 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700539 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700540 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
541 && usingExternallyProvidedLayout) {
542 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800543 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700544 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700546 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700547 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700548 }
549 }
550
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700551 /**
552 * Creates workspace loader from an XML resource listed in the app restrictions.
553 *
554 * @return the loader if the restrictions are set and the resource exists; null otherwise.
555 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700556 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700557 Context ctx = getContext();
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700558 String authority = Settings.Secure.getString(ctx.getContentResolver(),
559 "launcher3.layout.provider");
560 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700561 return null;
562 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700563
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700564 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
565 if (pi == null) {
566 Log.e(TAG, "No provider found for authority " + authority);
567 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700568 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800569 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700570 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
571 // Read the full xml so that we fail early in case of any IO error.
572 String layout = new String(IOUtils.toByteArray(in));
573 XmlPullParser parser = Xml.newPullParser();
574 parser.setInput(new StringReader(layout));
575
576 Log.d(TAG, "Loading layout from " + authority);
577 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
578 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
579 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
580 } catch (Exception e) {
581 Log.e(TAG, "Error getting layout stream from: " + authority , e);
582 return null;
583 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700584 }
585
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800586 public static Uri getLayoutUri(String authority, Context ctx) {
587 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
588 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
589 .appendQueryParameter("version", "1")
590 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
591 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
592 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
593 .build();
594 }
595
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700596 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700597 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
598 int defaultLayout = idp.defaultLayoutId;
599
Sunny Goyal337c81f2019-12-10 12:19:13 -0800600 if (getContext().getSystemService(UserManager.class).isDemoUser()
601 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700602 defaultLayout = idp.demoModeLayoutId;
603 }
604
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700605 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700606 mOpenHelper, getContext().getResources(), defaultLayout);
607 }
608
Sunny Goyald3849d12015-10-29 10:28:32 -0700609 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800610 * The class is subclassed in tests to create an in-memory db.
611 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800612 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
613 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700615 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700616 private int mMaxItemId = -1;
617 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700618 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800619
Tracy Zhoued5f3082020-04-20 01:13:26 -0700620 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
621 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700622 }
623
Tracy Zhoued5f3082020-04-20 01:13:26 -0700624 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
625 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700626 if (dbName == null) {
627 dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
628 context).dbFile : LauncherFiles.LAUNCHER_DB;
629 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700630 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700631 // Table creation sometimes fails silently, which leads to a crash loop.
632 // This way, we will try to create a table every time after crash, so the device
633 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700634 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700635 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
636 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700637 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700638 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800639 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700640 databaseHelper.mBackupTableExists = tableExists(
641 databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800642 }
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643
Tracy Zhouc0000452020-03-17 18:28:38 -0700644 databaseHelper.initIds();
645 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700646 }
647
648 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700649 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700650 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700651 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800652 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700653 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700654 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700655 }
656
657 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700658 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
659 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700660 if (mMaxItemId == -1) {
661 mMaxItemId = initializeMaxItemId(getWritableDatabase());
662 }
663 if (mMaxScreenId == -1) {
664 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700665 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800666 }
667
668 @Override
669 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800670 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700671
Adam Cohendcd297f2013-06-18 13:13:40 -0700672 mMaxItemId = 1;
673 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700674
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700675 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800676
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800677 // Fresh and clean launcher DB.
678 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700679 if (!mForMigration) {
680 onEmptyDbCreated();
681 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800682 }
683
Sunny Goyal161a2142018-10-29 14:02:20 -0700684 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800685 if (!MULTI_DB_GRID_MIRATION_ALGO.get() && mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700686 dropTable(db, Favorites.BACKUP_TABLE_NAME);
687 mBackupTableExists = false;
688 }
689 }
690
Sunny Goyalf076eae2016-01-11 12:25:10 -0800691 /**
692 * Overriden in tests.
693 */
694 protected void onEmptyDbCreated() {
695 // Set the flag for empty DB
696 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800697 }
698
Jon Miranda2bc6b932019-03-07 15:24:46 -0800699 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800700 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800701 }
702
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700703 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800704 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800705 }
706
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700707 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700708 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700709 }
710
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800711 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700712 public void onOpen(SQLiteDatabase db) {
713 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700714
715 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
716 if (!schemaFile.exists()) {
717 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700718 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800719 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700720 }
721
722 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700723 * One-time data updated before support of onDowngrade was added. This update is backwards
724 * compatible and can safely be run multiple times.
725 * Note: No new logic should be added here after release, as the new logic might not get
726 * executed on an existing device.
727 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700728 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700729 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
730 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800731 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700732 for (UserHandle user : um.getUserProfiles()) {
733 long serial = um.getSerialNumberForUser(user);
734 String sql = "update favorites set intent = replace(intent, "
735 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
736 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700737 }
738 }
739
740 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700742 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 switch (oldVersion) {
744 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800745 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800746 case 12:
747 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700749 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800750 // Insert new column for holding widget provider name
751 db.execSQL("ALTER TABLE favorites " +
752 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700753 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 } catch (SQLException ex) {
755 Log.e(TAG, ex.getMessage(), ex);
756 // Old version remains, which means we wipe old data
757 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800758 }
759 }
760 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800761 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800762 // Old version remains, which means we wipe old data
763 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 }
765 }
766 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700767 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800768 // Old version remains, which means we wipe old data
769 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800770 }
771 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800772 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700773 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800774 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800775 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800776 case 18:
777 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800778 case 19: {
779 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800780 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800781 // Old version remains, which means we wipe old data
782 break;
783 }
784 }
785 case 20:
786 if (!updateFolderItemsRank(db, true)) {
787 break;
788 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800789 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800790 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800791 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700792 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
793 // Old version remains, which means we wipe old data
794 break;
795 }
796 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700797 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700798 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700799 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000800 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700801 case 25:
802 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700803 case 26:
804 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700805 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800806 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700807 break;
808 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800809 case 27: {
810 // Update the favorites table so that the screen ids are ordered based on
811 // workspace page rank.
812 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
813 BaseColumns._ID, null, null, "screenRank");
814 int[] original = finalScreens.toArray();
815 Arrays.sort(original);
816 String updatemap = "";
817 for (int i = 0; i < original.length; i++) {
818 if (finalScreens.get(i) != original[i]) {
819 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
820 Favorites.SCREEN, finalScreens.get(i), original[i]);
821 }
822 }
823 if (!TextUtils.isEmpty(updatemap)) {
824 String query = String.format(Locale.ENGLISH,
825 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
826 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
827 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
828 db.execSQL(query);
829 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700830 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800831 }
832 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800833 // DB Upgraded successfully
834 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400835 }
836
Sunny Goyala2cc6242015-01-14 14:23:02 -0800837 // DB was not upgraded
838 Log.w(TAG, "Destroying all old data.");
839 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800840 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800841
Adam Cohen9b1d0622014-05-21 19:01:57 -0700842 @Override
843 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700844 try {
845 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
846 .onDowngrade(db, oldVersion, newVersion);
847 } catch (Exception e) {
848 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
849 ". Wiping databse.", e);
850 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700851 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700852 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700853
Sunny Goyal42de82f2014-09-26 22:09:29 -0700854 /**
855 * Clears all the data for a fresh start.
856 */
857 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700858 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700859 dropTable(db, Favorites.TABLE_NAME);
860 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800861 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700862 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800863 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700864 }
865
Sunny Goyald2f38192015-02-25 10:46:34 -0800866 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700867 * Removes widgets which are registered to the Launcher's host, but are not present
868 * in our model.
869 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700870 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700871 public void removeGhostWidgets(SQLiteDatabase db) {
872 // Get all existing widget ids.
873 final AppWidgetHost host = newLauncherWidgetHost();
874 final int[] allWidgets;
875 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700876 // Although the method was defined in O, it has existed since the beginning of time,
877 // so it might work on older platforms as well.
878 allWidgets = host.getAppWidgetIds();
879 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700880 Log.e(TAG, "getAppWidgetIds not supported", e);
881 return;
882 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800883 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
884 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
885 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700886 for (int widgetId : allWidgets) {
887 if (!validWidgets.contains(widgetId)) {
888 try {
889 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
890 host.deleteAppWidgetId(widgetId);
891 } catch (RuntimeException e) {
892 // Ignore
893 }
894 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700895 }
896 }
897
898 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700899 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
900 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
901 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700902 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700903 try (SQLiteTransaction t = new SQLiteTransaction(db);
904 // Only consider the primary user as other users can't have a shortcut.
905 Cursor c = db.query(Favorites.TABLE_NAME,
906 new String[] { Favorites._ID, Favorites.INTENT},
907 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
908 " AND profileId=" + getDefaultUserSerial(),
909 null, null, null, null);
910 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
911 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
912 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700913 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
914 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
915
916 while (c.moveToNext()) {
917 String intentDescription = c.getString(intentIndex);
918 Intent intent;
919 try {
920 intent = Intent.parseUri(intentDescription, 0);
921 } catch (URISyntaxException e) {
922 Log.e(TAG, "Unable to parse intent", e);
923 continue;
924 }
925
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700926 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700927 continue;
928 }
929
Sunny Goyalefb7e842018-10-04 15:11:00 -0700930 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700931 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700932 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700933 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700934 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700935 } catch (SQLException ex) {
936 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700937 }
938 }
939
Adam Cohen091440a2015-03-18 14:16:05 -0700940 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700941 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800942 if (addRankColumn) {
943 // Insert new column for holding rank
944 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
945 }
946
947 // Get a map for folder ID to folder width
948 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
949 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
950 + " GROUP BY container;",
951 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
952
953 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800954 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
955 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800956 new Object[] {c.getLong(1) + 1, c.getLong(0)});
957 }
958
959 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700960 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800961 } catch (SQLException ex) {
962 // Old version remains, which means we wipe old data
963 Log.e(TAG, ex.getMessage(), ex);
964 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800965 }
966 return true;
967 }
968
Sunny Goyal5d85c442015-03-10 13:14:47 -0700969 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700970 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700971 db.execSQL("ALTER TABLE favorites ADD COLUMN "
972 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700973 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100974 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100975 Log.e(TAG, ex.getMessage(), ex);
976 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100977 }
978 return true;
979 }
980
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700981 // Generates a new ID to use for an object in your database. This method should be only
982 // called from the main UI thread. As an exception, we do call it when we call the
983 // constructor from the worker thread; however, this doesn't extend until after the
984 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
985 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700986 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700987 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700988 if (mMaxItemId < 0) {
989 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700990 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700991 mMaxItemId += 1;
992 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700993 }
994
Sunny Goyal55fddc82017-04-06 15:02:52 -0700995 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700996 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700997 }
998
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700999 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001000 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001001 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001002 }
1003
Sunny Goyalc5939392018-12-07 11:43:47 -08001004 public void checkId(ContentValues values) {
1005 int id = values.getAsInteger(Favorites._ID);
1006 mMaxItemId = Math.max(id, mMaxItemId);
1007
1008 Integer screen = values.getAsInteger(Favorites.SCREEN);
1009 Integer container = values.getAsInteger(Favorites.CONTAINER);
1010 if (screen != null && container != null
1011 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1012 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001013 }
1014 }
1015
Sunny Goyalefb7e842018-10-04 15:11:00 -07001016 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001017 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001018 }
1019
1020 // Generates a new ID to use for an workspace screen in your database. This method
1021 // should be only called from the main UI thread. As an exception, we do call it when we
1022 // call the constructor from the worker thread; however, this doesn't extend until after the
1023 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1024 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001025 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001026 if (mMaxScreenId < 0) {
1027 throw new RuntimeException("Error: max screen id was not initialized");
1028 }
1029 mMaxScreenId += 1;
1030 return mMaxScreenId;
1031 }
1032
Sunny Goyalefb7e842018-10-04 15:11:00 -07001033 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001034 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
1035 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1036 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001037 }
1038
Adam Cohen091440a2015-03-18 14:16:05 -07001039 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001040 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001041 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001042
1043 // Ensure that the max ids are initialized
1044 mMaxItemId = initializeMaxItemId(db);
1045 mMaxScreenId = initializeMaxScreenId(db);
1046 return count;
1047 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001048 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001049
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001050 /**
1051 * @return the max _id in the provided table.
1052 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001053 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
1054 int max = (int) DatabaseUtils.longForQuery(db,
1055 String.format(Locale.ENGLISH, query, args),
1056 null);
1057 if (max < 0) {
1058 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001059 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001060 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001061 }
1062
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001063 static class SqlArguments {
1064 public final String table;
1065 public final String where;
1066 public final String[] args;
1067
1068 SqlArguments(Uri url, String where, String[] args) {
1069 if (url.getPathSegments().size() == 1) {
1070 this.table = url.getPathSegments().get(0);
1071 this.where = where;
1072 this.args = args;
1073 } else if (url.getPathSegments().size() != 2) {
1074 throw new IllegalArgumentException("Invalid URI: " + url);
1075 } else if (!TextUtils.isEmpty(where)) {
1076 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1077 } else {
1078 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001079 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001080 this.args = null;
1081 }
1082 }
1083
1084 SqlArguments(Uri url) {
1085 if (url.getPathSegments().size() == 1) {
1086 table = url.getPathSegments().get(0);
1087 where = null;
1088 args = null;
1089 } else {
1090 throw new IllegalArgumentException("Invalid URI: " + url);
1091 }
1092 }
1093 }
Adam Cohen72960972014-01-15 18:13:55 -08001094}