blob: d1fa764080e0c93b5938ce252e5d4e2a79bd16ee [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;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080038import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070042import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070044import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070045import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070046import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080048import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080049import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080050import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070051import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080053import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070054import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070055
Sihua Maaa2b8722022-10-25 15:17:58 -070056import androidx.annotation.NonNull;
57
Sunny Goyal0fe505b2014-08-06 09:55:36 -070058import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
59import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080061import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070062import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyal337c81f2019-12-10 12:19:13 -080063import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070064import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070065import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070066import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070067import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070068import com.android.launcher3.util.IntArray;
69import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080070import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070071import com.android.launcher3.util.PackageManagerHelper;
Sunny Goyal3e58eea2022-11-14 14:30:07 -080072import com.android.launcher3.util.Partner;
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;
Tracy Zhouc0000452020-03-17 18:28:38 -070087import java.util.function.Supplier;
Pinyao Ting7fd7e512022-10-03 17:46:03 -070088import java.util.stream.Collectors;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070091 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080092 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Sunny Goyal05f30882017-05-03 12:42:18 -070094 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
95
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070096 /**
97 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080098 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070099 */
Alex Chaue09067c2022-01-10 16:13:13 +0000100 public static final int SCHEMA_VERSION = 31;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800102 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Pinyao Ting96186af2020-07-20 11:03:39 -0700103 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700104
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800105 private static final int TEST_WORKSPACE_LAYOUT_RES_XML = R.xml.default_test_workspace;
Alex Chauf8b79d42022-12-15 13:41:49 +0000106 private static final int TEST2_WORKSPACE_LAYOUT_RES_XML = R.xml.default_test2_workspace;
Sebastian Franco239ae0a2023-03-03 15:56:52 -0800107 private static final int TAPL_WORKSPACE_LAYOUT_RES_XML = R.xml.default_tapl_test_workspace;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800108
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
Alex Chauf8b79d42022-12-15 13:41:49 +0000114 private int mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800115
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800116 /**
117 * $ adb shell dumpsys activity provider com.android.launcher3
118 */
119 @Override
120 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
121 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
122 if (appState == null || !appState.getModel().isModelLoaded()) {
123 return;
124 }
125 appState.getModel().dumpState("", fd, writer, args);
126 }
127
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 @Override
129 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800130 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700131 Log.d(TAG, "Launcher process started");
132 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700133
Sunny Goyalfdbef272017-02-01 12:52:54 -0800134 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800135 // is the first component to get created.
136 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137 return true;
138 }
139
140 @Override
141 public String getType(Uri uri) {
142 SqlArguments args = new SqlArguments(uri, null, null);
143 if (TextUtils.isEmpty(args.where)) {
144 return "vnd.android.cursor.dir/" + args.table;
145 } else {
146 return "vnd.android.cursor.item/" + args.table;
147 }
148 }
149
Sunny Goyalf076eae2016-01-11 12:25:10 -0800150 /**
151 * Overridden in tests
152 */
153 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700154 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700155 mOpenHelper = DatabaseHelper.createDatabaseHelper(
156 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700157
Sunny Goyal68031ca2021-08-02 12:23:44 -0700158 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700159 }
160 }
161
Tracy Zhouc0000452020-03-17 18:28:38 -0700162 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
163 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
164 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Alex Chau0adc3662022-07-04 13:05:38 +0100165 Log.e(TAG, "prepForMigration - target db is same as current: " + dbFile);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800166 return false;
167 }
168
Tracy Zhouc0000452020-03-17 18:28:38 -0700169 final DatabaseHelper helper = src.get();
170 mOpenHelper = dst.get();
171 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
172 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
173 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800174 return true;
175 }
176
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800177 @Override
178 public Cursor query(Uri uri, String[] projection, String selection,
179 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700180 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181
182 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
183 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
184 qb.setTables(args.table);
185
Romain Guy73b979d2009-06-09 12:57:21 -0700186 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800187 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700188 final Bundle extra = new Bundle();
189 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
190 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 result.setNotificationUri(getContext().getContentResolver(), uri);
192
193 return result;
194 }
195
Sunny Goyalefb7e842018-10-04 15:11:00 -0700196 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700197 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500198 if (values == null) {
199 throw new RuntimeException("Error: attempting to insert null values");
200 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800201 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 throw new RuntimeException("Error: attempting to add item without specifying an id");
203 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800204 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700205 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700206 }
207
Sunny Goyald1064182015-08-13 12:08:30 -0700208 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800209 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700210 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
211 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800212 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700213 }
214 }
215 }
216
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 @Override
218 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700219 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 SqlArguments args = new SqlArguments(uri);
221
Sunny Goyald1064182015-08-13 12:08:30 -0700222 // In very limited cases, we support system|signature permission apps to modify the db.
223 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700224 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700225 return null;
226 }
227 }
228
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400230 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700231 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800232 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800233 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234
235 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800236 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237 return uri;
238 }
239
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700240 private boolean initializeExternalAdd(ContentValues values) {
241 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700242 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700243 values.put(LauncherSettings.Favorites._ID, id);
244
245 // 2. In the case of an app widget, and if no app widget id is specified, we
246 // attempt allocate and bind the widget.
247 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
248 if (itemType != null &&
249 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
250 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
251
252 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
253 ComponentName cn = ComponentName.unflattenFromString(
254 values.getAsString(Favorites.APPWIDGET_PROVIDER));
255
256 if (cn != null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700257 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700258 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700259 int appWidgetId = widgetHolder.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700260 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
261 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700262 widgetHolder.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700263 return false;
264 }
265 } catch (RuntimeException e) {
266 Log.e(TAG, "Failed to initialize external widget", e);
267 return false;
Sihua Maaa2b8722022-10-25 15:17:58 -0700268 } finally {
269 // Necessary to destroy the holder to free up possible activity context
270 widgetHolder.destroy();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700271 }
272 } else {
273 return false;
274 }
275 }
276
Sunny Goyalc5939392018-12-07 11:43:47 -0800277 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700278 }
279
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800280 @Override
281 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700282 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800283 SqlArguments args = new SqlArguments(uri);
284
285 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700286 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 int numValues = values.length;
288 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400289 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700290 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
291 return 0;
292 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800293 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800294 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700295 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800296 }
297
Sunny Goyald1064182015-08-13 12:08:30 -0700298 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 return values.length;
300 }
301
Sunny Goyal161a2142018-10-29 14:02:20 -0700302 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 @Override
Yura085c8532014-02-11 15:15:29 +0000304 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
305 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700306 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700307 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800308 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700309
310 final int numOperations = operations.size();
311 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
312 for (int i = 0; i < numOperations; i++) {
313 ContentProviderOperation op = operations.get(i);
314 results[i] = op.apply(this, results, i);
315
316 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
317 results[i].count != null && results[i].count > 0;
318 }
319 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800320 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700321 }
322
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700323 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700324 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700325 return results;
Yura085c8532014-02-11 15:15:29 +0000326 }
327 }
328
329 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700331 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
333
334 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335
Louis Begina9c21c62016-08-15 15:18:41 -0700336 if (Binder.getCallingPid() != Process.myPid()
337 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700338 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700339 }
340 int count = db.delete(args.table, args.where, args.args);
341 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800342 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700343 reloadLauncherIfExternal();
344 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 return count;
346 }
347
348 @Override
349 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700350 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
352
Chris Wren1ada10d2013-09-13 18:01:38 -0400353 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
355 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700356 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 return count;
358 }
359
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700361 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 if (Binder.getCallingUid() != Process.myUid()) {
363 return null;
364 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700365 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700366
367 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700368 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
369 clearFlagEmptyDbCreated();
370 return null;
371 }
372 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
373 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700374 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
375 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700376 return result;
377 }
378 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
379 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800380 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
381 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700382 return result;
383 }
384 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
385 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800386 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
Andras Kloczl953eb802021-10-15 21:16:48 +0100387 mOpenHelper.getNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700388 return result;
389 }
390 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800391 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700392 return null;
393 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800394 case LauncherSettings.Settings.METHOD_SET_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000395 switch (arg) {
396 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST:
397 mDefaultWorkspaceLayoutOverride = TEST_WORKSPACE_LAYOUT_RES_XML;
398 break;
399 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST2:
400 mDefaultWorkspaceLayoutOverride = TEST2_WORKSPACE_LAYOUT_RES_XML;
401 break;
Sebastian Franco239ae0a2023-03-03 15:56:52 -0800402 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TAPL:
403 mDefaultWorkspaceLayoutOverride = TAPL_WORKSPACE_LAYOUT_RES_XML;
404 break;
Alex Chauf8b79d42022-12-15 13:41:49 +0000405 default:
406 mDefaultWorkspaceLayoutOverride = 0;
407 break;
408 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800409 return null;
410 }
411 case LauncherSettings.Settings.METHOD_CLEAR_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000412 mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800413 return null;
414 }
Sunny Goyald2497482015-09-22 18:24:19 -0700415 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
416 loadDefaultFavoritesIfNecessary();
417 return null;
418 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700419 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
420 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
421 return null;
422 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700423 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
424 Bundle result = new Bundle();
425 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
426 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
427 return result;
428 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700429 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
430 mOpenHelper.mHotseatRestoreTableExists = tableExists(
431 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
432 return null;
433 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800434 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700435 Bundle result = new Bundle();
436 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
437 prepForMigration(
Alex Chaufe9a07b2022-03-08 21:48:34 +0000438 arg /* dbFile */,
Sunny Goyal278939f2021-07-28 14:35:47 -0700439 Favorites.TMP_TABLE,
440 () -> mOpenHelper,
441 () -> DatabaseHelper.createDatabaseHelper(
442 getContext(), true /* forMigration */)));
443 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700444 }
445 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700446 Bundle result = new Bundle();
447 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
448 prepForMigration(
449 arg /* dbFile */,
450 Favorites.PREVIEW_TABLE_NAME,
451 () -> DatabaseHelper.createDatabaseHelper(
452 getContext(), arg, true /* forMigration */),
453 () -> mOpenHelper));
454 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700455 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700456 }
457 return null;
458 }
459
Tracy Zhou7df93d22020-01-27 13:44:06 -0800460 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700461 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800462 }
463
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700464 /**
465 * Deletes any empty folder from the DB.
466 * @return Ids of deleted folders.
467 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700468 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700469 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700470 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700471 // Select folders whose id do not match any container value.
472 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
473 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
474 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
475 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800477
Alex Chauac038432021-11-04 16:49:59 +0000478 IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Sunny Goyalc5939392018-12-07 11:43:47 -0800479 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700480 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700481 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700482 LauncherSettings.Favorites._ID, folderIds), null);
483 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700484 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800485 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700486 } catch (SQLException ex) {
487 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800488 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700489 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700490 }
491
Adam Cohen091440a2015-03-18 14:16:05 -0700492 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800493 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800494 }
495
Sunny Goyald2497482015-09-22 18:24:19 -0700496 private void clearFlagEmptyDbCreated() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000497 LauncherPrefs.getPrefs(getContext()).edit()
Pinyao Ting96186af2020-07-20 11:03:39 -0700498 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700499 }
500
Sunny Goyal42de82f2014-09-26 22:09:29 -0700501 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 * 1) From the app restrictions
504 * 2) From a package provided by play store
505 * 3) From a partner configuration APK, already in the system image
506 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700507 */
Sunny Goyald2497482015-09-22 18:24:19 -0700508 synchronized private void loadDefaultFavoritesIfNecessary() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000509 SharedPreferences sp = LauncherPrefs.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700510
Pinyao Ting96186af2020-07-20 11:03:39 -0700511 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500512 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200513
Sihua Maaa2b8722022-10-25 15:17:58 -0700514 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sihua Macdb3c0a2023-02-13 15:12:32 -0800515 try {
516 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHolder);
517 if (loader == null) {
518 loader = AutoInstallsLayout.get(getContext(), widgetHolder, mOpenHelper);
519 }
520 if (loader == null) {
521 final Partner partner = Partner.get(getContext().getPackageManager());
522 if (partner != null) {
523 int workspaceResId = partner.getXmlResId(RES_PARTNER_DEFAULT_LAYOUT);
524 if (workspaceResId != 0) {
525 loader = new DefaultLayoutParser(getContext(), widgetHolder,
526 mOpenHelper, partner.getResources(), workspaceResId);
527 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700528 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700529 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700530
Sihua Macdb3c0a2023-02-13 15:12:32 -0800531 final boolean usingExternallyProvidedLayout = loader != null;
532 if (loader == null) {
533 loader = getDefaultLayoutParser(widgetHolder);
534 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800535
Sihua Macdb3c0a2023-02-13 15:12:32 -0800536 // There might be some partially restored DB items, due to buggy restore logic in
537 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800538 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sihua Macdb3c0a2023-02-13 15:12:32 -0800539 // Populate favorites table with initial favorites
540 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
541 && usingExternallyProvidedLayout) {
542 // Unable to load external layout. Cleanup and load the internal layout.
543 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
544 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
545 getDefaultLayoutParser(widgetHolder));
546 }
547 clearFlagEmptyDbCreated();
548 } finally {
549 widgetHolder.destroy();
Sunny Goyal9d219682014-10-23 14:21:02 -0700550 }
Michael Jurkab85f8a42012-04-25 15:48:32 -0700551 }
552 }
553
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700554 /**
555 * Creates workspace loader from an XML resource listed in the app restrictions.
556 *
557 * @return the loader if the restrictions are set and the resource exists; null otherwise.
558 */
Sihua Maaa2b8722022-10-25 15:17:58 -0700559 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(
560 LauncherWidgetHolder widgetHolder) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700561 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700562 final String authority;
563 if (!TextUtils.isEmpty(mProviderAuthority)) {
564 authority = mProviderAuthority;
565 } else {
566 authority = Settings.Secure.getString(ctx.getContentResolver(),
567 "launcher3.layout.provider");
568 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700569 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700570 return null;
571 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700572
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700573 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
574 if (pi == null) {
575 Log.e(TAG, "No provider found for authority " + authority);
576 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700577 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800578 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700579 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
580 // Read the full xml so that we fail early in case of any IO error.
581 String layout = new String(IOUtils.toByteArray(in));
582 XmlPullParser parser = Xml.newPullParser();
583 parser.setInput(new StringReader(layout));
584
585 Log.d(TAG, "Loading layout from " + authority);
Sihua Maaa2b8722022-10-25 15:17:58 -0700586 return new AutoInstallsLayout(ctx, widgetHolder, mOpenHelper,
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700587 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
588 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
589 } catch (Exception e) {
590 Log.e(TAG, "Error getting layout stream from: " + authority , e);
591 return null;
592 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700593 }
594
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800595 public static Uri getLayoutUri(String authority, Context ctx) {
596 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
597 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
598 .appendQueryParameter("version", "1")
599 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
600 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700601 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800602 .build();
603 }
604
Sihua Maaa2b8722022-10-25 15:17:58 -0700605 private DefaultLayoutParser getDefaultLayoutParser(LauncherWidgetHolder widgetHolder) {
Adam Cohen27824492017-09-22 17:10:55 -0700606 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
Alex Chauf8b79d42022-12-15 13:41:49 +0000607 int defaultLayout = mDefaultWorkspaceLayoutOverride > 0
608 ? mDefaultWorkspaceLayoutOverride : idp.defaultLayoutId;
Adam Cohen27824492017-09-22 17:10:55 -0700609
Sunny Goyal337c81f2019-12-10 12:19:13 -0800610 if (getContext().getSystemService(UserManager.class).isDemoUser()
611 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700612 defaultLayout = idp.demoModeLayoutId;
613 }
614
Sihua Maaa2b8722022-10-25 15:17:58 -0700615 return new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal9d219682014-10-23 14:21:02 -0700616 mOpenHelper, getContext().getResources(), defaultLayout);
617 }
618
Sunny Goyald3849d12015-10-29 10:28:32 -0700619 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800620 * The class is subclassed in tests to create an in-memory db.
621 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800622 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
623 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700625 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700626 private int mMaxItemId = -1;
Samuel Fufaf667a132020-05-29 14:47:42 -0700627 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628
Tracy Zhoued5f3082020-04-20 01:13:26 -0700629 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
630 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700631 }
632
Tracy Zhoued5f3082020-04-20 01:13:26 -0700633 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
634 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700635 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700636 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700637 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700638 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700639 // Table creation sometimes fails silently, which leads to a crash loop.
640 // This way, we will try to create a table every time after crash, so the device
641 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700642 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700643 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
644 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700645 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700646 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700647 databaseHelper.mHotseatRestoreTableExists = tableExists(
648 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700649
Tracy Zhouc0000452020-03-17 18:28:38 -0700650 databaseHelper.initIds();
651 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700652 }
653
654 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700655 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700656 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700657 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800658 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700659 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700660 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700661 }
662
663 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700664 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
665 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700666 if (mMaxItemId == -1) {
667 mMaxItemId = initializeMaxItemId(getWritableDatabase());
668 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800669 }
670
671 @Override
672 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800673 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700674
Adam Cohendcd297f2013-06-18 13:13:40 -0700675 mMaxItemId = 1;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700676
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700677 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800678
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800679 // Fresh and clean launcher DB.
680 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700681 if (!mForMigration) {
682 onEmptyDbCreated();
683 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800684 }
685
Sunny Goyal161a2142018-10-29 14:02:20 -0700686 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Samuel Fufaf667a132020-05-29 14:47:42 -0700687 if (mHotseatRestoreTableExists) {
688 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
689 mHotseatRestoreTableExists = false;
690 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700691 }
692
Sunny Goyalf076eae2016-01-11 12:25:10 -0800693 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700694 * Re-composite given key in respect to database. If the current db is
695 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
696 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
697 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
698 */
699 String getKey(final String key) {
700 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
701 return key;
702 }
703 return key + "@" + getDatabaseName();
704 }
705
706 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800707 * Overriden in tests.
708 */
709 protected void onEmptyDbCreated() {
710 // Set the flag for empty DB
Stefan Andonian146701c2022-11-10 23:07:40 +0000711 LauncherPrefs.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
Pinyao Ting96186af2020-07-20 11:03:39 -0700712 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800713 }
714
Jon Miranda2bc6b932019-03-07 15:24:46 -0800715 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800716 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800717 }
718
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700719 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800720 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800721 }
722
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700723 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700724 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700725 }
726
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800727 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700728 public void onOpen(SQLiteDatabase db) {
729 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700730
731 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
732 if (!schemaFile.exists()) {
733 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700734 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800735 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700736 }
737
738 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700739 * One-time data updated before support of onDowngrade was added. This update is backwards
740 * compatible and can safely be run multiple times.
741 * Note: No new logic should be added here after release, as the new logic might not get
742 * executed on an existing device.
743 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700744 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700745 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
746 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800747 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700748 for (UserHandle user : um.getUserProfiles()) {
749 long serial = um.getSerialNumberForUser(user);
750 String sql = "update favorites set intent = replace(intent, "
751 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
752 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700753 }
754 }
755
756 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700758 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800759 switch (oldVersion) {
760 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800761 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800762 case 12:
763 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700765 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800766 // Insert new column for holding widget provider name
767 db.execSQL("ALTER TABLE favorites " +
768 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700769 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800770 } catch (SQLException ex) {
771 Log.e(TAG, ex.getMessage(), ex);
772 // Old version remains, which means we wipe old data
773 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800774 }
775 }
776 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800777 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800778 // Old version remains, which means we wipe old data
779 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800780 }
781 }
782 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700783 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800784 // Old version remains, which means we wipe old data
785 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800786 }
787 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800788 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700789 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800790 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800791 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800792 case 18:
793 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 case 19: {
795 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800796 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800797 // Old version remains, which means we wipe old data
798 break;
799 }
800 }
801 case 20:
802 if (!updateFolderItemsRank(db, true)) {
803 break;
804 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800805 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800806 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800807 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700808 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
809 // Old version remains, which means we wipe old data
810 break;
811 }
812 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700813 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700814 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700815 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000816 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700817 case 25:
818 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700819 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700820 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800821 case 27: {
822 // Update the favorites table so that the screen ids are ordered based on
823 // workspace page rank.
Alex Chauac038432021-11-04 16:49:59 +0000824 IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
825 "workspaceScreens", BaseColumns._ID, null, null, "screenRank");
Sunny Goyalc5939392018-12-07 11:43:47 -0800826 int[] original = finalScreens.toArray();
827 Arrays.sort(original);
828 String updatemap = "";
829 for (int i = 0; i < original.length; i++) {
830 if (finalScreens.get(i) != original[i]) {
831 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
832 Favorites.SCREEN, finalScreens.get(i), original[i]);
833 }
834 }
835 if (!TextUtils.isEmpty(updatemap)) {
836 String query = String.format(Locale.ENGLISH,
837 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
838 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
839 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
840 db.execSQL(query);
841 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700842 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800843 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100844 case 28: {
845 boolean columnAdded = addIntegerColumn(
846 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
847 if (!columnAdded) {
848 // Old version remains, which means we wipe old data
849 break;
850 }
851 }
852 case 29: {
Andras Kloczl929e3a22021-09-06 03:30:30 +0100853 // Remove widget panel related leftover workspace items
854 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
855 Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
856 }
857 case 30: {
Alex Chaue09067c2022-01-10 16:13:13 +0000858 if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
859 // Clean up first row in screen 0 as it might contain junk data.
860 Log.d(TAG, "Cleaning up first row");
861 db.delete(Favorites.TABLE_NAME,
862 String.format(Locale.ENGLISH,
863 "%1$s = %2$d AND %3$s = %4$d AND %5$s = %6$d",
864 Favorites.SCREEN, 0,
865 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP,
866 Favorites.CELLY, 0), null);
867 }
868 return;
869 }
870 case 31: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800871 // DB Upgraded successfully
872 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100873 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400874 }
875
Sunny Goyala2cc6242015-01-14 14:23:02 -0800876 // DB was not upgraded
877 Log.w(TAG, "Destroying all old data.");
878 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800879 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800880
Adam Cohen9b1d0622014-05-21 19:01:57 -0700881 @Override
882 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700883 try {
884 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
885 .onDowngrade(db, oldVersion, newVersion);
886 } catch (Exception e) {
887 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
888 ". Wiping databse.", e);
889 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700890 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700891 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700892
Sunny Goyal42de82f2014-09-26 22:09:29 -0700893 /**
894 * Clears all the data for a fresh start.
895 */
896 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700897 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700898 dropTable(db, Favorites.TABLE_NAME);
899 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800900 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700901 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800902 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700903 }
904
Sunny Goyald2f38192015-02-25 10:46:34 -0800905 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700906 * Removes widgets which are registered to the Launcher's host, but are not present
907 * in our model.
908 */
909 public void removeGhostWidgets(SQLiteDatabase db) {
910 // Get all existing widget ids.
Sihua Maaa2b8722022-10-25 15:17:58 -0700911 final LauncherWidgetHolder holder = newLauncherWidgetHolder();
Sunny Goyal55fddc82017-04-06 15:02:52 -0700912 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700913 final int[] allWidgets;
914 try {
915 // Although the method was defined in O, it has existed since the beginning of
916 // time, so it might work on older platforms as well.
917 allWidgets = holder.getAppWidgetIds();
918 } catch (IncompatibleClassChangeError e) {
919 Log.e(TAG, "getAppWidgetIds not supported", e);
Sihua Maaa2b8722022-10-25 15:17:58 -0700920 return;
921 }
922 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
923 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
924 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
925 boolean isAnyWidgetRemoved = false;
926 for (int widgetId : allWidgets) {
927 if (!validWidgets.contains(widgetId)) {
928 try {
929 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
930 holder.deleteAppWidgetId(widgetId);
931 isAnyWidgetRemoved = true;
932 } catch (RuntimeException e) {
933 // Ignore
934 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700935 }
936 }
Sihua Maaa2b8722022-10-25 15:17:58 -0700937 if (isAnyWidgetRemoved) {
938 final String allWidgetsIds = Arrays.stream(allWidgets).mapToObj(String::valueOf)
939 .collect(Collectors.joining(",", "[", "]"));
940 final String validWidgetsIds = Arrays.stream(
941 validWidgets.getArray().toArray()).mapToObj(String::valueOf)
942 .collect(Collectors.joining(",", "[", "]"));
943 FileLog.d(TAG, "One or more widgets was removed. db_path=" + db.getPath()
944 + " allWidgetsIds=" + allWidgetsIds
945 + ", validWidgetsIds=" + validWidgetsIds);
946 }
947 } finally {
948 holder.destroy();
Pinyao Ting7fd7e512022-10-03 17:46:03 -0700949 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700950 }
951
952 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700953 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
954 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
955 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700956 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700957 try (SQLiteTransaction t = new SQLiteTransaction(db);
958 // Only consider the primary user as other users can't have a shortcut.
959 Cursor c = db.query(Favorites.TABLE_NAME,
960 new String[] { Favorites._ID, Favorites.INTENT},
961 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
962 " AND profileId=" + getDefaultUserSerial(),
963 null, null, null, null);
964 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
965 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
966 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700967 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
968 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
969
970 while (c.moveToNext()) {
971 String intentDescription = c.getString(intentIndex);
972 Intent intent;
973 try {
974 intent = Intent.parseUri(intentDescription, 0);
975 } catch (URISyntaxException e) {
976 Log.e(TAG, "Unable to parse intent", e);
977 continue;
978 }
979
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700980 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700981 continue;
982 }
983
Sunny Goyalefb7e842018-10-04 15:11:00 -0700984 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700985 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700986 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700987 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700988 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700989 } catch (SQLException ex) {
990 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700991 }
992 }
993
Adam Cohen091440a2015-03-18 14:16:05 -0700994 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700995 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800996 if (addRankColumn) {
997 // Insert new column for holding rank
998 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
999 }
1000
1001 // Get a map for folder ID to folder width
1002 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1003 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1004 + " GROUP BY container;",
1005 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1006
1007 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001008 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1009 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001010 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1011 }
1012
1013 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001014 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001015 } catch (SQLException ex) {
1016 // Old version remains, which means we wipe old data
1017 Log.e(TAG, ex.getMessage(), ex);
1018 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001019 }
1020 return true;
1021 }
1022
Sunny Goyal5d85c442015-03-10 13:14:47 -07001023 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001024 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001025 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1026 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001027 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001028 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001029 Log.e(TAG, ex.getMessage(), ex);
1030 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001031 }
1032 return true;
1033 }
1034
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001035 // Generates a new ID to use for an object in your database. This method should be only
1036 // called from the main UI thread. As an exception, we do call it when we call the
1037 // constructor from the worker thread; however, this doesn't extend until after the
1038 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1039 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001040 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001041 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001042 if (mMaxItemId < 0) {
1043 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001044 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001045 mMaxItemId += 1;
1046 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001047 }
1048
Sihua Maaa2b8722022-10-25 15:17:58 -07001049 /**
1050 * @return A new {@link LauncherWidgetHolder} based on the current context
1051 */
1052 @NonNull
1053 public LauncherWidgetHolder newLauncherWidgetHolder() {
Sihua Ma1db8bc22022-11-08 17:13:13 -08001054 return LauncherWidgetHolder.newInstance(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001055 }
1056
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001057 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001058 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001059 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001060 }
1061
Sunny Goyalc5939392018-12-07 11:43:47 -08001062 public void checkId(ContentValues values) {
1063 int id = values.getAsInteger(Favorites._ID);
1064 mMaxItemId = Math.max(id, mMaxItemId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001065 }
1066
Sunny Goyalefb7e842018-10-04 15:11:00 -07001067 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001068 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001069 }
1070
Andras Kloczl953eb802021-10-15 21:16:48 +01001071 // Returns a new ID to use for an workspace screen in your database that is greater than all
1072 // existing screen IDs.
1073 private int getNewScreenId() {
1074 return getMaxId(getWritableDatabase(),
1075 "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001076 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Andras Kloczl953eb802021-10-15 21:16:48 +01001077 Favorites.CONTAINER_DESKTOP) + 1;
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001078 }
1079
Adam Cohen091440a2015-03-18 14:16:05 -07001080 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001081 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001082 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001083
1084 // Ensure that the max ids are initialized
1085 mMaxItemId = initializeMaxItemId(db);
Adam Cohen71483f42014-05-15 14:04:01 -07001086 return count;
1087 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001088 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001089
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001090 /**
1091 * @return the max _id in the provided table.
1092 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001093 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001094 int max = 0;
1095 try (SQLiteStatement prog = db.compileStatement(
1096 String.format(Locale.ENGLISH, query, args))) {
1097 max = (int) DatabaseUtils.longForQuery(prog, null);
1098 if (max < 0) {
1099 throw new RuntimeException("Error: could not query max id");
1100 }
1101 } catch (IllegalArgumentException exception) {
1102 String message = exception.getMessage();
1103 if (message.contains("re-open") && message.contains("already-closed")) {
1104 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1105 } else {
1106 throw exception;
1107 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001108 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001109 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001110 }
1111
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001112 static class SqlArguments {
1113 public final String table;
1114 public final String where;
1115 public final String[] args;
1116
1117 SqlArguments(Uri url, String where, String[] args) {
1118 if (url.getPathSegments().size() == 1) {
1119 this.table = url.getPathSegments().get(0);
1120 this.where = where;
1121 this.args = args;
1122 } else if (url.getPathSegments().size() != 2) {
1123 throw new IllegalArgumentException("Invalid URI: " + url);
1124 } else if (!TextUtils.isEmpty(where)) {
1125 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1126 } else {
1127 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001128 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001129 this.args = null;
1130 }
1131 }
1132
1133 SqlArguments(Uri url) {
1134 if (url.getPathSegments().size() == 1) {
1135 table = url.getPathSegments().get(0);
1136 where = null;
1137 args = null;
1138 } else {
1139 throw new IllegalArgumentException("Invalid URI: " + url);
1140 }
1141 }
1142 }
Adam Cohen72960972014-01-15 18:13:55 -08001143}