blob: 440e9e38dddd42bc5265602c1f9e4a561f0ad080 [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;
23
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070024import android.annotation.TargetApi;
Jon Miranda2bc6b932019-03-07 15:24:46 -080025import android.app.backup.BackupManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070026import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070027import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070029import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000030import android.content.ContentProviderOperation;
31import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.ContentUris;
33import android.content.ContentValues;
34import android.content.Context;
35import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000036import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070037import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070038import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080041import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070045import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070046import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070048import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070049import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070050import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080051import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080052import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080053import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070054import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070055import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070057import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070058
Sunny Goyal0fe505b2014-08-06 09:55:36 -070059import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
60import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070061import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080062import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070063import com.android.launcher3.model.DbDowngradeHelper;
Yogisha Dixit658c5da2021-05-24 23:23:15 +010064import com.android.launcher3.model.data.ItemInfo;
Sunny Goyal337c81f2019-12-10 12:19:13 -080065import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070066import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070067import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070068import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070069import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070070import com.android.launcher3.util.IntArray;
71import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080072import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070073import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070074import com.android.launcher3.util.Thunk;
Yogisha Dixit741fae92021-02-22 14:03:44 +000075import com.android.launcher3.widget.LauncherAppWidgetHost;
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;
Pinyao Ting0807c942020-04-28 13:58:45 -070088import java.util.concurrent.TimeUnit;
Tracy Zhouc0000452020-03-17 18:28:38 -070089import java.util.function.Supplier;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070092 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080093 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Sunny Goyal05f30882017-05-03 12:42:18 -070095 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Ting0807c942020-04-28 13:58:45 -070096 private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
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 */
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100102 public static final int SCHEMA_VERSION = 29;
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";
Pinyao Ting96186af2020-07-20 11:03:39 -0700105 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700106
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800107 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108
Sunny Goyalf076eae2016-01-11 12:25:10 -0800109 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700110 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
Pinyao Ting0807c942020-04-28 13:58:45 -0700112 private long mLastRestoreTimestamp = 0L;
113
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800114 /**
115 * $ adb shell dumpsys activity provider com.android.launcher3
116 */
117 @Override
118 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
119 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
120 if (appState == null || !appState.getModel().isModelLoaded()) {
121 return;
122 }
123 appState.getModel().dumpState("", fd, writer, args);
124 }
125
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800126 @Override
127 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800128 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700129 Log.d(TAG, "Launcher process started");
130 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700131
Sunny Goyalfdbef272017-02-01 12:52:54 -0800132 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800133 // is the first component to get created.
134 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800135 return true;
136 }
137
138 @Override
139 public String getType(Uri uri) {
140 SqlArguments args = new SqlArguments(uri, null, null);
141 if (TextUtils.isEmpty(args.where)) {
142 return "vnd.android.cursor.dir/" + args.table;
143 } else {
144 return "vnd.android.cursor.item/" + args.table;
145 }
146 }
147
Sunny Goyalf076eae2016-01-11 12:25:10 -0800148 /**
149 * Overridden in tests
150 */
151 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700152 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700153 mOpenHelper = DatabaseHelper.createDatabaseHelper(
154 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700155
156 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700157 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
158 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700159 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
160 }
161 // Set is pending to false irrespective of the result, so that it doesn't get
162 // executed again.
163 RestoreDbTask.setPending(getContext(), false);
164 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700165 }
166 }
167
Tracy Zhouc0000452020-03-17 18:28:38 -0700168 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
169 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
170 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800171 return false;
172 }
173
Tracy Zhouc0000452020-03-17 18:28:38 -0700174 final DatabaseHelper helper = src.get();
175 mOpenHelper = dst.get();
176 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
177 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
178 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800179 return true;
180 }
181
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 @Override
183 public Cursor query(Uri uri, String[] projection, String selection,
184 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700185 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186
187 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
188 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
189 qb.setTables(args.table);
190
Romain Guy73b979d2009-06-09 12:57:21 -0700191 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700193 final Bundle extra = new Bundle();
194 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
195 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196 result.setNotificationUri(getContext().getContentResolver(), uri);
197
198 return result;
199 }
200
Sunny Goyalefb7e842018-10-04 15:11:00 -0700201 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500203 if (values == null) {
204 throw new RuntimeException("Error: attempting to insert null values");
205 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800206 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700207 throw new RuntimeException("Error: attempting to add item without specifying an id");
208 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800209 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700210 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700211 }
212
Sunny Goyald1064182015-08-13 12:08:30 -0700213 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800214 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700215 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
216 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800217 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700218 }
219 }
220 }
221
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222 @Override
223 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700224 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225 SqlArguments args = new SqlArguments(uri);
226
Sunny Goyald1064182015-08-13 12:08:30 -0700227 // In very limited cases, we support system|signature permission apps to modify the db.
228 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700229 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700230 return null;
231 }
232 }
233
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400235 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700236 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800237 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800238 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239
240 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800241 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return uri;
243 }
244
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700245 private boolean initializeExternalAdd(ContentValues values) {
246 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700247 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700248 values.put(LauncherSettings.Favorites._ID, id);
249
250 // 2. In the case of an app widget, and if no app widget id is specified, we
251 // attempt allocate and bind the widget.
252 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
253 if (itemType != null &&
254 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
255 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
256
257 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
258 ComponentName cn = ComponentName.unflattenFromString(
259 values.getAsString(Favorites.APPWIDGET_PROVIDER));
260
261 if (cn != null) {
262 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700263 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
264 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700265 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
266 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700267 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700268 return false;
269 }
270 } catch (RuntimeException e) {
271 Log.e(TAG, "Failed to initialize external widget", e);
272 return false;
273 }
274 } else {
275 return false;
276 }
277 }
278
Sunny Goyalc5939392018-12-07 11:43:47 -0800279 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700280 }
281
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800282 @Override
283 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700284 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800285 SqlArguments args = new SqlArguments(uri);
286
287 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700288 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800289 int numValues = values.length;
290 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400291 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700292 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
293 return 0;
294 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800296 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700297 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800298 }
299
Sunny Goyald1064182015-08-13 12:08:30 -0700300 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 return values.length;
302 }
303
Sunny Goyal161a2142018-10-29 14:02:20 -0700304 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305 @Override
Yura085c8532014-02-11 15:15:29 +0000306 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
307 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700308 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700309 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800310 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700311
312 final int numOperations = operations.size();
313 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
314 for (int i = 0; i < numOperations; i++) {
315 ContentProviderOperation op = operations.get(i);
316 results[i] = op.apply(this, results, i);
317
318 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
319 results[i].count != null && results[i].count > 0;
320 }
321 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800322 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700323 }
324
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700325 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700326 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700327 return results;
Yura085c8532014-02-11 15:15:29 +0000328 }
329 }
330
331 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700333 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
335
336 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337
Louis Begina9c21c62016-08-15 15:18:41 -0700338 if (Binder.getCallingPid() != Process.myPid()
339 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700340 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700341 }
342 int count = db.delete(args.table, args.where, args.args);
343 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800344 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700345 reloadLauncherIfExternal();
346 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 return count;
348 }
349
350 @Override
351 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700352 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800353 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
354
Chris Wren1ada10d2013-09-13 18:01:38 -0400355 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
357 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700358 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 return count;
360 }
361
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700363 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700364 if (Binder.getCallingUid() != Process.myUid()) {
365 return null;
366 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700367 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700368
369 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700370 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
371 clearFlagEmptyDbCreated();
372 return null;
373 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700374 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
375 Bundle result = new Bundle();
376 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Pinyao Ting96186af2020-07-20 11:03:39 -0700377 Utilities.getPrefs(getContext()).getBoolean(
378 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700379 return result;
380 }
Sunny Goyald2497482015-09-22 18:24:19 -0700381 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
382 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700383 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
384 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700385 return result;
386 }
387 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
388 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800389 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
390 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700391 return result;
392 }
393 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
394 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800395 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
396 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700397 return result;
398 }
399 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800400 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700401 return null;
402 }
403 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
404 loadDefaultFavoritesIfNecessary();
405 return null;
406 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700407 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
408 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
409 return null;
410 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700411 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
412 Bundle result = new Bundle();
413 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
414 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
415 return result;
416 }
417 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700418 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
419 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700420 return null;
421 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700422 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
423 mOpenHelper.mHotseatRestoreTableExists = tableExists(
424 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
425 return null;
426 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700427 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700428 final long ts = System.currentTimeMillis();
429 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
430 mLastRestoreTimestamp = ts;
431 RestoreDbTask.restoreIfPossible(
432 getContext(), mOpenHelper, new BackupManager(getContext()));
433 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700434 return null;
435 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800436 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
437 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
438 Bundle result = new Bundle();
439 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Tracy Zhouc0000452020-03-17 18:28:38 -0700440 prepForMigration(
441 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
442 Favorites.TMP_TABLE,
443 () -> mOpenHelper,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700444 () -> DatabaseHelper.createDatabaseHelper(
445 getContext(), true /* forMigration */)));
Tracy Zhouc0000452020-03-17 18:28:38 -0700446 return result;
447 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700448 return null;
Tracy Zhouc0000452020-03-17 18:28:38 -0700449 }
450 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
451 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
452 Bundle result = new Bundle();
453 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
454 prepForMigration(
455 arg /* dbFile */,
456 Favorites.PREVIEW_TABLE_NAME,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700457 () -> DatabaseHelper.createDatabaseHelper(
458 getContext(), arg, true /* forMigration */),
Tracy Zhouc0000452020-03-17 18:28:38 -0700459 () -> mOpenHelper));
Tracy Zhou7df93d22020-01-27 13:44:06 -0800460 return result;
461 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700462 return null;
463 }
464 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
465 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
466 final DatabaseHelper helper = mOpenHelper;
467 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
468 mProviderAuthority = null;
469 } else {
470 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
471 }
472 mOpenHelper = DatabaseHelper.createDatabaseHelper(
473 getContext(), arg, false /* forMigration */);
474 helper.close();
475 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
476 if (app == null) return null;
477 app.getModel().forceReload();
478 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800479 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700480 }
481 return null;
482 }
483
Tracy Zhou7df93d22020-01-27 13:44:06 -0800484 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700485 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800486 }
487
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700488 /**
489 * Deletes any empty folder from the DB.
490 * @return Ids of deleted folders.
491 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700492 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700493 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700494 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700495 // Select folders whose id do not match any container value.
496 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
497 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
498 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
499 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700500 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800501
502 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
503 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700504 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700506 LauncherSettings.Favorites._ID, folderIds), null);
507 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700508 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800509 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700510 } catch (SQLException ex) {
511 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800512 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700513 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700514 }
515
Adam Cohen091440a2015-03-18 14:16:05 -0700516 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800517 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800518 }
519
Sunny Goyald2497482015-09-22 18:24:19 -0700520 private void clearFlagEmptyDbCreated() {
Pinyao Ting96186af2020-07-20 11:03:39 -0700521 Utilities.getPrefs(getContext()).edit()
522 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700523 }
524
Sunny Goyal42de82f2014-09-26 22:09:29 -0700525 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700526 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700527 * 1) From the app restrictions
528 * 2) From a package provided by play store
529 * 3) From a partner configuration APK, already in the system image
530 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700531 */
Sunny Goyald2497482015-09-22 18:24:19 -0700532 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700533 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700534
Pinyao Ting96186af2020-07-20 11:03:39 -0700535 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500536 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200537
Sunny Goyal55fddc82017-04-06 15:02:52 -0700538 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700539 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700540 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700541 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700542 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700543 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700544 final Partner partner = Partner.get(getContext().getPackageManager());
545 if (partner != null && partner.hasDefaultLayout()) {
546 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700547 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700548 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700549 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700551 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700552 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700553 }
554 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700555
Sunny Goyal9d219682014-10-23 14:21:02 -0700556 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700557 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700558 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700559 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800560
561 // There might be some partially restored DB items, due to buggy restore logic in
562 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800563 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700564 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700565 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
566 && usingExternallyProvidedLayout) {
567 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800568 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700569 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700570 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700571 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700572 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700573 }
574 }
575
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700576 /**
577 * Creates workspace loader from an XML resource listed in the app restrictions.
578 *
579 * @return the loader if the restrictions are set and the resource exists; null otherwise.
580 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700581 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700582 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700583 final String authority;
584 if (!TextUtils.isEmpty(mProviderAuthority)) {
585 authority = mProviderAuthority;
586 } else {
587 authority = Settings.Secure.getString(ctx.getContentResolver(),
588 "launcher3.layout.provider");
589 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700590 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700591 return null;
592 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700593
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700594 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
595 if (pi == null) {
596 Log.e(TAG, "No provider found for authority " + authority);
597 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700598 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800599 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700600 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
601 // Read the full xml so that we fail early in case of any IO error.
602 String layout = new String(IOUtils.toByteArray(in));
603 XmlPullParser parser = Xml.newPullParser();
604 parser.setInput(new StringReader(layout));
605
606 Log.d(TAG, "Loading layout from " + authority);
607 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
608 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
609 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
610 } catch (Exception e) {
611 Log.e(TAG, "Error getting layout stream from: " + authority , e);
612 return null;
613 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700614 }
615
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800616 public static Uri getLayoutUri(String authority, Context ctx) {
617 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
618 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
619 .appendQueryParameter("version", "1")
620 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
621 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700622 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800623 .build();
624 }
625
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700626 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700627 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
628 int defaultLayout = idp.defaultLayoutId;
629
Sunny Goyal337c81f2019-12-10 12:19:13 -0800630 if (getContext().getSystemService(UserManager.class).isDemoUser()
631 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700632 defaultLayout = idp.demoModeLayoutId;
633 }
634
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700635 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700636 mOpenHelper, getContext().getResources(), defaultLayout);
637 }
638
Sunny Goyald3849d12015-10-29 10:28:32 -0700639 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800640 * The class is subclassed in tests to create an in-memory db.
641 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800642 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
643 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800644 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700645 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700646 private int mMaxItemId = -1;
647 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700648 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700649 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650
Tracy Zhoued5f3082020-04-20 01:13:26 -0700651 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
652 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700653 }
654
Tracy Zhoued5f3082020-04-20 01:13:26 -0700655 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
656 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700657 if (dbName == null) {
658 dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
659 context).dbFile : LauncherFiles.LAUNCHER_DB;
660 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700661 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700662 // Table creation sometimes fails silently, which leads to a crash loop.
663 // This way, we will try to create a table every time after crash, so the device
664 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700665 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700666 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
667 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700668 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700669 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800670 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700671 databaseHelper.mBackupTableExists = tableExists(
672 databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800673 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700674 databaseHelper.mHotseatRestoreTableExists = tableExists(
675 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700676
Tracy Zhouc0000452020-03-17 18:28:38 -0700677 databaseHelper.initIds();
678 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700679 }
680
681 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700682 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700683 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700684 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800685 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700686 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700687 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700688 }
689
690 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700691 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
692 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700693 if (mMaxItemId == -1) {
694 mMaxItemId = initializeMaxItemId(getWritableDatabase());
695 }
696 if (mMaxScreenId == -1) {
697 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700698 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 }
700
701 @Override
702 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800703 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700704
Adam Cohendcd297f2013-06-18 13:13:40 -0700705 mMaxItemId = 1;
706 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700707
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700708 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800709
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800710 // Fresh and clean launcher DB.
711 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700712 if (!mForMigration) {
713 onEmptyDbCreated();
714 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800715 }
716
Sunny Goyal161a2142018-10-29 14:02:20 -0700717 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700718 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700719 dropTable(db, Favorites.BACKUP_TABLE_NAME);
720 mBackupTableExists = false;
721 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700722 if (mHotseatRestoreTableExists) {
723 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
724 mHotseatRestoreTableExists = false;
725 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700726 }
727
Sunny Goyalf076eae2016-01-11 12:25:10 -0800728 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700729 * Re-composite given key in respect to database. If the current db is
730 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
731 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
732 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
733 */
734 String getKey(final String key) {
735 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
736 return key;
737 }
738 return key + "@" + getDatabaseName();
739 }
740
741 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800742 * Overriden in tests.
743 */
744 protected void onEmptyDbCreated() {
745 // Set the flag for empty DB
Pinyao Ting96186af2020-07-20 11:03:39 -0700746 Utilities.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
747 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800748 }
749
Jon Miranda2bc6b932019-03-07 15:24:46 -0800750 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800751 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800752 }
753
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700754 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800755 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800756 }
757
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700758 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700759 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700760 }
761
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800762 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700763 public void onOpen(SQLiteDatabase db) {
764 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700765
766 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
767 if (!schemaFile.exists()) {
768 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700769 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800770 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700771 }
772
773 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700774 * One-time data updated before support of onDowngrade was added. This update is backwards
775 * compatible and can safely be run multiple times.
776 * Note: No new logic should be added here after release, as the new logic might not get
777 * executed on an existing device.
778 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700779 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700780 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
781 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800782 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700783 for (UserHandle user : um.getUserProfiles()) {
784 long serial = um.getSerialNumberForUser(user);
785 String sql = "update favorites set intent = replace(intent, "
786 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
787 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700788 }
789 }
790
791 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800792 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700793 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 switch (oldVersion) {
795 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800796 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800797 case 12:
798 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800799 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700800 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800801 // Insert new column for holding widget provider name
802 db.execSQL("ALTER TABLE favorites " +
803 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700804 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800805 } catch (SQLException ex) {
806 Log.e(TAG, ex.getMessage(), ex);
807 // Old version remains, which means we wipe old data
808 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800809 }
810 }
811 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800812 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800813 // Old version remains, which means we wipe old data
814 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800815 }
816 }
817 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700818 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800819 // Old version remains, which means we wipe old data
820 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800821 }
822 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800823 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700824 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800825 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800826 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800827 case 18:
828 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800829 case 19: {
830 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800831 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800832 // Old version remains, which means we wipe old data
833 break;
834 }
835 }
836 case 20:
837 if (!updateFolderItemsRank(db, true)) {
838 break;
839 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800840 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800841 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800842 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700843 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
844 // Old version remains, which means we wipe old data
845 break;
846 }
847 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700849 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700850 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000851 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700852 case 25:
853 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700854 case 26:
855 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700856 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800857 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700858 break;
859 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800860 case 27: {
861 // Update the favorites table so that the screen ids are ordered based on
862 // workspace page rank.
863 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
864 BaseColumns._ID, null, null, "screenRank");
865 int[] original = finalScreens.toArray();
866 Arrays.sort(original);
867 String updatemap = "";
868 for (int i = 0; i < original.length; i++) {
869 if (finalScreens.get(i) != original[i]) {
870 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
871 Favorites.SCREEN, finalScreens.get(i), original[i]);
872 }
873 }
874 if (!TextUtils.isEmpty(updatemap)) {
875 String query = String.format(Locale.ENGLISH,
876 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
877 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
878 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
879 db.execSQL(query);
880 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700881 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800882 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100883 case 28: {
884 boolean columnAdded = addIntegerColumn(
885 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
886 if (!columnAdded) {
887 // Old version remains, which means we wipe old data
888 break;
889 }
890 }
891 case 29: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800892 // DB Upgraded successfully
893 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100894 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400895 }
896
Sunny Goyala2cc6242015-01-14 14:23:02 -0800897 // DB was not upgraded
898 Log.w(TAG, "Destroying all old data.");
899 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800901
Adam Cohen9b1d0622014-05-21 19:01:57 -0700902 @Override
903 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700904 try {
905 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
906 .onDowngrade(db, oldVersion, newVersion);
907 } catch (Exception e) {
908 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
909 ". Wiping databse.", e);
910 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700911 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700912 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700913
Sunny Goyal42de82f2014-09-26 22:09:29 -0700914 /**
915 * Clears all the data for a fresh start.
916 */
917 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700918 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700919 dropTable(db, Favorites.TABLE_NAME);
920 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800921 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700922 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800923 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700924 }
925
Sunny Goyald2f38192015-02-25 10:46:34 -0800926 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700927 * Removes widgets which are registered to the Launcher's host, but are not present
928 * in our model.
929 */
930 public void removeGhostWidgets(SQLiteDatabase db) {
931 // Get all existing widget ids.
932 final AppWidgetHost host = newLauncherWidgetHost();
933 final int[] allWidgets;
934 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700935 // Although the method was defined in O, it has existed since the beginning of time,
936 // so it might work on older platforms as well.
937 allWidgets = host.getAppWidgetIds();
938 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700939 Log.e(TAG, "getAppWidgetIds not supported", e);
940 return;
941 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800942 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
943 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
944 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700945 for (int widgetId : allWidgets) {
946 if (!validWidgets.contains(widgetId)) {
947 try {
948 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
949 host.deleteAppWidgetId(widgetId);
950 } catch (RuntimeException e) {
951 // Ignore
952 }
953 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700954 }
955 }
956
957 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700958 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
959 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
960 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700961 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700962 try (SQLiteTransaction t = new SQLiteTransaction(db);
963 // Only consider the primary user as other users can't have a shortcut.
964 Cursor c = db.query(Favorites.TABLE_NAME,
965 new String[] { Favorites._ID, Favorites.INTENT},
966 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
967 " AND profileId=" + getDefaultUserSerial(),
968 null, null, null, null);
969 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
970 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
971 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700972 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
973 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
974
975 while (c.moveToNext()) {
976 String intentDescription = c.getString(intentIndex);
977 Intent intent;
978 try {
979 intent = Intent.parseUri(intentDescription, 0);
980 } catch (URISyntaxException e) {
981 Log.e(TAG, "Unable to parse intent", e);
982 continue;
983 }
984
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700985 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700986 continue;
987 }
988
Sunny Goyalefb7e842018-10-04 15:11:00 -0700989 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700990 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700991 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700992 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700993 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700994 } catch (SQLException ex) {
995 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700996 }
997 }
998
Adam Cohen091440a2015-03-18 14:16:05 -0700999 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001000 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001001 if (addRankColumn) {
1002 // Insert new column for holding rank
1003 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1004 }
1005
1006 // Get a map for folder ID to folder width
1007 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1008 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1009 + " GROUP BY container;",
1010 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1011
1012 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001013 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1014 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001015 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1016 }
1017
1018 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001019 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001020 } catch (SQLException ex) {
1021 // Old version remains, which means we wipe old data
1022 Log.e(TAG, ex.getMessage(), ex);
1023 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001024 }
1025 return true;
1026 }
1027
Sunny Goyal5d85c442015-03-10 13:14:47 -07001028 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001029 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001030 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1031 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001032 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001033 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001034 Log.e(TAG, ex.getMessage(), ex);
1035 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001036 }
1037 return true;
1038 }
1039
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001040 // Generates a new ID to use for an object in your database. This method should be only
1041 // called from the main UI thread. As an exception, we do call it when we call the
1042 // constructor from the worker thread; however, this doesn't extend until after the
1043 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1044 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001045 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001046 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001047 if (mMaxItemId < 0) {
1048 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001049 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001050 mMaxItemId += 1;
1051 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001052 }
1053
Sunny Goyal55fddc82017-04-06 15:02:52 -07001054 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001055 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001056 }
1057
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001058 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001059 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001060 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001061 }
1062
Sunny Goyalc5939392018-12-07 11:43:47 -08001063 public void checkId(ContentValues values) {
1064 int id = values.getAsInteger(Favorites._ID);
1065 mMaxItemId = Math.max(id, mMaxItemId);
1066
1067 Integer screen = values.getAsInteger(Favorites.SCREEN);
1068 Integer container = values.getAsInteger(Favorites.CONTAINER);
1069 if (screen != null && container != null
1070 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1071 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001072 }
1073 }
1074
Sunny Goyalefb7e842018-10-04 15:11:00 -07001075 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001076 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001077 }
1078
1079 // Generates a new ID to use for an workspace screen in your database. This method
1080 // should be only called from the main UI thread. As an exception, we do call it when we
1081 // call the constructor from the worker thread; however, this doesn't extend until after the
1082 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1083 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001084 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001085 if (mMaxScreenId < 0) {
1086 throw new RuntimeException("Error: max screen id was not initialized");
1087 }
1088 mMaxScreenId += 1;
1089 return mMaxScreenId;
1090 }
1091
Sunny Goyalefb7e842018-10-04 15:11:00 -07001092 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001093 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
1094 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1095 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001096 }
1097
Adam Cohen091440a2015-03-18 14:16:05 -07001098 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001099 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001100 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001101
1102 // Ensure that the max ids are initialized
1103 mMaxItemId = initializeMaxItemId(db);
1104 mMaxScreenId = initializeMaxScreenId(db);
1105 return count;
1106 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001107 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001108
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001109 /**
1110 * @return the max _id in the provided table.
1111 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001112 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001113 int max = 0;
1114 try (SQLiteStatement prog = db.compileStatement(
1115 String.format(Locale.ENGLISH, query, args))) {
1116 max = (int) DatabaseUtils.longForQuery(prog, null);
1117 if (max < 0) {
1118 throw new RuntimeException("Error: could not query max id");
1119 }
1120 } catch (IllegalArgumentException exception) {
1121 String message = exception.getMessage();
1122 if (message.contains("re-open") && message.contains("already-closed")) {
1123 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1124 } else {
1125 throw exception;
1126 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001127 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001128 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001129 }
1130
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001131 static class SqlArguments {
1132 public final String table;
1133 public final String where;
1134 public final String[] args;
1135
1136 SqlArguments(Uri url, String where, String[] args) {
1137 if (url.getPathSegments().size() == 1) {
1138 this.table = url.getPathSegments().get(0);
1139 this.where = where;
1140 this.args = args;
1141 } else if (url.getPathSegments().size() != 2) {
1142 throw new IllegalArgumentException("Invalid URI: " + url);
1143 } else if (!TextUtils.isEmpty(where)) {
1144 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1145 } else {
1146 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001147 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 this.args = null;
1149 }
1150 }
1151
1152 SqlArguments(Uri url) {
1153 if (url.getPathSegments().size() == 1) {
1154 table = url.getPathSegments().get(0);
1155 where = null;
1156 args = null;
1157 } else {
1158 throw new IllegalArgumentException("Invalid URI: " + url);
1159 }
1160 }
1161 }
Adam Cohen72960972014-01-15 18:13:55 -08001162}