blob: 8ddbbaaf2eacf07bad800fc9953baf0f6dd052cb [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyal3e58eea2022-11-14 14:30:07 -080019import static com.android.launcher3.DefaultLayoutParser.RES_PARTNER_DEFAULT_LAYOUT;
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;
Mike Cleronb87bd162009-10-30 16:36:56 -070026import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000029import android.content.ContentProviderOperation;
30import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070031import android.content.ContentUris;
32import android.content.ContentValues;
33import android.content.Context;
34import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000035import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070036import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070037import android.content.pm.ProviderInfo;
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;
Sunny Goyal3e58eea2022-11-14 14:30:07 -080073import com.android.launcher3.util.Partner;
Adam Cohen091440a2015-03-18 14:16:05 -070074import com.android.launcher3.util.Thunk;
Sihua Ma8bbfcb62022-11-08 16:46:07 -080075import com.android.launcher3.widget.LauncherWidgetHolder;
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;
Pinyao Ting7fd7e512022-10-03 17:46:03 -070090import java.util.stream.Collectors;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070093 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080094 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
Sunny Goyal05f30882017-05-03 12:42:18 -070096 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Ting0807c942020-04-28 13:58:45 -070097 private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
Sunny Goyal05f30882017-05-03 12:42:18 -070098
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070099 /**
100 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -0800101 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700102 */
Alex Chaue09067c2022-01-10 16:13:13 +0000103 public static final int SCHEMA_VERSION = 31;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800105 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Pinyao Ting96186af2020-07-20 11:03:39 -0700106 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700107
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800108 private static final int TEST_WORKSPACE_LAYOUT_RES_XML = R.xml.default_test_workspace;
109
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800110 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111
Sunny Goyalf076eae2016-01-11 12:25:10 -0800112 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700113 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114
Pinyao Ting0807c942020-04-28 13:58:45 -0700115 private long mLastRestoreTimestamp = 0L;
116
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800117 private boolean mUseTestWorkspaceLayout;
118
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800119 /**
120 * $ adb shell dumpsys activity provider com.android.launcher3
121 */
122 @Override
123 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
124 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
125 if (appState == null || !appState.getModel().isModelLoaded()) {
126 return;
127 }
128 appState.getModel().dumpState("", fd, writer, args);
129 }
130
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131 @Override
132 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800133 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700134 Log.d(TAG, "Launcher process started");
135 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700136
Sunny Goyalfdbef272017-02-01 12:52:54 -0800137 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800138 // is the first component to get created.
139 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800140 return true;
141 }
142
143 @Override
144 public String getType(Uri uri) {
145 SqlArguments args = new SqlArguments(uri, null, null);
146 if (TextUtils.isEmpty(args.where)) {
147 return "vnd.android.cursor.dir/" + args.table;
148 } else {
149 return "vnd.android.cursor.item/" + args.table;
150 }
151 }
152
Sunny Goyalf076eae2016-01-11 12:25:10 -0800153 /**
154 * Overridden in tests
155 */
156 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700158 mOpenHelper = DatabaseHelper.createDatabaseHelper(
159 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700160
Sunny Goyal68031ca2021-08-02 12:23:44 -0700161 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700162 }
163 }
164
Tracy Zhouc0000452020-03-17 18:28:38 -0700165 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
166 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
167 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Alex Chau0adc3662022-07-04 13:05:38 +0100168 Log.e(TAG, "prepForMigration - target db is same as current: " + dbFile);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800169 return false;
170 }
171
Tracy Zhouc0000452020-03-17 18:28:38 -0700172 final DatabaseHelper helper = src.get();
173 mOpenHelper = dst.get();
174 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
175 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
176 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800177 return true;
178 }
179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 @Override
181 public Cursor query(Uri uri, String[] projection, String selection,
182 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700183 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
185 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
186 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
187 qb.setTables(args.table);
188
Romain Guy73b979d2009-06-09 12:57:21 -0700189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700191 final Bundle extra = new Bundle();
192 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
193 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 result.setNotificationUri(getContext().getContentResolver(), uri);
195
196 return result;
197 }
198
Sunny Goyalefb7e842018-10-04 15:11:00 -0700199 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700200 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500201 if (values == null) {
202 throw new RuntimeException("Error: attempting to insert null values");
203 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800204 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700205 throw new RuntimeException("Error: attempting to add item without specifying an id");
206 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800207 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700208 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700209 }
210
Sunny Goyald1064182015-08-13 12:08:30 -0700211 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800212 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700213 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
214 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800215 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700216 }
217 }
218 }
219
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 @Override
221 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700222 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223 SqlArguments args = new SqlArguments(uri);
224
Sunny Goyald1064182015-08-13 12:08:30 -0700225 // In very limited cases, we support system|signature permission apps to modify the db.
226 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700227 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700228 return null;
229 }
230 }
231
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400233 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700234 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800235 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800236 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237
238 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800239 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240 return uri;
241 }
242
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700243 private boolean initializeExternalAdd(ContentValues values) {
244 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700245 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700246 values.put(LauncherSettings.Favorites._ID, id);
247
248 // 2. In the case of an app widget, and if no app widget id is specified, we
249 // attempt allocate and bind the widget.
250 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
251 if (itemType != null &&
252 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
253 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
254
255 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
256 ComponentName cn = ComponentName.unflattenFromString(
257 values.getAsString(Favorites.APPWIDGET_PROVIDER));
258
259 if (cn != null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700260 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700261 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700262 int appWidgetId = widgetHolder.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700263 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
264 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700265 widgetHolder.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700266 return false;
267 }
268 } catch (RuntimeException e) {
269 Log.e(TAG, "Failed to initialize external widget", e);
270 return false;
Sihua Maaa2b8722022-10-25 15:17:58 -0700271 } finally {
272 // Necessary to destroy the holder to free up possible activity context
273 widgetHolder.destroy();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700274 }
275 } else {
276 return false;
277 }
278 }
279
Sunny Goyalc5939392018-12-07 11:43:47 -0800280 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700281 }
282
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800283 @Override
284 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700285 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800286 SqlArguments args = new SqlArguments(uri);
287
288 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700289 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 int numValues = values.length;
291 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400292 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700293 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
294 return 0;
295 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800296 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800297 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700298 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 }
300
Sunny Goyald1064182015-08-13 12:08:30 -0700301 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 return values.length;
303 }
304
Sunny Goyal161a2142018-10-29 14:02:20 -0700305 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 @Override
Yura085c8532014-02-11 15:15:29 +0000307 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
308 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700309 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700310 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800311 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700312
313 final int numOperations = operations.size();
314 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
315 for (int i = 0; i < numOperations; i++) {
316 ContentProviderOperation op = operations.get(i);
317 results[i] = op.apply(this, results, i);
318
319 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
320 results[i].count != null && results[i].count > 0;
321 }
322 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800323 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700324 }
325
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700326 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700327 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700328 return results;
Yura085c8532014-02-11 15:15:29 +0000329 }
330 }
331
332 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700334 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
336
337 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338
Louis Begina9c21c62016-08-15 15:18:41 -0700339 if (Binder.getCallingPid() != Process.myPid()
340 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700341 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700342 }
343 int count = db.delete(args.table, args.where, args.args);
344 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800345 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700346 reloadLauncherIfExternal();
347 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 return count;
349 }
350
351 @Override
352 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700353 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
355
Chris Wren1ada10d2013-09-13 18:01:38 -0400356 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
358 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700359 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 return count;
361 }
362
Sunny Goyal7779d622015-06-11 16:18:39 -0700363 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700364 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700365 if (Binder.getCallingUid() != Process.myUid()) {
366 return null;
367 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700368 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700369
370 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700371 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
372 clearFlagEmptyDbCreated();
373 return null;
374 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700375 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
376 Bundle result = new Bundle();
377 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Stefan Andonian146701c2022-11-10 23:07:40 +0000378 LauncherPrefs.getPrefs(getContext()).getBoolean(
Pinyao Ting96186af2020-07-20 11:03:39 -0700379 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700380 return result;
381 }
Sunny Goyald2497482015-09-22 18:24:19 -0700382 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
383 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700384 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
385 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700386 return result;
387 }
388 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
389 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800390 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
391 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700392 return result;
393 }
394 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
395 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800396 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
Andras Kloczl953eb802021-10-15 21:16:48 +0100397 mOpenHelper.getNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700398 return result;
399 }
400 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800401 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700402 return null;
403 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800404 case LauncherSettings.Settings.METHOD_SET_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
405 mUseTestWorkspaceLayout = true;
406 return null;
407 }
408 case LauncherSettings.Settings.METHOD_CLEAR_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
409 mUseTestWorkspaceLayout = false;
410 return null;
411 }
Sunny Goyald2497482015-09-22 18:24:19 -0700412 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
413 loadDefaultFavoritesIfNecessary();
414 return null;
415 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700416 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
417 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
418 return null;
419 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700420 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
421 Bundle result = new Bundle();
422 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
423 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
424 return result;
425 }
426 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700427 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
428 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700429 return null;
430 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700431 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
432 mOpenHelper.mHotseatRestoreTableExists = tableExists(
433 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
434 return null;
435 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700436 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700437 final long ts = System.currentTimeMillis();
438 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
439 mLastRestoreTimestamp = ts;
440 RestoreDbTask.restoreIfPossible(
441 getContext(), mOpenHelper, new BackupManager(getContext()));
442 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700443 return null;
444 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800445 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700446 Bundle result = new Bundle();
447 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
448 prepForMigration(
Alex Chaufe9a07b2022-03-08 21:48:34 +0000449 arg /* dbFile */,
Sunny Goyal278939f2021-07-28 14:35:47 -0700450 Favorites.TMP_TABLE,
451 () -> mOpenHelper,
452 () -> DatabaseHelper.createDatabaseHelper(
453 getContext(), true /* forMigration */)));
454 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700455 }
456 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700457 Bundle result = new Bundle();
458 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
459 prepForMigration(
460 arg /* dbFile */,
461 Favorites.PREVIEW_TABLE_NAME,
462 () -> DatabaseHelper.createDatabaseHelper(
463 getContext(), arg, true /* forMigration */),
464 () -> mOpenHelper));
465 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700466 }
467 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
468 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
469 final DatabaseHelper helper = mOpenHelper;
470 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
471 mProviderAuthority = null;
472 } else {
473 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
474 }
475 mOpenHelper = DatabaseHelper.createDatabaseHelper(
476 getContext(), arg, false /* forMigration */);
477 helper.close();
478 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
479 if (app == null) return null;
480 app.getModel().forceReload();
481 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800482 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700483 }
484 return null;
485 }
486
Tracy Zhou7df93d22020-01-27 13:44:06 -0800487 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700488 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800489 }
490
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700491 /**
492 * Deletes any empty folder from the DB.
493 * @return Ids of deleted folders.
494 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700495 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700496 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700497 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700498 // Select folders whose id do not match any container value.
499 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
500 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
501 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
502 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700503 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800504
Alex Chauac038432021-11-04 16:49:59 +0000505 IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Sunny Goyalc5939392018-12-07 11:43:47 -0800506 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700507 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700508 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700509 LauncherSettings.Favorites._ID, folderIds), null);
510 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700511 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800512 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700513 } catch (SQLException ex) {
514 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800515 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700516 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700517 }
518
Adam Cohen091440a2015-03-18 14:16:05 -0700519 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800520 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800521 }
522
Sunny Goyald2497482015-09-22 18:24:19 -0700523 private void clearFlagEmptyDbCreated() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000524 LauncherPrefs.getPrefs(getContext()).edit()
Pinyao Ting96186af2020-07-20 11:03:39 -0700525 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700526 }
527
Sunny Goyal42de82f2014-09-26 22:09:29 -0700528 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700529 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700530 * 1) From the app restrictions
531 * 2) From a package provided by play store
532 * 3) From a partner configuration APK, already in the system image
533 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700534 */
Sunny Goyald2497482015-09-22 18:24:19 -0700535 synchronized private void loadDefaultFavoritesIfNecessary() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000536 SharedPreferences sp = LauncherPrefs.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700537
Pinyao Ting96186af2020-07-20 11:03:39 -0700538 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500539 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200540
Sihua Maaa2b8722022-10-25 15:17:58 -0700541 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
542 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHolder);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700543 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700544 loader = AutoInstallsLayout.get(getContext(), widgetHolder, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700545 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700546 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700547 final Partner partner = Partner.get(getContext().getPackageManager());
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800548 if (partner != null) {
549 int workspaceResId = partner.getXmlResId(RES_PARTNER_DEFAULT_LAYOUT);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700550 if (workspaceResId != 0) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700551 loader = new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800552 mOpenHelper, partner.getResources(), workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700553 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700554 }
555 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700556
Sunny Goyal9d219682014-10-23 14:21:02 -0700557 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700558 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700559 loader = getDefaultLayoutParser(widgetHolder);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700560 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800561
562 // There might be some partially restored DB items, due to buggy restore logic in
563 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800564 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700565 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700566 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
567 && usingExternallyProvidedLayout) {
568 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800569 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700570 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sihua Maaa2b8722022-10-25 15:17:58 -0700571 getDefaultLayoutParser(widgetHolder));
Sunny Goyal9d219682014-10-23 14:21:02 -0700572 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700573 clearFlagEmptyDbCreated();
Sihua Maaa2b8722022-10-25 15:17:58 -0700574 widgetHolder.destroy();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700575 }
576 }
577
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700578 /**
579 * Creates workspace loader from an XML resource listed in the app restrictions.
580 *
581 * @return the loader if the restrictions are set and the resource exists; null otherwise.
582 */
Sihua Maaa2b8722022-10-25 15:17:58 -0700583 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(
584 LauncherWidgetHolder widgetHolder) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700585 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700586 final String authority;
587 if (!TextUtils.isEmpty(mProviderAuthority)) {
588 authority = mProviderAuthority;
589 } else {
590 authority = Settings.Secure.getString(ctx.getContentResolver(),
591 "launcher3.layout.provider");
592 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700593 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700594 return null;
595 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700596
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700597 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
598 if (pi == null) {
599 Log.e(TAG, "No provider found for authority " + authority);
600 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700601 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800602 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700603 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
604 // Read the full xml so that we fail early in case of any IO error.
605 String layout = new String(IOUtils.toByteArray(in));
606 XmlPullParser parser = Xml.newPullParser();
607 parser.setInput(new StringReader(layout));
608
609 Log.d(TAG, "Loading layout from " + authority);
Sihua Maaa2b8722022-10-25 15:17:58 -0700610 return new AutoInstallsLayout(ctx, widgetHolder, mOpenHelper,
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700611 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
612 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
613 } catch (Exception e) {
614 Log.e(TAG, "Error getting layout stream from: " + authority , e);
615 return null;
616 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700617 }
618
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800619 public static Uri getLayoutUri(String authority, Context ctx) {
620 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
621 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
622 .appendQueryParameter("version", "1")
623 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
624 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700625 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800626 .build();
627 }
628
Sihua Maaa2b8722022-10-25 15:17:58 -0700629 private DefaultLayoutParser getDefaultLayoutParser(LauncherWidgetHolder widgetHolder) {
Adam Cohen27824492017-09-22 17:10:55 -0700630 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800631 int defaultLayout = mUseTestWorkspaceLayout
632 ? TEST_WORKSPACE_LAYOUT_RES_XML : idp.defaultLayoutId;
Adam Cohen27824492017-09-22 17:10:55 -0700633
Sunny Goyal337c81f2019-12-10 12:19:13 -0800634 if (getContext().getSystemService(UserManager.class).isDemoUser()
635 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700636 defaultLayout = idp.demoModeLayoutId;
637 }
638
Sihua Maaa2b8722022-10-25 15:17:58 -0700639 return new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal9d219682014-10-23 14:21:02 -0700640 mOpenHelper, getContext().getResources(), defaultLayout);
641 }
642
Sunny Goyald3849d12015-10-29 10:28:32 -0700643 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800644 * The class is subclassed in tests to create an in-memory db.
645 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800646 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
647 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700649 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700650 private int mMaxItemId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700651 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700652 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653
Tracy Zhoued5f3082020-04-20 01:13:26 -0700654 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
655 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700656 }
657
Tracy Zhoued5f3082020-04-20 01:13:26 -0700658 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
659 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700660 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700661 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700662 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700663 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700664 // Table creation sometimes fails silently, which leads to a crash loop.
665 // This way, we will try to create a table every time after crash, so the device
666 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700667 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700668 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
669 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700670 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700671 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700672 databaseHelper.mHotseatRestoreTableExists = tableExists(
673 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700674
Tracy Zhouc0000452020-03-17 18:28:38 -0700675 databaseHelper.initIds();
676 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700677 }
678
679 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700680 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700681 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700682 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800683 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700684 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700685 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700686 }
687
688 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700689 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
690 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700691 if (mMaxItemId == -1) {
692 mMaxItemId = initializeMaxItemId(getWritableDatabase());
693 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800694 }
695
696 @Override
697 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800698 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700699
Adam Cohendcd297f2013-06-18 13:13:40 -0700700 mMaxItemId = 1;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700701
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700702 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800703
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800704 // Fresh and clean launcher DB.
705 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700706 if (!mForMigration) {
707 onEmptyDbCreated();
708 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800709 }
710
Sunny Goyal161a2142018-10-29 14:02:20 -0700711 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700712 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700713 dropTable(db, Favorites.BACKUP_TABLE_NAME);
714 mBackupTableExists = false;
715 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700716 if (mHotseatRestoreTableExists) {
717 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
718 mHotseatRestoreTableExists = false;
719 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700720 }
721
Sunny Goyalf076eae2016-01-11 12:25:10 -0800722 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700723 * Re-composite given key in respect to database. If the current db is
724 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
725 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
726 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
727 */
728 String getKey(final String key) {
729 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
730 return key;
731 }
732 return key + "@" + getDatabaseName();
733 }
734
735 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800736 * Overriden in tests.
737 */
738 protected void onEmptyDbCreated() {
739 // Set the flag for empty DB
Stefan Andonian146701c2022-11-10 23:07:40 +0000740 LauncherPrefs.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
Pinyao Ting96186af2020-07-20 11:03:39 -0700741 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800742 }
743
Jon Miranda2bc6b932019-03-07 15:24:46 -0800744 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800745 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800746 }
747
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700748 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800749 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800750 }
751
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700752 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700753 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700754 }
755
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800756 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700757 public void onOpen(SQLiteDatabase db) {
758 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700759
760 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
761 if (!schemaFile.exists()) {
762 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700763 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800764 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700765 }
766
767 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700768 * One-time data updated before support of onDowngrade was added. This update is backwards
769 * compatible and can safely be run multiple times.
770 * Note: No new logic should be added here after release, as the new logic might not get
771 * executed on an existing device.
772 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700773 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700774 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
775 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800776 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700777 for (UserHandle user : um.getUserProfiles()) {
778 long serial = um.getSerialNumberForUser(user);
779 String sql = "update favorites set intent = replace(intent, "
780 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
781 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700782 }
783 }
784
785 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800786 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700787 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800788 switch (oldVersion) {
789 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800790 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800791 case 12:
792 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800793 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700794 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800795 // Insert new column for holding widget provider name
796 db.execSQL("ALTER TABLE favorites " +
797 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700798 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800799 } catch (SQLException ex) {
800 Log.e(TAG, ex.getMessage(), ex);
801 // Old version remains, which means we wipe old data
802 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800803 }
804 }
805 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800806 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800807 // Old version remains, which means we wipe old data
808 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800809 }
810 }
811 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700812 if (!addIntegerColumn(db, Favorites.RESTORED, 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 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800817 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700818 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800819 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800820 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800821 case 18:
822 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800823 case 19: {
824 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800825 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800826 // Old version remains, which means we wipe old data
827 break;
828 }
829 }
830 case 20:
831 if (!updateFolderItemsRank(db, true)) {
832 break;
833 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800834 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800835 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800836 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700837 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
838 // Old version remains, which means we wipe old data
839 break;
840 }
841 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700842 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700843 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700844 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000845 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700846 case 25:
847 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700848 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700849 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800850 case 27: {
851 // Update the favorites table so that the screen ids are ordered based on
852 // workspace page rank.
Alex Chauac038432021-11-04 16:49:59 +0000853 IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
854 "workspaceScreens", BaseColumns._ID, null, null, "screenRank");
Sunny Goyalc5939392018-12-07 11:43:47 -0800855 int[] original = finalScreens.toArray();
856 Arrays.sort(original);
857 String updatemap = "";
858 for (int i = 0; i < original.length; i++) {
859 if (finalScreens.get(i) != original[i]) {
860 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
861 Favorites.SCREEN, finalScreens.get(i), original[i]);
862 }
863 }
864 if (!TextUtils.isEmpty(updatemap)) {
865 String query = String.format(Locale.ENGLISH,
866 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
867 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
868 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
869 db.execSQL(query);
870 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700871 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800872 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100873 case 28: {
874 boolean columnAdded = addIntegerColumn(
875 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
876 if (!columnAdded) {
877 // Old version remains, which means we wipe old data
878 break;
879 }
880 }
881 case 29: {
Andras Kloczl929e3a22021-09-06 03:30:30 +0100882 // Remove widget panel related leftover workspace items
883 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
884 Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
885 }
886 case 30: {
Alex Chaue09067c2022-01-10 16:13:13 +0000887 if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
888 // Clean up first row in screen 0 as it might contain junk data.
889 Log.d(TAG, "Cleaning up first row");
890 db.delete(Favorites.TABLE_NAME,
891 String.format(Locale.ENGLISH,
892 "%1$s = %2$d AND %3$s = %4$d AND %5$s = %6$d",
893 Favorites.SCREEN, 0,
894 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP,
895 Favorites.CELLY, 0), null);
896 }
897 return;
898 }
899 case 31: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800900 // DB Upgraded successfully
901 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100902 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400903 }
904
Sunny Goyala2cc6242015-01-14 14:23:02 -0800905 // DB was not upgraded
906 Log.w(TAG, "Destroying all old data.");
907 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800908 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800909
Adam Cohen9b1d0622014-05-21 19:01:57 -0700910 @Override
911 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700912 try {
913 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
914 .onDowngrade(db, oldVersion, newVersion);
915 } catch (Exception e) {
916 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
917 ". Wiping databse.", e);
918 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700919 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700920 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700921
Sunny Goyal42de82f2014-09-26 22:09:29 -0700922 /**
923 * Clears all the data for a fresh start.
924 */
925 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700926 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700927 dropTable(db, Favorites.TABLE_NAME);
928 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800929 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700930 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800931 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700932 }
933
Sunny Goyald2f38192015-02-25 10:46:34 -0800934 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700935 * Removes widgets which are registered to the Launcher's host, but are not present
936 * in our model.
937 */
938 public void removeGhostWidgets(SQLiteDatabase db) {
939 // Get all existing widget ids.
Sihua Maaa2b8722022-10-25 15:17:58 -0700940 final LauncherWidgetHolder holder = newLauncherWidgetHolder();
Sunny Goyal55fddc82017-04-06 15:02:52 -0700941 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700942 final int[] allWidgets;
943 try {
944 // Although the method was defined in O, it has existed since the beginning of
945 // time, so it might work on older platforms as well.
946 allWidgets = holder.getAppWidgetIds();
947 } catch (IncompatibleClassChangeError e) {
948 Log.e(TAG, "getAppWidgetIds not supported", e);
949 // Necessary to destroy the holder to free up possible activity context
950 holder.destroy();
951 return;
952 }
953 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
954 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
955 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
956 boolean isAnyWidgetRemoved = false;
957 for (int widgetId : allWidgets) {
958 if (!validWidgets.contains(widgetId)) {
959 try {
960 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
961 holder.deleteAppWidgetId(widgetId);
962 isAnyWidgetRemoved = true;
963 } catch (RuntimeException e) {
964 // Ignore
965 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700966 }
967 }
Sihua Maaa2b8722022-10-25 15:17:58 -0700968 if (isAnyWidgetRemoved) {
969 final String allWidgetsIds = Arrays.stream(allWidgets).mapToObj(String::valueOf)
970 .collect(Collectors.joining(",", "[", "]"));
971 final String validWidgetsIds = Arrays.stream(
972 validWidgets.getArray().toArray()).mapToObj(String::valueOf)
973 .collect(Collectors.joining(",", "[", "]"));
974 FileLog.d(TAG, "One or more widgets was removed. db_path=" + db.getPath()
975 + " allWidgetsIds=" + allWidgetsIds
976 + ", validWidgetsIds=" + validWidgetsIds);
977 }
978 } finally {
979 holder.destroy();
Pinyao Ting7fd7e512022-10-03 17:46:03 -0700980 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700981 }
982
983 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700984 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
985 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
986 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700987 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700988 try (SQLiteTransaction t = new SQLiteTransaction(db);
989 // Only consider the primary user as other users can't have a shortcut.
990 Cursor c = db.query(Favorites.TABLE_NAME,
991 new String[] { Favorites._ID, Favorites.INTENT},
992 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
993 " AND profileId=" + getDefaultUserSerial(),
994 null, null, null, null);
995 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
996 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
997 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700998 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
999 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
1000
1001 while (c.moveToNext()) {
1002 String intentDescription = c.getString(intentIndex);
1003 Intent intent;
1004 try {
1005 intent = Intent.parseUri(intentDescription, 0);
1006 } catch (URISyntaxException e) {
1007 Log.e(TAG, "Unable to parse intent", e);
1008 continue;
1009 }
1010
Sunny Goyal9dbb27c2019-07-17 15:12:56 -07001011 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001012 continue;
1013 }
1014
Sunny Goyalefb7e842018-10-04 15:11:00 -07001015 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001016 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -07001017 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -07001018 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001019 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -07001020 } catch (SQLException ex) {
1021 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001022 }
1023 }
1024
Adam Cohen091440a2015-03-18 14:16:05 -07001025 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001026 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001027 if (addRankColumn) {
1028 // Insert new column for holding rank
1029 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1030 }
1031
1032 // Get a map for folder ID to folder width
1033 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1034 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1035 + " GROUP BY container;",
1036 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1037
1038 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001039 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1040 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001041 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1042 }
1043
1044 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001045 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001046 } catch (SQLException ex) {
1047 // Old version remains, which means we wipe old data
1048 Log.e(TAG, ex.getMessage(), ex);
1049 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001050 }
1051 return true;
1052 }
1053
Sunny Goyal5d85c442015-03-10 13:14:47 -07001054 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001055 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001056 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1057 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001058 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001059 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001060 Log.e(TAG, ex.getMessage(), ex);
1061 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001062 }
1063 return true;
1064 }
1065
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001066 // Generates a new ID to use for an object in your database. This method should be only
1067 // called from the main UI thread. As an exception, we do call it when we call the
1068 // constructor from the worker thread; however, this doesn't extend until after the
1069 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1070 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001071 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001072 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001073 if (mMaxItemId < 0) {
1074 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001075 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001076 mMaxItemId += 1;
1077 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001078 }
1079
Sihua Maaa2b8722022-10-25 15:17:58 -07001080 /**
1081 * @return A new {@link LauncherWidgetHolder} based on the current context
1082 */
1083 @NonNull
1084 public LauncherWidgetHolder newLauncherWidgetHolder() {
1085 return new LauncherWidgetHolder(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001086 }
1087
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001088 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001089 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001090 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001091 }
1092
Sunny Goyalc5939392018-12-07 11:43:47 -08001093 public void checkId(ContentValues values) {
1094 int id = values.getAsInteger(Favorites._ID);
1095 mMaxItemId = Math.max(id, mMaxItemId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001096 }
1097
Sunny Goyalefb7e842018-10-04 15:11:00 -07001098 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001099 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001100 }
1101
Andras Kloczl953eb802021-10-15 21:16:48 +01001102 // Returns a new ID to use for an workspace screen in your database that is greater than all
1103 // existing screen IDs.
1104 private int getNewScreenId() {
1105 return getMaxId(getWritableDatabase(),
1106 "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001107 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Andras Kloczl953eb802021-10-15 21:16:48 +01001108 Favorites.CONTAINER_DESKTOP) + 1;
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001109 }
1110
Adam Cohen091440a2015-03-18 14:16:05 -07001111 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001112 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001113 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001114
1115 // Ensure that the max ids are initialized
1116 mMaxItemId = initializeMaxItemId(db);
Adam Cohen71483f42014-05-15 14:04:01 -07001117 return count;
1118 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001119 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001120
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001121 /**
1122 * @return the max _id in the provided table.
1123 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001124 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001125 int max = 0;
1126 try (SQLiteStatement prog = db.compileStatement(
1127 String.format(Locale.ENGLISH, query, args))) {
1128 max = (int) DatabaseUtils.longForQuery(prog, null);
1129 if (max < 0) {
1130 throw new RuntimeException("Error: could not query max id");
1131 }
1132 } catch (IllegalArgumentException exception) {
1133 String message = exception.getMessage();
1134 if (message.contains("re-open") && message.contains("already-closed")) {
1135 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1136 } else {
1137 throw exception;
1138 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001139 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001140 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001141 }
1142
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001143 static class SqlArguments {
1144 public final String table;
1145 public final String where;
1146 public final String[] args;
1147
1148 SqlArguments(Uri url, String where, String[] args) {
1149 if (url.getPathSegments().size() == 1) {
1150 this.table = url.getPathSegments().get(0);
1151 this.where = where;
1152 this.args = args;
1153 } else if (url.getPathSegments().size() != 2) {
1154 throw new IllegalArgumentException("Invalid URI: " + url);
1155 } else if (!TextUtils.isEmpty(where)) {
1156 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1157 } else {
1158 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001159 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001160 this.args = null;
1161 }
1162 }
1163
1164 SqlArguments(Uri url) {
1165 if (url.getPathSegments().size() == 1) {
1166 table = url.getPathSegments().get(0);
1167 where = null;
1168 args = null;
1169 } else {
1170 throw new IllegalArgumentException("Invalid URI: " + url);
1171 }
1172 }
1173 }
Adam Cohen72960972014-01-15 18:13:55 -08001174}