blob: 49f20c6272d8e3876b26e5459656f1ed02da4b81 [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 Zhouf6018722020-02-06 16:37:16 -080019import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
Sunny Goyal161a2142018-10-29 14:02:20 -070020import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
21import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
22
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070023import android.annotation.TargetApi;
Jon Miranda2bc6b932019-03-07 15:24:46 -080024import android.app.backup.BackupManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070025import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070026import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000029import android.content.ContentProviderOperation;
30import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070031import android.content.ContentUris;
32import android.content.ContentValues;
33import android.content.Context;
34import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000035import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070036import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070037import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080040import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070042import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070044import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070045import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070047import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070049import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080050import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080051import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080052import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070053import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070054import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070056import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070057
Sunny Goyal0fe505b2014-08-06 09:55:36 -070058import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
59import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080061import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070062import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyal337c81f2019-12-10 12:19:13 -080063import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070064import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070065import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070066import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070067import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070068import com.android.launcher3.util.IntArray;
69import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080070import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070071import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070072import com.android.launcher3.util.Thunk;
Yogisha Dixit741fae92021-02-22 14:03:44 +000073import com.android.launcher3.widget.LauncherAppWidgetHost;
Michael Jurka8b805b12012-04-18 14:23:14 -070074
Sunny Goyalc0f03d92019-03-22 14:13:36 -070075import org.xmlpull.v1.XmlPullParser;
76
Sunny Goyal05f30882017-05-03 12:42:18 -070077import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080078import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070079import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080080import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070081import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070082import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070083import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070084import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080085import java.util.Locale;
Pinyao Ting0807c942020-04-28 13:58:45 -070086import java.util.concurrent.TimeUnit;
Tracy Zhouc0000452020-03-17 18:28:38 -070087import java.util.function.Supplier;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070090 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080091 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Sunny Goyal05f30882017-05-03 12:42:18 -070093 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Ting0807c942020-04-28 13:58:45 -070094 private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
Sunny Goyal05f30882017-05-03 12:42:18 -070095
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070096 /**
97 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080098 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070099 */
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100100 public static final int SCHEMA_VERSION = 29;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800102 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Pinyao Ting96186af2020-07-20 11:03:39 -0700103 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700104
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800105 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106
Sunny Goyalf076eae2016-01-11 12:25:10 -0800107 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700108 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Pinyao Ting0807c942020-04-28 13:58:45 -0700110 private long mLastRestoreTimestamp = 0L;
111
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800112 /**
113 * $ adb shell dumpsys activity provider com.android.launcher3
114 */
115 @Override
116 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
117 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
118 if (appState == null || !appState.getModel().isModelLoaded()) {
119 return;
120 }
121 appState.getModel().dumpState("", fd, writer, args);
122 }
123
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800124 @Override
125 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800126 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700127 Log.d(TAG, "Launcher process started");
128 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700129
Sunny Goyalfdbef272017-02-01 12:52:54 -0800130 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800131 // is the first component to get created.
132 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 return true;
134 }
135
136 @Override
137 public String getType(Uri uri) {
138 SqlArguments args = new SqlArguments(uri, null, null);
139 if (TextUtils.isEmpty(args.where)) {
140 return "vnd.android.cursor.dir/" + args.table;
141 } else {
142 return "vnd.android.cursor.item/" + args.table;
143 }
144 }
145
Sunny Goyalf076eae2016-01-11 12:25:10 -0800146 /**
147 * Overridden in tests
148 */
149 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700150 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700151 mOpenHelper = DatabaseHelper.createDatabaseHelper(
152 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700153
Sunny Goyal68031ca2021-08-02 12:23:44 -0700154 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700155 }
156 }
157
Tracy Zhouc0000452020-03-17 18:28:38 -0700158 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
159 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
160 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800161 return false;
162 }
163
Tracy Zhouc0000452020-03-17 18:28:38 -0700164 final DatabaseHelper helper = src.get();
165 mOpenHelper = dst.get();
166 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
167 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
168 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800169 return true;
170 }
171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 @Override
173 public Cursor query(Uri uri, String[] projection, String selection,
174 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700175 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
178 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
179 qb.setTables(args.table);
180
Romain Guy73b979d2009-06-09 12:57:21 -0700181 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700183 final Bundle extra = new Bundle();
184 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
185 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186 result.setNotificationUri(getContext().getContentResolver(), uri);
187
188 return result;
189 }
190
Sunny Goyalefb7e842018-10-04 15:11:00 -0700191 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700192 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500193 if (values == null) {
194 throw new RuntimeException("Error: attempting to insert null values");
195 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800196 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700197 throw new RuntimeException("Error: attempting to add item without specifying an id");
198 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800199 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700200 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700201 }
202
Sunny Goyald1064182015-08-13 12:08:30 -0700203 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800204 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700205 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
206 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800207 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700208 }
209 }
210 }
211
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 @Override
213 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700214 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215 SqlArguments args = new SqlArguments(uri);
216
Sunny Goyald1064182015-08-13 12:08:30 -0700217 // In very limited cases, we support system|signature permission apps to modify the db.
218 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700219 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700220 return null;
221 }
222 }
223
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400225 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700226 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800227 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800228 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229
230 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800231 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232 return uri;
233 }
234
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700235 private boolean initializeExternalAdd(ContentValues values) {
236 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700237 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700238 values.put(LauncherSettings.Favorites._ID, id);
239
240 // 2. In the case of an app widget, and if no app widget id is specified, we
241 // attempt allocate and bind the widget.
242 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
243 if (itemType != null &&
244 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
245 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
246
247 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
248 ComponentName cn = ComponentName.unflattenFromString(
249 values.getAsString(Favorites.APPWIDGET_PROVIDER));
250
251 if (cn != null) {
252 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700253 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
254 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700255 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
256 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700257 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700258 return false;
259 }
260 } catch (RuntimeException e) {
261 Log.e(TAG, "Failed to initialize external widget", e);
262 return false;
263 }
264 } else {
265 return false;
266 }
267 }
268
Sunny Goyalc5939392018-12-07 11:43:47 -0800269 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700270 }
271
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 @Override
273 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700274 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 SqlArguments args = new SqlArguments(uri);
276
277 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700278 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800279 int numValues = values.length;
280 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400281 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700282 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
283 return 0;
284 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800285 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800286 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700287 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 }
289
Sunny Goyald1064182015-08-13 12:08:30 -0700290 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 return values.length;
292 }
293
Sunny Goyal161a2142018-10-29 14:02:20 -0700294 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 @Override
Yura085c8532014-02-11 15:15:29 +0000296 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
297 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700298 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700299 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800300 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700301
302 final int numOperations = operations.size();
303 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
304 for (int i = 0; i < numOperations; i++) {
305 ContentProviderOperation op = operations.get(i);
306 results[i] = op.apply(this, results, i);
307
308 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
309 results[i].count != null && results[i].count > 0;
310 }
311 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800312 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700313 }
314
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700315 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700316 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700317 return results;
Yura085c8532014-02-11 15:15:29 +0000318 }
319 }
320
321 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
325
326 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327
Louis Begina9c21c62016-08-15 15:18:41 -0700328 if (Binder.getCallingPid() != Process.myPid()
329 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700330 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700331 }
332 int count = db.delete(args.table, args.where, args.args);
333 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800334 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700335 reloadLauncherIfExternal();
336 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337 return count;
338 }
339
340 @Override
341 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700342 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
344
Chris Wren1ada10d2013-09-13 18:01:38 -0400345 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800346 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
347 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700348 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 return count;
350 }
351
Sunny Goyal7779d622015-06-11 16:18:39 -0700352 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700353 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700354 if (Binder.getCallingUid() != Process.myUid()) {
355 return null;
356 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700357 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700358
359 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700360 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
361 clearFlagEmptyDbCreated();
362 return null;
363 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700364 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
365 Bundle result = new Bundle();
366 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Pinyao Ting96186af2020-07-20 11:03:39 -0700367 Utilities.getPrefs(getContext()).getBoolean(
368 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700369 return result;
370 }
Sunny Goyald2497482015-09-22 18:24:19 -0700371 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
372 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700373 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
374 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700375 return result;
376 }
377 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
378 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800379 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
380 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700381 return result;
382 }
383 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
384 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800385 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
386 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700387 return result;
388 }
389 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800390 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700391 return null;
392 }
393 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
394 loadDefaultFavoritesIfNecessary();
395 return null;
396 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700397 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
398 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
399 return null;
400 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700401 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
402 Bundle result = new Bundle();
403 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
404 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
405 return result;
406 }
407 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700408 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
409 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700410 return null;
411 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700412 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
413 mOpenHelper.mHotseatRestoreTableExists = tableExists(
414 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
415 return null;
416 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700417 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700418 final long ts = System.currentTimeMillis();
419 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
420 mLastRestoreTimestamp = ts;
421 RestoreDbTask.restoreIfPossible(
422 getContext(), mOpenHelper, new BackupManager(getContext()));
423 }
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: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700427 Bundle result = new Bundle();
428 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
429 prepForMigration(
430 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
431 Favorites.TMP_TABLE,
432 () -> mOpenHelper,
433 () -> DatabaseHelper.createDatabaseHelper(
434 getContext(), true /* forMigration */)));
435 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700436 }
437 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700438 Bundle result = new Bundle();
439 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
440 prepForMigration(
441 arg /* dbFile */,
442 Favorites.PREVIEW_TABLE_NAME,
443 () -> DatabaseHelper.createDatabaseHelper(
444 getContext(), arg, true /* forMigration */),
445 () -> mOpenHelper));
446 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700447 }
448 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
449 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
450 final DatabaseHelper helper = mOpenHelper;
451 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
452 mProviderAuthority = null;
453 } else {
454 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
455 }
456 mOpenHelper = DatabaseHelper.createDatabaseHelper(
457 getContext(), arg, false /* forMigration */);
458 helper.close();
459 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
460 if (app == null) return null;
461 app.getModel().forceReload();
462 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800463 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700464 }
465 return null;
466 }
467
Tracy Zhou7df93d22020-01-27 13:44:06 -0800468 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700469 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800470 }
471
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700472 /**
473 * Deletes any empty folder from the DB.
474 * @return Ids of deleted folders.
475 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700476 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700477 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700478 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700479 // Select folders whose id do not match any container value.
480 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
481 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
482 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
483 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700484 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800485
486 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
487 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700488 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700489 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700490 LauncherSettings.Favorites._ID, folderIds), null);
491 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700492 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800493 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700494 } catch (SQLException ex) {
495 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800496 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700497 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700498 }
499
Adam Cohen091440a2015-03-18 14:16:05 -0700500 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800501 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800502 }
503
Sunny Goyald2497482015-09-22 18:24:19 -0700504 private void clearFlagEmptyDbCreated() {
Pinyao Ting96186af2020-07-20 11:03:39 -0700505 Utilities.getPrefs(getContext()).edit()
506 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700507 }
508
Sunny Goyal42de82f2014-09-26 22:09:29 -0700509 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700510 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700511 * 1) From the app restrictions
512 * 2) From a package provided by play store
513 * 3) From a partner configuration APK, already in the system image
514 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700515 */
Sunny Goyald2497482015-09-22 18:24:19 -0700516 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700517 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700518
Pinyao Ting96186af2020-07-20 11:03:39 -0700519 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500520 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200521
Sunny Goyal55fddc82017-04-06 15:02:52 -0700522 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700523 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700524 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700525 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700527 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700528 final Partner partner = Partner.get(getContext().getPackageManager());
529 if (partner != null && partner.hasDefaultLayout()) {
530 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700531 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700532 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700533 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700535 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700536 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700537 }
538 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700539
Sunny Goyal9d219682014-10-23 14:21:02 -0700540 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700541 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700542 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700543 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800544
545 // There might be some partially restored DB items, due to buggy restore logic in
546 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800547 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700548 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700549 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
550 && usingExternallyProvidedLayout) {
551 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800552 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700553 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700554 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700555 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700556 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700557 }
558 }
559
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700560 /**
561 * Creates workspace loader from an XML resource listed in the app restrictions.
562 *
563 * @return the loader if the restrictions are set and the resource exists; null otherwise.
564 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700565 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700566 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700567 final String authority;
568 if (!TextUtils.isEmpty(mProviderAuthority)) {
569 authority = mProviderAuthority;
570 } else {
571 authority = Settings.Secure.getString(ctx.getContentResolver(),
572 "launcher3.layout.provider");
573 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700574 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700575 return null;
576 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700577
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700578 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
579 if (pi == null) {
580 Log.e(TAG, "No provider found for authority " + authority);
581 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700582 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800583 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700584 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
585 // Read the full xml so that we fail early in case of any IO error.
586 String layout = new String(IOUtils.toByteArray(in));
587 XmlPullParser parser = Xml.newPullParser();
588 parser.setInput(new StringReader(layout));
589
590 Log.d(TAG, "Loading layout from " + authority);
591 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
592 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
593 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
594 } catch (Exception e) {
595 Log.e(TAG, "Error getting layout stream from: " + authority , e);
596 return null;
597 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700598 }
599
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800600 public static Uri getLayoutUri(String authority, Context ctx) {
601 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
602 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
603 .appendQueryParameter("version", "1")
604 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
605 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700606 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800607 .build();
608 }
609
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700610 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700611 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
612 int defaultLayout = idp.defaultLayoutId;
613
Sunny Goyal337c81f2019-12-10 12:19:13 -0800614 if (getContext().getSystemService(UserManager.class).isDemoUser()
615 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700616 defaultLayout = idp.demoModeLayoutId;
617 }
618
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700619 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700620 mOpenHelper, getContext().getResources(), defaultLayout);
621 }
622
Sunny Goyald3849d12015-10-29 10:28:32 -0700623 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800624 * The class is subclassed in tests to create an in-memory db.
625 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800626 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
627 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700629 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700630 private int mMaxItemId = -1;
631 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700632 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700633 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634
Tracy Zhoued5f3082020-04-20 01:13:26 -0700635 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
636 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700637 }
638
Tracy Zhoued5f3082020-04-20 01:13:26 -0700639 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
640 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700641 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700642 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700643 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700644 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700645 // Table creation sometimes fails silently, which leads to a crash loop.
646 // This way, we will try to create a table every time after crash, so the device
647 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700648 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700649 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
650 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700651 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700652 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700653 databaseHelper.mHotseatRestoreTableExists = tableExists(
654 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700655
Tracy Zhouc0000452020-03-17 18:28:38 -0700656 databaseHelper.initIds();
657 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700658 }
659
660 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700661 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700662 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700663 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800664 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700665 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700666 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700667 }
668
669 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700670 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
671 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700672 if (mMaxItemId == -1) {
673 mMaxItemId = initializeMaxItemId(getWritableDatabase());
674 }
675 if (mMaxScreenId == -1) {
676 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700677 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678 }
679
680 @Override
681 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800682 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700683
Adam Cohendcd297f2013-06-18 13:13:40 -0700684 mMaxItemId = 1;
685 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700686
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700687 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800688
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800689 // Fresh and clean launcher DB.
690 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700691 if (!mForMigration) {
692 onEmptyDbCreated();
693 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800694 }
695
Sunny Goyal161a2142018-10-29 14:02:20 -0700696 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700697 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700698 dropTable(db, Favorites.BACKUP_TABLE_NAME);
699 mBackupTableExists = false;
700 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700701 if (mHotseatRestoreTableExists) {
702 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
703 mHotseatRestoreTableExists = false;
704 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700705 }
706
Sunny Goyalf076eae2016-01-11 12:25:10 -0800707 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700708 * Re-composite given key in respect to database. If the current db is
709 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
710 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
711 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
712 */
713 String getKey(final String key) {
714 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
715 return key;
716 }
717 return key + "@" + getDatabaseName();
718 }
719
720 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800721 * Overriden in tests.
722 */
723 protected void onEmptyDbCreated() {
724 // Set the flag for empty DB
Pinyao Ting96186af2020-07-20 11:03:39 -0700725 Utilities.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
726 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800727 }
728
Jon Miranda2bc6b932019-03-07 15:24:46 -0800729 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800730 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800731 }
732
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700733 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800734 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800735 }
736
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700737 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700738 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700739 }
740
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700742 public void onOpen(SQLiteDatabase db) {
743 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700744
745 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
746 if (!schemaFile.exists()) {
747 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700748 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800749 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700750 }
751
752 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700753 * One-time data updated before support of onDowngrade was added. This update is backwards
754 * compatible and can safely be run multiple times.
755 * Note: No new logic should be added here after release, as the new logic might not get
756 * executed on an existing device.
757 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700758 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700759 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
760 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800761 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700762 for (UserHandle user : um.getUserProfiles()) {
763 long serial = um.getSerialNumberForUser(user);
764 String sql = "update favorites set intent = replace(intent, "
765 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
766 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700767 }
768 }
769
770 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700772 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800773 switch (oldVersion) {
774 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800775 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800776 case 12:
777 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800778 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700779 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800780 // Insert new column for holding widget provider name
781 db.execSQL("ALTER TABLE favorites " +
782 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700783 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800784 } catch (SQLException ex) {
785 Log.e(TAG, ex.getMessage(), ex);
786 // Old version remains, which means we wipe old data
787 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800788 }
789 }
790 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800791 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800792 // Old version remains, which means we wipe old data
793 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 }
795 }
796 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700797 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800798 // Old version remains, which means we wipe old data
799 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800800 }
801 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800802 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700803 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800804 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800805 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800806 case 18:
807 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 case 19: {
809 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800810 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800811 // Old version remains, which means we wipe old data
812 break;
813 }
814 }
815 case 20:
816 if (!updateFolderItemsRank(db, true)) {
817 break;
818 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800819 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800820 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800821 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700822 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
823 // Old version remains, which means we wipe old data
824 break;
825 }
826 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700827 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700828 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700829 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000830 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700831 case 25:
832 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700833 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700834 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800835 case 27: {
836 // Update the favorites table so that the screen ids are ordered based on
837 // workspace page rank.
838 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
839 BaseColumns._ID, null, null, "screenRank");
840 int[] original = finalScreens.toArray();
841 Arrays.sort(original);
842 String updatemap = "";
843 for (int i = 0; i < original.length; i++) {
844 if (finalScreens.get(i) != original[i]) {
845 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
846 Favorites.SCREEN, finalScreens.get(i), original[i]);
847 }
848 }
849 if (!TextUtils.isEmpty(updatemap)) {
850 String query = String.format(Locale.ENGLISH,
851 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
852 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
853 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
854 db.execSQL(query);
855 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700856 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800857 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100858 case 28: {
859 boolean columnAdded = addIntegerColumn(
860 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
861 if (!columnAdded) {
862 // Old version remains, which means we wipe old data
863 break;
864 }
865 }
866 case 29: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800867 // DB Upgraded successfully
868 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100869 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400870 }
871
Sunny Goyala2cc6242015-01-14 14:23:02 -0800872 // DB was not upgraded
873 Log.w(TAG, "Destroying all old data.");
874 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800875 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800876
Adam Cohen9b1d0622014-05-21 19:01:57 -0700877 @Override
878 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700879 try {
880 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
881 .onDowngrade(db, oldVersion, newVersion);
882 } catch (Exception e) {
883 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
884 ". Wiping databse.", e);
885 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700886 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700887 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700888
Sunny Goyal42de82f2014-09-26 22:09:29 -0700889 /**
890 * Clears all the data for a fresh start.
891 */
892 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700893 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700894 dropTable(db, Favorites.TABLE_NAME);
895 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800896 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700897 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800898 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700899 }
900
Sunny Goyald2f38192015-02-25 10:46:34 -0800901 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700902 * Removes widgets which are registered to the Launcher's host, but are not present
903 * in our model.
904 */
905 public void removeGhostWidgets(SQLiteDatabase db) {
906 // Get all existing widget ids.
907 final AppWidgetHost host = newLauncherWidgetHost();
908 final int[] allWidgets;
909 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700910 // Although the method was defined in O, it has existed since the beginning of time,
911 // so it might work on older platforms as well.
912 allWidgets = host.getAppWidgetIds();
913 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700914 Log.e(TAG, "getAppWidgetIds not supported", e);
915 return;
916 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800917 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
918 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
919 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700920 for (int widgetId : allWidgets) {
921 if (!validWidgets.contains(widgetId)) {
922 try {
923 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
924 host.deleteAppWidgetId(widgetId);
925 } catch (RuntimeException e) {
926 // Ignore
927 }
928 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700929 }
930 }
931
932 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700933 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
934 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
935 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700936 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700937 try (SQLiteTransaction t = new SQLiteTransaction(db);
938 // Only consider the primary user as other users can't have a shortcut.
939 Cursor c = db.query(Favorites.TABLE_NAME,
940 new String[] { Favorites._ID, Favorites.INTENT},
941 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
942 " AND profileId=" + getDefaultUserSerial(),
943 null, null, null, null);
944 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
945 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
946 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700947 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
948 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
949
950 while (c.moveToNext()) {
951 String intentDescription = c.getString(intentIndex);
952 Intent intent;
953 try {
954 intent = Intent.parseUri(intentDescription, 0);
955 } catch (URISyntaxException e) {
956 Log.e(TAG, "Unable to parse intent", e);
957 continue;
958 }
959
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700960 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700961 continue;
962 }
963
Sunny Goyalefb7e842018-10-04 15:11:00 -0700964 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700965 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700966 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700967 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700968 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700969 } catch (SQLException ex) {
970 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700971 }
972 }
973
Adam Cohen091440a2015-03-18 14:16:05 -0700974 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700975 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800976 if (addRankColumn) {
977 // Insert new column for holding rank
978 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
979 }
980
981 // Get a map for folder ID to folder width
982 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
983 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
984 + " GROUP BY container;",
985 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
986
987 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800988 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
989 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800990 new Object[] {c.getLong(1) + 1, c.getLong(0)});
991 }
992
993 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700994 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800995 } catch (SQLException ex) {
996 // Old version remains, which means we wipe old data
997 Log.e(TAG, ex.getMessage(), ex);
998 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800999 }
1000 return true;
1001 }
1002
Sunny Goyal5d85c442015-03-10 13:14:47 -07001003 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001004 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001005 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1006 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001007 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001008 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001009 Log.e(TAG, ex.getMessage(), ex);
1010 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001011 }
1012 return true;
1013 }
1014
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001015 // Generates a new ID to use for an object in your database. This method should be only
1016 // called from the main UI thread. As an exception, we do call it when we call the
1017 // constructor from the worker thread; however, this doesn't extend until after the
1018 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1019 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001020 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001021 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001022 if (mMaxItemId < 0) {
1023 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001024 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001025 mMaxItemId += 1;
1026 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001027 }
1028
Sunny Goyal55fddc82017-04-06 15:02:52 -07001029 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001030 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001031 }
1032
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001033 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001034 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001035 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001036 }
1037
Sunny Goyalc5939392018-12-07 11:43:47 -08001038 public void checkId(ContentValues values) {
1039 int id = values.getAsInteger(Favorites._ID);
1040 mMaxItemId = Math.max(id, mMaxItemId);
1041
1042 Integer screen = values.getAsInteger(Favorites.SCREEN);
1043 Integer container = values.getAsInteger(Favorites.CONTAINER);
1044 if (screen != null && container != null
1045 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1046 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001047 }
1048 }
1049
Sunny Goyalefb7e842018-10-04 15:11:00 -07001050 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001051 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001052 }
1053
1054 // Generates a new ID to use for an workspace screen in your database. This method
1055 // should be only called from the main UI thread. As an exception, we do call it when we
1056 // call the constructor from the worker thread; however, this doesn't extend until after the
1057 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1058 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001059 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001060 if (mMaxScreenId < 0) {
1061 throw new RuntimeException("Error: max screen id was not initialized");
1062 }
1063 mMaxScreenId += 1;
1064 return mMaxScreenId;
1065 }
1066
Sunny Goyalefb7e842018-10-04 15:11:00 -07001067 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyal12e3f1f2021-07-15 14:31:58 -07001068 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001069 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1070 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001071 }
1072
Adam Cohen091440a2015-03-18 14:16:05 -07001073 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001074 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001075 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001076
1077 // Ensure that the max ids are initialized
1078 mMaxItemId = initializeMaxItemId(db);
1079 mMaxScreenId = initializeMaxScreenId(db);
1080 return count;
1081 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001082 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001083
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001084 /**
1085 * @return the max _id in the provided table.
1086 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001087 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001088 int max = 0;
1089 try (SQLiteStatement prog = db.compileStatement(
1090 String.format(Locale.ENGLISH, query, args))) {
1091 max = (int) DatabaseUtils.longForQuery(prog, null);
1092 if (max < 0) {
1093 throw new RuntimeException("Error: could not query max id");
1094 }
1095 } catch (IllegalArgumentException exception) {
1096 String message = exception.getMessage();
1097 if (message.contains("re-open") && message.contains("already-closed")) {
1098 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1099 } else {
1100 throw exception;
1101 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001102 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001103 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001104 }
1105
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001106 static class SqlArguments {
1107 public final String table;
1108 public final String where;
1109 public final String[] args;
1110
1111 SqlArguments(Uri url, String where, String[] args) {
1112 if (url.getPathSegments().size() == 1) {
1113 this.table = url.getPathSegments().get(0);
1114 this.where = where;
1115 this.args = args;
1116 } else if (url.getPathSegments().size() != 2) {
1117 throw new IllegalArgumentException("Invalid URI: " + url);
1118 } else if (!TextUtils.isEmpty(where)) {
1119 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1120 } else {
1121 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001122 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001123 this.args = null;
1124 }
1125 }
1126
1127 SqlArguments(Uri url) {
1128 if (url.getPathSegments().size() == 1) {
1129 table = url.getPathSegments().get(0);
1130 where = null;
1131 args = null;
1132 } else {
1133 throw new IllegalArgumentException("Invalid URI: " + url);
1134 }
1135 }
1136 }
Adam Cohen72960972014-01-15 18:13:55 -08001137}