blob: d002c2b90183391738a9be6baf6be8754da70774 [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;
Mike Cleronb87bd162009-10-30 16:36:56 -070025import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000028import android.content.ContentProviderOperation;
29import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070030import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000034import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070035import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070036import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080039import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070042import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070043import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070046import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070048import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080049import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080050import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080051import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070052import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070053import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080054import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070055import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070056
Sihua Maaa2b8722022-10-25 15:17:58 -070057import androidx.annotation.NonNull;
58
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;
Sunny Goyal337c81f2019-12-10 12:19:13 -080064import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070065import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070066import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070067import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070068import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070069import com.android.launcher3.util.IntArray;
70import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080071import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070072import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070073import com.android.launcher3.util.Thunk;
Sihua Ma8bbfcb62022-11-08 16:46:07 -080074import com.android.launcher3.widget.LauncherWidgetHolder;
Michael Jurka8b805b12012-04-18 14:23:14 -070075
Sunny Goyalc0f03d92019-03-22 14:13:36 -070076import org.xmlpull.v1.XmlPullParser;
77
Sunny Goyal05f30882017-05-03 12:42:18 -070078import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080079import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070080import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080081import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070082import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070083import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070084import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070085import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080086import java.util.Locale;
Pinyao Ting0807c942020-04-28 13:58:45 -070087import java.util.concurrent.TimeUnit;
Tracy Zhouc0000452020-03-17 18:28:38 -070088import java.util.function.Supplier;
Pinyao Ting7fd7e512022-10-03 17:46:03 -070089import java.util.stream.Collectors;
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 */
Alex Chaue09067c2022-01-10 16:13:13 +0000102 public static final int SCHEMA_VERSION = 31;
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
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800107 private static final int TEST_WORKSPACE_LAYOUT_RES_XML = R.xml.default_test_workspace;
108
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800109 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
Sunny Goyalf076eae2016-01-11 12:25:10 -0800111 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700112 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
Pinyao Ting0807c942020-04-28 13:58:45 -0700114 private long mLastRestoreTimestamp = 0L;
115
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800116 private boolean mUseTestWorkspaceLayout;
117
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800118 /**
119 * $ adb shell dumpsys activity provider com.android.launcher3
120 */
121 @Override
122 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
123 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
124 if (appState == null || !appState.getModel().isModelLoaded()) {
125 return;
126 }
127 appState.getModel().dumpState("", fd, writer, args);
128 }
129
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800130 @Override
131 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800132 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700133 Log.d(TAG, "Launcher process started");
134 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700135
Sunny Goyalfdbef272017-02-01 12:52:54 -0800136 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800137 // is the first component to get created.
138 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139 return true;
140 }
141
142 @Override
143 public String getType(Uri uri) {
144 SqlArguments args = new SqlArguments(uri, null, null);
145 if (TextUtils.isEmpty(args.where)) {
146 return "vnd.android.cursor.dir/" + args.table;
147 } else {
148 return "vnd.android.cursor.item/" + args.table;
149 }
150 }
151
Sunny Goyalf076eae2016-01-11 12:25:10 -0800152 /**
153 * Overridden in tests
154 */
155 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700156 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700157 mOpenHelper = DatabaseHelper.createDatabaseHelper(
158 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700159
Sunny Goyal68031ca2021-08-02 12:23:44 -0700160 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700161 }
162 }
163
Tracy Zhouc0000452020-03-17 18:28:38 -0700164 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
165 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
166 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Alex Chau0adc3662022-07-04 13:05:38 +0100167 Log.e(TAG, "prepForMigration - target db is same as current: " + dbFile);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800168 return false;
169 }
170
Tracy Zhouc0000452020-03-17 18:28:38 -0700171 final DatabaseHelper helper = src.get();
172 mOpenHelper = dst.get();
173 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
174 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
175 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800176 return true;
177 }
178
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179 @Override
180 public Cursor query(Uri uri, String[] projection, String selection,
181 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700182 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183
184 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
185 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
186 qb.setTables(args.table);
187
Romain Guy73b979d2009-06-09 12:57:21 -0700188 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700190 final Bundle extra = new Bundle();
191 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
192 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193 result.setNotificationUri(getContext().getContentResolver(), uri);
194
195 return result;
196 }
197
Sunny Goyalefb7e842018-10-04 15:11:00 -0700198 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700199 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500200 if (values == null) {
201 throw new RuntimeException("Error: attempting to insert null values");
202 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800203 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700204 throw new RuntimeException("Error: attempting to add item without specifying an id");
205 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800206 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700207 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700208 }
209
Sunny Goyald1064182015-08-13 12:08:30 -0700210 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800211 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700212 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
213 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800214 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700215 }
216 }
217 }
218
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800219 @Override
220 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700221 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222 SqlArguments args = new SqlArguments(uri);
223
Sunny Goyald1064182015-08-13 12:08:30 -0700224 // In very limited cases, we support system|signature permission apps to modify the db.
225 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700226 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700227 return null;
228 }
229 }
230
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400232 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700233 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800234 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800235 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800236
237 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800238 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239 return uri;
240 }
241
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700242 private boolean initializeExternalAdd(ContentValues values) {
243 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700244 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700245 values.put(LauncherSettings.Favorites._ID, id);
246
247 // 2. In the case of an app widget, and if no app widget id is specified, we
248 // attempt allocate and bind the widget.
249 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
250 if (itemType != null &&
251 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
252 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
253
254 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
255 ComponentName cn = ComponentName.unflattenFromString(
256 values.getAsString(Favorites.APPWIDGET_PROVIDER));
257
258 if (cn != null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700259 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700260 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700261 int appWidgetId = widgetHolder.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700262 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
263 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700264 widgetHolder.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700265 return false;
266 }
267 } catch (RuntimeException e) {
268 Log.e(TAG, "Failed to initialize external widget", e);
269 return false;
Sihua Maaa2b8722022-10-25 15:17:58 -0700270 } finally {
271 // Necessary to destroy the holder to free up possible activity context
272 widgetHolder.destroy();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700273 }
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,
Stefan Andonian146701c2022-11-10 23:07:40 +0000377 LauncherPrefs.getPrefs(getContext()).getBoolean(
Pinyao Ting96186af2020-07-20 11:03:39 -0700378 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,
Andras Kloczl953eb802021-10-15 21:16:48 +0100396 mOpenHelper.getNewScreenId());
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 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800403 case LauncherSettings.Settings.METHOD_SET_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
404 mUseTestWorkspaceLayout = true;
405 return null;
406 }
407 case LauncherSettings.Settings.METHOD_CLEAR_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
408 mUseTestWorkspaceLayout = false;
409 return null;
410 }
Sunny Goyald2497482015-09-22 18:24:19 -0700411 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
412 loadDefaultFavoritesIfNecessary();
413 return null;
414 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700415 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
416 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
417 return null;
418 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700419 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
420 Bundle result = new Bundle();
421 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
422 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
423 return result;
424 }
425 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700426 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
427 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700428 return null;
429 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700430 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
431 mOpenHelper.mHotseatRestoreTableExists = tableExists(
432 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
433 return null;
434 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700435 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700436 final long ts = System.currentTimeMillis();
437 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
438 mLastRestoreTimestamp = ts;
439 RestoreDbTask.restoreIfPossible(
440 getContext(), mOpenHelper, new BackupManager(getContext()));
441 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700442 return null;
443 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800444 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700445 Bundle result = new Bundle();
446 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
447 prepForMigration(
Alex Chaufe9a07b2022-03-08 21:48:34 +0000448 arg /* dbFile */,
Sunny Goyal278939f2021-07-28 14:35:47 -0700449 Favorites.TMP_TABLE,
450 () -> mOpenHelper,
451 () -> DatabaseHelper.createDatabaseHelper(
452 getContext(), true /* forMigration */)));
453 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700454 }
455 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700456 Bundle result = new Bundle();
457 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
458 prepForMigration(
459 arg /* dbFile */,
460 Favorites.PREVIEW_TABLE_NAME,
461 () -> DatabaseHelper.createDatabaseHelper(
462 getContext(), arg, true /* forMigration */),
463 () -> mOpenHelper));
464 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700465 }
466 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
467 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
468 final DatabaseHelper helper = mOpenHelper;
469 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
470 mProviderAuthority = null;
471 } else {
472 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
473 }
474 mOpenHelper = DatabaseHelper.createDatabaseHelper(
475 getContext(), arg, false /* forMigration */);
476 helper.close();
477 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
478 if (app == null) return null;
479 app.getModel().forceReload();
480 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800481 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700482 }
483 return null;
484 }
485
Tracy Zhou7df93d22020-01-27 13:44:06 -0800486 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700487 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800488 }
489
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700490 /**
491 * Deletes any empty folder from the DB.
492 * @return Ids of deleted folders.
493 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700494 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700495 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700496 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700497 // Select folders whose id do not match any container value.
498 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
499 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
500 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
501 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700502 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800503
Alex Chauac038432021-11-04 16:49:59 +0000504 IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Sunny Goyalc5939392018-12-07 11:43:47 -0800505 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700506 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700507 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700508 LauncherSettings.Favorites._ID, folderIds), null);
509 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700510 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800511 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700512 } catch (SQLException ex) {
513 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800514 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700515 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700516 }
517
Adam Cohen091440a2015-03-18 14:16:05 -0700518 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800519 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800520 }
521
Sunny Goyald2497482015-09-22 18:24:19 -0700522 private void clearFlagEmptyDbCreated() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000523 LauncherPrefs.getPrefs(getContext()).edit()
Pinyao Ting96186af2020-07-20 11:03:39 -0700524 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700525 }
526
Sunny Goyal42de82f2014-09-26 22:09:29 -0700527 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700528 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700529 * 1) From the app restrictions
530 * 2) From a package provided by play store
531 * 3) From a partner configuration APK, already in the system image
532 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700533 */
Sunny Goyald2497482015-09-22 18:24:19 -0700534 synchronized private void loadDefaultFavoritesIfNecessary() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000535 SharedPreferences sp = LauncherPrefs.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700536
Pinyao Ting96186af2020-07-20 11:03:39 -0700537 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500538 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200539
Sihua Maaa2b8722022-10-25 15:17:58 -0700540 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
541 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHolder);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700542 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700543 loader = AutoInstallsLayout.get(getContext(), widgetHolder, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700544 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700545 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700546 final Partner partner = Partner.get(getContext().getPackageManager());
547 if (partner != null && partner.hasDefaultLayout()) {
548 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700549 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700550 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700551 if (workspaceResId != 0) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700552 loader = new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700553 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700554 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700555 }
556 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700557
Sunny Goyal9d219682014-10-23 14:21:02 -0700558 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700559 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700560 loader = getDefaultLayoutParser(widgetHolder);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700561 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800562
563 // There might be some partially restored DB items, due to buggy restore logic in
564 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800565 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700566 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700567 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
568 && usingExternallyProvidedLayout) {
569 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800570 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700571 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sihua Maaa2b8722022-10-25 15:17:58 -0700572 getDefaultLayoutParser(widgetHolder));
Sunny Goyal9d219682014-10-23 14:21:02 -0700573 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700574 clearFlagEmptyDbCreated();
Sihua Maaa2b8722022-10-25 15:17:58 -0700575 widgetHolder.destroy();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700576 }
577 }
578
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700579 /**
580 * Creates workspace loader from an XML resource listed in the app restrictions.
581 *
582 * @return the loader if the restrictions are set and the resource exists; null otherwise.
583 */
Sihua Maaa2b8722022-10-25 15:17:58 -0700584 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(
585 LauncherWidgetHolder widgetHolder) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700586 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700587 final String authority;
588 if (!TextUtils.isEmpty(mProviderAuthority)) {
589 authority = mProviderAuthority;
590 } else {
591 authority = Settings.Secure.getString(ctx.getContentResolver(),
592 "launcher3.layout.provider");
593 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700594 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700595 return null;
596 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700597
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700598 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
599 if (pi == null) {
600 Log.e(TAG, "No provider found for authority " + authority);
601 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700602 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800603 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700604 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
605 // Read the full xml so that we fail early in case of any IO error.
606 String layout = new String(IOUtils.toByteArray(in));
607 XmlPullParser parser = Xml.newPullParser();
608 parser.setInput(new StringReader(layout));
609
610 Log.d(TAG, "Loading layout from " + authority);
Sihua Maaa2b8722022-10-25 15:17:58 -0700611 return new AutoInstallsLayout(ctx, widgetHolder, mOpenHelper,
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700612 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
613 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
614 } catch (Exception e) {
615 Log.e(TAG, "Error getting layout stream from: " + authority , e);
616 return null;
617 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700618 }
619
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800620 public static Uri getLayoutUri(String authority, Context ctx) {
621 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
622 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
623 .appendQueryParameter("version", "1")
624 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
625 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700626 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800627 .build();
628 }
629
Sihua Maaa2b8722022-10-25 15:17:58 -0700630 private DefaultLayoutParser getDefaultLayoutParser(LauncherWidgetHolder widgetHolder) {
Adam Cohen27824492017-09-22 17:10:55 -0700631 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800632 int defaultLayout = mUseTestWorkspaceLayout
633 ? TEST_WORKSPACE_LAYOUT_RES_XML : idp.defaultLayoutId;
Adam Cohen27824492017-09-22 17:10:55 -0700634
Sunny Goyal337c81f2019-12-10 12:19:13 -0800635 if (getContext().getSystemService(UserManager.class).isDemoUser()
636 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700637 defaultLayout = idp.demoModeLayoutId;
638 }
639
Sihua Maaa2b8722022-10-25 15:17:58 -0700640 return new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal9d219682014-10-23 14:21:02 -0700641 mOpenHelper, getContext().getResources(), defaultLayout);
642 }
643
Sunny Goyald3849d12015-10-29 10:28:32 -0700644 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800645 * The class is subclassed in tests to create an in-memory db.
646 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800647 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
648 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700650 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700651 private int mMaxItemId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700652 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700653 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654
Tracy Zhoued5f3082020-04-20 01:13:26 -0700655 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
656 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700657 }
658
Tracy Zhoued5f3082020-04-20 01:13:26 -0700659 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
660 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700661 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700662 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700663 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700664 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700665 // Table creation sometimes fails silently, which leads to a crash loop.
666 // This way, we will try to create a table every time after crash, so the device
667 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700668 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700669 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
670 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700671 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700672 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700673 databaseHelper.mHotseatRestoreTableExists = tableExists(
674 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700675
Tracy Zhouc0000452020-03-17 18:28:38 -0700676 databaseHelper.initIds();
677 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700678 }
679
680 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700681 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700682 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700683 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800684 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700685 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700686 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700687 }
688
689 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700690 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
691 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700692 if (mMaxItemId == -1) {
693 mMaxItemId = initializeMaxItemId(getWritableDatabase());
694 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800695 }
696
697 @Override
698 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800699 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700700
Adam Cohendcd297f2013-06-18 13:13:40 -0700701 mMaxItemId = 1;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700702
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700703 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800704
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800705 // Fresh and clean launcher DB.
706 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700707 if (!mForMigration) {
708 onEmptyDbCreated();
709 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800710 }
711
Sunny Goyal161a2142018-10-29 14:02:20 -0700712 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700713 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700714 dropTable(db, Favorites.BACKUP_TABLE_NAME);
715 mBackupTableExists = false;
716 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700717 if (mHotseatRestoreTableExists) {
718 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
719 mHotseatRestoreTableExists = false;
720 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700721 }
722
Sunny Goyalf076eae2016-01-11 12:25:10 -0800723 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700724 * Re-composite given key in respect to database. If the current db is
725 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
726 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
727 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
728 */
729 String getKey(final String key) {
730 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
731 return key;
732 }
733 return key + "@" + getDatabaseName();
734 }
735
736 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800737 * Overriden in tests.
738 */
739 protected void onEmptyDbCreated() {
740 // Set the flag for empty DB
Stefan Andonian146701c2022-11-10 23:07:40 +0000741 LauncherPrefs.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
Pinyao Ting96186af2020-07-20 11:03:39 -0700742 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800743 }
744
Jon Miranda2bc6b932019-03-07 15:24:46 -0800745 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800746 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800747 }
748
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700749 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800750 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800751 }
752
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700753 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700754 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700755 }
756
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700758 public void onOpen(SQLiteDatabase db) {
759 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700760
761 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
762 if (!schemaFile.exists()) {
763 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700764 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800765 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700766 }
767
768 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700769 * One-time data updated before support of onDowngrade was added. This update is backwards
770 * compatible and can safely be run multiple times.
771 * Note: No new logic should be added here after release, as the new logic might not get
772 * executed on an existing device.
773 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700774 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700775 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
776 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800777 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700778 for (UserHandle user : um.getUserProfiles()) {
779 long serial = um.getSerialNumberForUser(user);
780 String sql = "update favorites set intent = replace(intent, "
781 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
782 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700783 }
784 }
785
786 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800787 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700788 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 switch (oldVersion) {
790 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800791 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800792 case 12:
793 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700795 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800796 // Insert new column for holding widget provider name
797 db.execSQL("ALTER TABLE favorites " +
798 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700799 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800800 } catch (SQLException ex) {
801 Log.e(TAG, ex.getMessage(), ex);
802 // Old version remains, which means we wipe old data
803 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 }
805 }
806 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800807 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 // Old version remains, which means we wipe old data
809 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800810 }
811 }
812 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700813 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 // Old version remains, which means we wipe old data
815 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800816 }
817 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800818 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700819 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800820 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800821 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800822 case 18:
823 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 case 19: {
825 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800826 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800827 // Old version remains, which means we wipe old data
828 break;
829 }
830 }
831 case 20:
832 if (!updateFolderItemsRank(db, true)) {
833 break;
834 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800835 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800836 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800837 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700838 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
839 // Old version remains, which means we wipe old data
840 break;
841 }
842 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700844 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700845 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000846 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700847 case 25:
848 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700849 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700850 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800851 case 27: {
852 // Update the favorites table so that the screen ids are ordered based on
853 // workspace page rank.
Alex Chauac038432021-11-04 16:49:59 +0000854 IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
855 "workspaceScreens", BaseColumns._ID, null, null, "screenRank");
Sunny Goyalc5939392018-12-07 11:43:47 -0800856 int[] original = finalScreens.toArray();
857 Arrays.sort(original);
858 String updatemap = "";
859 for (int i = 0; i < original.length; i++) {
860 if (finalScreens.get(i) != original[i]) {
861 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
862 Favorites.SCREEN, finalScreens.get(i), original[i]);
863 }
864 }
865 if (!TextUtils.isEmpty(updatemap)) {
866 String query = String.format(Locale.ENGLISH,
867 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
868 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
869 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
870 db.execSQL(query);
871 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700872 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800873 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100874 case 28: {
875 boolean columnAdded = addIntegerColumn(
876 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
877 if (!columnAdded) {
878 // Old version remains, which means we wipe old data
879 break;
880 }
881 }
882 case 29: {
Andras Kloczl929e3a22021-09-06 03:30:30 +0100883 // Remove widget panel related leftover workspace items
884 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
885 Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
886 }
887 case 30: {
Alex Chaue09067c2022-01-10 16:13:13 +0000888 if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
889 // Clean up first row in screen 0 as it might contain junk data.
890 Log.d(TAG, "Cleaning up first row");
891 db.delete(Favorites.TABLE_NAME,
892 String.format(Locale.ENGLISH,
893 "%1$s = %2$d AND %3$s = %4$d AND %5$s = %6$d",
894 Favorites.SCREEN, 0,
895 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP,
896 Favorites.CELLY, 0), null);
897 }
898 return;
899 }
900 case 31: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800901 // DB Upgraded successfully
902 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100903 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400904 }
905
Sunny Goyala2cc6242015-01-14 14:23:02 -0800906 // DB was not upgraded
907 Log.w(TAG, "Destroying all old data.");
908 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800909 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800910
Adam Cohen9b1d0622014-05-21 19:01:57 -0700911 @Override
912 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700913 try {
914 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
915 .onDowngrade(db, oldVersion, newVersion);
916 } catch (Exception e) {
917 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
918 ". Wiping databse.", e);
919 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700920 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700921 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700922
Sunny Goyal42de82f2014-09-26 22:09:29 -0700923 /**
924 * Clears all the data for a fresh start.
925 */
926 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700927 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700928 dropTable(db, Favorites.TABLE_NAME);
929 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800930 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700931 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800932 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700933 }
934
Sunny Goyald2f38192015-02-25 10:46:34 -0800935 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700936 * Removes widgets which are registered to the Launcher's host, but are not present
937 * in our model.
938 */
939 public void removeGhostWidgets(SQLiteDatabase db) {
940 // Get all existing widget ids.
Sihua Maaa2b8722022-10-25 15:17:58 -0700941 final LauncherWidgetHolder holder = newLauncherWidgetHolder();
Sunny Goyal55fddc82017-04-06 15:02:52 -0700942 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700943 final int[] allWidgets;
944 try {
945 // Although the method was defined in O, it has existed since the beginning of
946 // time, so it might work on older platforms as well.
947 allWidgets = holder.getAppWidgetIds();
948 } catch (IncompatibleClassChangeError e) {
949 Log.e(TAG, "getAppWidgetIds not supported", e);
950 // Necessary to destroy the holder to free up possible activity context
951 holder.destroy();
952 return;
953 }
954 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
955 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
956 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
957 boolean isAnyWidgetRemoved = false;
958 for (int widgetId : allWidgets) {
959 if (!validWidgets.contains(widgetId)) {
960 try {
961 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
962 holder.deleteAppWidgetId(widgetId);
963 isAnyWidgetRemoved = true;
964 } catch (RuntimeException e) {
965 // Ignore
966 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700967 }
968 }
Sihua Maaa2b8722022-10-25 15:17:58 -0700969 if (isAnyWidgetRemoved) {
970 final String allWidgetsIds = Arrays.stream(allWidgets).mapToObj(String::valueOf)
971 .collect(Collectors.joining(",", "[", "]"));
972 final String validWidgetsIds = Arrays.stream(
973 validWidgets.getArray().toArray()).mapToObj(String::valueOf)
974 .collect(Collectors.joining(",", "[", "]"));
975 FileLog.d(TAG, "One or more widgets was removed. db_path=" + db.getPath()
976 + " allWidgetsIds=" + allWidgetsIds
977 + ", validWidgetsIds=" + validWidgetsIds);
978 }
979 } finally {
980 holder.destroy();
Pinyao Ting7fd7e512022-10-03 17:46:03 -0700981 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700982 }
983
984 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700985 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
986 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
987 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700988 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700989 try (SQLiteTransaction t = new SQLiteTransaction(db);
990 // Only consider the primary user as other users can't have a shortcut.
991 Cursor c = db.query(Favorites.TABLE_NAME,
992 new String[] { Favorites._ID, Favorites.INTENT},
993 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
994 " AND profileId=" + getDefaultUserSerial(),
995 null, null, null, null);
996 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
997 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
998 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700999 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1000 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
1001
1002 while (c.moveToNext()) {
1003 String intentDescription = c.getString(intentIndex);
1004 Intent intent;
1005 try {
1006 intent = Intent.parseUri(intentDescription, 0);
1007 } catch (URISyntaxException e) {
1008 Log.e(TAG, "Unable to parse intent", e);
1009 continue;
1010 }
1011
Sunny Goyal9dbb27c2019-07-17 15:12:56 -07001012 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001013 continue;
1014 }
1015
Sunny Goyalefb7e842018-10-04 15:11:00 -07001016 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001017 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -07001018 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -07001019 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001020 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -07001021 } catch (SQLException ex) {
1022 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001023 }
1024 }
1025
Adam Cohen091440a2015-03-18 14:16:05 -07001026 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001027 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001028 if (addRankColumn) {
1029 // Insert new column for holding rank
1030 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1031 }
1032
1033 // Get a map for folder ID to folder width
1034 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1035 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1036 + " GROUP BY container;",
1037 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1038
1039 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001040 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1041 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001042 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1043 }
1044
1045 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001046 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001047 } catch (SQLException ex) {
1048 // Old version remains, which means we wipe old data
1049 Log.e(TAG, ex.getMessage(), ex);
1050 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001051 }
1052 return true;
1053 }
1054
Sunny Goyal5d85c442015-03-10 13:14:47 -07001055 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001056 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001057 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1058 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001059 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001060 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001061 Log.e(TAG, ex.getMessage(), ex);
1062 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001063 }
1064 return true;
1065 }
1066
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001067 // Generates a new ID to use for an object in your database. This method should be only
1068 // called from the main UI thread. As an exception, we do call it when we call the
1069 // constructor from the worker thread; however, this doesn't extend until after the
1070 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1071 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001072 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001073 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 if (mMaxItemId < 0) {
1075 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001076 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001077 mMaxItemId += 1;
1078 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001079 }
1080
Sihua Maaa2b8722022-10-25 15:17:58 -07001081 /**
1082 * @return A new {@link LauncherWidgetHolder} based on the current context
1083 */
1084 @NonNull
1085 public LauncherWidgetHolder newLauncherWidgetHolder() {
1086 return new LauncherWidgetHolder(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001087 }
1088
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001089 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001090 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001091 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001092 }
1093
Sunny Goyalc5939392018-12-07 11:43:47 -08001094 public void checkId(ContentValues values) {
1095 int id = values.getAsInteger(Favorites._ID);
1096 mMaxItemId = Math.max(id, mMaxItemId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001097 }
1098
Sunny Goyalefb7e842018-10-04 15:11:00 -07001099 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001100 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001101 }
1102
Andras Kloczl953eb802021-10-15 21:16:48 +01001103 // Returns a new ID to use for an workspace screen in your database that is greater than all
1104 // existing screen IDs.
1105 private int getNewScreenId() {
1106 return getMaxId(getWritableDatabase(),
1107 "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001108 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Andras Kloczl953eb802021-10-15 21:16:48 +01001109 Favorites.CONTAINER_DESKTOP) + 1;
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001110 }
1111
Adam Cohen091440a2015-03-18 14:16:05 -07001112 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001113 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001114 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001115
1116 // Ensure that the max ids are initialized
1117 mMaxItemId = initializeMaxItemId(db);
Adam Cohen71483f42014-05-15 14:04:01 -07001118 return count;
1119 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001120 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001121
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001122 /**
1123 * @return the max _id in the provided table.
1124 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001125 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001126 int max = 0;
1127 try (SQLiteStatement prog = db.compileStatement(
1128 String.format(Locale.ENGLISH, query, args))) {
1129 max = (int) DatabaseUtils.longForQuery(prog, null);
1130 if (max < 0) {
1131 throw new RuntimeException("Error: could not query max id");
1132 }
1133 } catch (IllegalArgumentException exception) {
1134 String message = exception.getMessage();
1135 if (message.contains("re-open") && message.contains("already-closed")) {
1136 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1137 } else {
1138 throw exception;
1139 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001140 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001141 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001142 }
1143
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001144 static class SqlArguments {
1145 public final String table;
1146 public final String where;
1147 public final String[] args;
1148
1149 SqlArguments(Uri url, String where, String[] args) {
1150 if (url.getPathSegments().size() == 1) {
1151 this.table = url.getPathSegments().get(0);
1152 this.where = where;
1153 this.args = args;
1154 } else if (url.getPathSegments().size() != 2) {
1155 throw new IllegalArgumentException("Invalid URI: " + url);
1156 } else if (!TextUtils.isEmpty(where)) {
1157 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1158 } else {
1159 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001160 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001161 this.args = null;
1162 }
1163 }
1164
1165 SqlArguments(Uri url) {
1166 if (url.getPathSegments().size() == 1) {
1167 table = url.getPathSegments().get(0);
1168 where = null;
1169 args = null;
1170 } else {
1171 throw new IllegalArgumentException("Invalid URI: " + url);
1172 }
1173 }
1174 }
Adam Cohen72960972014-01-15 18:13:55 -08001175}