blob: 1368de9fc574e49592fd66c9e33645f4c16a9bd8 [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;
Alex Chauf8b79d42022-12-15 13:41:49 +0000109 private static final int TEST2_WORKSPACE_LAYOUT_RES_XML = R.xml.default_test2_workspace;
Sebastian Franco239ae0a2023-03-03 15:56:52 -0800110 private static final int TAPL_WORKSPACE_LAYOUT_RES_XML = R.xml.default_tapl_test_workspace;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800111
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800112 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
Sunny Goyalf076eae2016-01-11 12:25:10 -0800114 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700115 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116
Pinyao Ting0807c942020-04-28 13:58:45 -0700117 private long mLastRestoreTimestamp = 0L;
118
Alex Chauf8b79d42022-12-15 13:41:49 +0000119 private int mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800120
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800121 /**
122 * $ adb shell dumpsys activity provider com.android.launcher3
123 */
124 @Override
125 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
126 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
127 if (appState == null || !appState.getModel().isModelLoaded()) {
128 return;
129 }
130 appState.getModel().dumpState("", fd, writer, args);
131 }
132
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 @Override
134 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800135 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700136 Log.d(TAG, "Launcher process started");
137 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700138
Sunny Goyalfdbef272017-02-01 12:52:54 -0800139 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800140 // is the first component to get created.
141 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800142 return true;
143 }
144
145 @Override
146 public String getType(Uri uri) {
147 SqlArguments args = new SqlArguments(uri, null, null);
148 if (TextUtils.isEmpty(args.where)) {
149 return "vnd.android.cursor.dir/" + args.table;
150 } else {
151 return "vnd.android.cursor.item/" + args.table;
152 }
153 }
154
Sunny Goyalf076eae2016-01-11 12:25:10 -0800155 /**
156 * Overridden in tests
157 */
158 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700159 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700160 mOpenHelper = DatabaseHelper.createDatabaseHelper(
161 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700162
Sunny Goyal68031ca2021-08-02 12:23:44 -0700163 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700164 }
165 }
166
Tracy Zhouc0000452020-03-17 18:28:38 -0700167 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
168 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
169 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Alex Chau0adc3662022-07-04 13:05:38 +0100170 Log.e(TAG, "prepForMigration - target db is same as current: " + dbFile);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800171 return false;
172 }
173
Tracy Zhouc0000452020-03-17 18:28:38 -0700174 final DatabaseHelper helper = src.get();
175 mOpenHelper = dst.get();
176 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
177 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
178 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800179 return true;
180 }
181
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 @Override
183 public Cursor query(Uri uri, String[] projection, String selection,
184 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700185 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186
187 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
188 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
189 qb.setTables(args.table);
190
Romain Guy73b979d2009-06-09 12:57:21 -0700191 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700193 final Bundle extra = new Bundle();
194 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
195 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196 result.setNotificationUri(getContext().getContentResolver(), uri);
197
198 return result;
199 }
200
Sunny Goyalefb7e842018-10-04 15:11:00 -0700201 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500203 if (values == null) {
204 throw new RuntimeException("Error: attempting to insert null values");
205 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800206 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700207 throw new RuntimeException("Error: attempting to add item without specifying an id");
208 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800209 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700210 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700211 }
212
Sunny Goyald1064182015-08-13 12:08:30 -0700213 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800214 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700215 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
216 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800217 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700218 }
219 }
220 }
221
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222 @Override
223 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700224 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225 SqlArguments args = new SqlArguments(uri);
226
Sunny Goyald1064182015-08-13 12:08:30 -0700227 // In very limited cases, we support system|signature permission apps to modify the db.
228 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700229 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700230 return null;
231 }
232 }
233
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400235 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700236 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800237 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800238 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800239
240 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800241 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 return uri;
243 }
244
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700245 private boolean initializeExternalAdd(ContentValues values) {
246 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700247 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700248 values.put(LauncherSettings.Favorites._ID, id);
249
250 // 2. In the case of an app widget, and if no app widget id is specified, we
251 // attempt allocate and bind the widget.
252 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
253 if (itemType != null &&
254 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
255 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
256
257 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
258 ComponentName cn = ComponentName.unflattenFromString(
259 values.getAsString(Favorites.APPWIDGET_PROVIDER));
260
261 if (cn != null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700262 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700263 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700264 int appWidgetId = widgetHolder.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700265 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
266 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700267 widgetHolder.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700268 return false;
269 }
270 } catch (RuntimeException e) {
271 Log.e(TAG, "Failed to initialize external widget", e);
272 return false;
Sihua Maaa2b8722022-10-25 15:17:58 -0700273 } finally {
274 // Necessary to destroy the holder to free up possible activity context
275 widgetHolder.destroy();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700276 }
277 } else {
278 return false;
279 }
280 }
281
Sunny Goyalc5939392018-12-07 11:43:47 -0800282 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700283 }
284
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800285 @Override
286 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700287 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 SqlArguments args = new SqlArguments(uri);
289
290 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700291 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 int numValues = values.length;
293 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400294 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700295 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
296 return 0;
297 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800298 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800299 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700300 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 }
302
Sunny Goyald1064182015-08-13 12:08:30 -0700303 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304 return values.length;
305 }
306
Sunny Goyal161a2142018-10-29 14:02:20 -0700307 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800308 @Override
Yura085c8532014-02-11 15:15:29 +0000309 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
310 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700311 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700312 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800313 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700314
315 final int numOperations = operations.size();
316 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
317 for (int i = 0; i < numOperations; i++) {
318 ContentProviderOperation op = operations.get(i);
319 results[i] = op.apply(this, results, i);
320
321 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
322 results[i].count != null && results[i].count > 0;
323 }
324 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800325 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700326 }
327
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700328 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700329 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700330 return results;
Yura085c8532014-02-11 15:15:29 +0000331 }
332 }
333
334 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700336 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
338
339 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340
Louis Begina9c21c62016-08-15 15:18:41 -0700341 if (Binder.getCallingPid() != Process.myPid()
342 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700343 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700344 }
345 int count = db.delete(args.table, args.where, args.args);
346 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800347 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700348 reloadLauncherIfExternal();
349 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 return count;
351 }
352
353 @Override
354 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700355 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
357
Chris Wren1ada10d2013-09-13 18:01:38 -0400358 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800359 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
360 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700361 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800362 return count;
363 }
364
Sunny Goyal7779d622015-06-11 16:18:39 -0700365 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700366 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700367 if (Binder.getCallingUid() != Process.myUid()) {
368 return null;
369 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700370 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700371
372 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700373 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
374 clearFlagEmptyDbCreated();
375 return null;
376 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700377 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
378 Bundle result = new Bundle();
379 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Stefan Andonian146701c2022-11-10 23:07:40 +0000380 LauncherPrefs.getPrefs(getContext()).getBoolean(
Pinyao Ting96186af2020-07-20 11:03:39 -0700381 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700382 return result;
383 }
Sunny Goyald2497482015-09-22 18:24:19 -0700384 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
385 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700386 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
387 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700388 return result;
389 }
390 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
391 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800392 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
393 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700394 return result;
395 }
396 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
397 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800398 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
Andras Kloczl953eb802021-10-15 21:16:48 +0100399 mOpenHelper.getNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700400 return result;
401 }
402 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800403 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700404 return null;
405 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800406 case LauncherSettings.Settings.METHOD_SET_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000407 switch (arg) {
408 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST:
409 mDefaultWorkspaceLayoutOverride = TEST_WORKSPACE_LAYOUT_RES_XML;
410 break;
411 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST2:
412 mDefaultWorkspaceLayoutOverride = TEST2_WORKSPACE_LAYOUT_RES_XML;
413 break;
Sebastian Franco239ae0a2023-03-03 15:56:52 -0800414 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TAPL:
415 mDefaultWorkspaceLayoutOverride = TAPL_WORKSPACE_LAYOUT_RES_XML;
416 break;
Alex Chauf8b79d42022-12-15 13:41:49 +0000417 default:
418 mDefaultWorkspaceLayoutOverride = 0;
419 break;
420 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800421 return null;
422 }
423 case LauncherSettings.Settings.METHOD_CLEAR_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000424 mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800425 return null;
426 }
Sunny Goyald2497482015-09-22 18:24:19 -0700427 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
428 loadDefaultFavoritesIfNecessary();
429 return null;
430 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700431 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
432 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
433 return null;
434 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700435 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
436 Bundle result = new Bundle();
437 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
438 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
439 return result;
440 }
441 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700442 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
443 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700444 return null;
445 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700446 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
447 mOpenHelper.mHotseatRestoreTableExists = tableExists(
448 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
449 return null;
450 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700451 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700452 final long ts = System.currentTimeMillis();
453 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
454 mLastRestoreTimestamp = ts;
455 RestoreDbTask.restoreIfPossible(
456 getContext(), mOpenHelper, new BackupManager(getContext()));
457 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700458 return null;
459 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800460 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700461 Bundle result = new Bundle();
462 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
463 prepForMigration(
Alex Chaufe9a07b2022-03-08 21:48:34 +0000464 arg /* dbFile */,
Sunny Goyal278939f2021-07-28 14:35:47 -0700465 Favorites.TMP_TABLE,
466 () -> mOpenHelper,
467 () -> DatabaseHelper.createDatabaseHelper(
468 getContext(), true /* forMigration */)));
469 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700470 }
471 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700472 Bundle result = new Bundle();
473 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
474 prepForMigration(
475 arg /* dbFile */,
476 Favorites.PREVIEW_TABLE_NAME,
477 () -> DatabaseHelper.createDatabaseHelper(
478 getContext(), arg, true /* forMigration */),
479 () -> mOpenHelper));
480 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700481 }
482 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
483 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
484 final DatabaseHelper helper = mOpenHelper;
485 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
486 mProviderAuthority = null;
487 } else {
488 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
489 }
490 mOpenHelper = DatabaseHelper.createDatabaseHelper(
491 getContext(), arg, false /* forMigration */);
492 helper.close();
493 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
494 if (app == null) return null;
495 app.getModel().forceReload();
496 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800497 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700498 }
499 return null;
500 }
501
Tracy Zhou7df93d22020-01-27 13:44:06 -0800502 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700503 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800504 }
505
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700506 /**
507 * Deletes any empty folder from the DB.
508 * @return Ids of deleted folders.
509 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700510 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700511 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700512 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700513 // Select folders whose id do not match any container value.
514 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
515 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
516 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
517 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700518 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800519
Alex Chauac038432021-11-04 16:49:59 +0000520 IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Sunny Goyalc5939392018-12-07 11:43:47 -0800521 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700522 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700523 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700524 LauncherSettings.Favorites._ID, folderIds), null);
525 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700526 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800527 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700528 } catch (SQLException ex) {
529 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800530 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700531 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700532 }
533
Adam Cohen091440a2015-03-18 14:16:05 -0700534 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800535 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800536 }
537
Sunny Goyald2497482015-09-22 18:24:19 -0700538 private void clearFlagEmptyDbCreated() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000539 LauncherPrefs.getPrefs(getContext()).edit()
Pinyao Ting96186af2020-07-20 11:03:39 -0700540 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700541 }
542
Sunny Goyal42de82f2014-09-26 22:09:29 -0700543 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700544 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700545 * 1) From the app restrictions
546 * 2) From a package provided by play store
547 * 3) From a partner configuration APK, already in the system image
548 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700549 */
Sunny Goyald2497482015-09-22 18:24:19 -0700550 synchronized private void loadDefaultFavoritesIfNecessary() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000551 SharedPreferences sp = LauncherPrefs.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700552
Pinyao Ting96186af2020-07-20 11:03:39 -0700553 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500554 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200555
Sihua Maaa2b8722022-10-25 15:17:58 -0700556 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
557 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHolder);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700558 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700559 loader = AutoInstallsLayout.get(getContext(), widgetHolder, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700560 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700561 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700562 final Partner partner = Partner.get(getContext().getPackageManager());
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800563 if (partner != null) {
564 int workspaceResId = partner.getXmlResId(RES_PARTNER_DEFAULT_LAYOUT);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700565 if (workspaceResId != 0) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700566 loader = new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800567 mOpenHelper, partner.getResources(), workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700568 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700569 }
570 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700571
Sunny Goyal9d219682014-10-23 14:21:02 -0700572 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700573 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700574 loader = getDefaultLayoutParser(widgetHolder);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700575 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800576
577 // There might be some partially restored DB items, due to buggy restore logic in
578 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800579 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700580 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700581 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
582 && usingExternallyProvidedLayout) {
583 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800584 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700585 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sihua Maaa2b8722022-10-25 15:17:58 -0700586 getDefaultLayoutParser(widgetHolder));
Sunny Goyal9d219682014-10-23 14:21:02 -0700587 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700588 clearFlagEmptyDbCreated();
Sihua Maaa2b8722022-10-25 15:17:58 -0700589 widgetHolder.destroy();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700590 }
591 }
592
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700593 /**
594 * Creates workspace loader from an XML resource listed in the app restrictions.
595 *
596 * @return the loader if the restrictions are set and the resource exists; null otherwise.
597 */
Sihua Maaa2b8722022-10-25 15:17:58 -0700598 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(
599 LauncherWidgetHolder widgetHolder) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700600 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700601 final String authority;
602 if (!TextUtils.isEmpty(mProviderAuthority)) {
603 authority = mProviderAuthority;
604 } else {
605 authority = Settings.Secure.getString(ctx.getContentResolver(),
606 "launcher3.layout.provider");
607 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700608 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700609 return null;
610 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700611
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700612 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
613 if (pi == null) {
614 Log.e(TAG, "No provider found for authority " + authority);
615 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700616 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800617 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700618 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
619 // Read the full xml so that we fail early in case of any IO error.
620 String layout = new String(IOUtils.toByteArray(in));
621 XmlPullParser parser = Xml.newPullParser();
622 parser.setInput(new StringReader(layout));
623
624 Log.d(TAG, "Loading layout from " + authority);
Sihua Maaa2b8722022-10-25 15:17:58 -0700625 return new AutoInstallsLayout(ctx, widgetHolder, mOpenHelper,
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700626 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
627 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
628 } catch (Exception e) {
629 Log.e(TAG, "Error getting layout stream from: " + authority , e);
630 return null;
631 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700632 }
633
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800634 public static Uri getLayoutUri(String authority, Context ctx) {
635 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
636 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
637 .appendQueryParameter("version", "1")
638 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
639 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700640 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800641 .build();
642 }
643
Sihua Maaa2b8722022-10-25 15:17:58 -0700644 private DefaultLayoutParser getDefaultLayoutParser(LauncherWidgetHolder widgetHolder) {
Adam Cohen27824492017-09-22 17:10:55 -0700645 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
Alex Chauf8b79d42022-12-15 13:41:49 +0000646 int defaultLayout = mDefaultWorkspaceLayoutOverride > 0
647 ? mDefaultWorkspaceLayoutOverride : idp.defaultLayoutId;
Adam Cohen27824492017-09-22 17:10:55 -0700648
Sunny Goyal337c81f2019-12-10 12:19:13 -0800649 if (getContext().getSystemService(UserManager.class).isDemoUser()
650 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700651 defaultLayout = idp.demoModeLayoutId;
652 }
653
Sihua Maaa2b8722022-10-25 15:17:58 -0700654 return new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal9d219682014-10-23 14:21:02 -0700655 mOpenHelper, getContext().getResources(), defaultLayout);
656 }
657
Sunny Goyald3849d12015-10-29 10:28:32 -0700658 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800659 * The class is subclassed in tests to create an in-memory db.
660 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800661 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
662 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800663 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700664 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700665 private int mMaxItemId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700666 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700667 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668
Tracy Zhoued5f3082020-04-20 01:13:26 -0700669 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
670 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700671 }
672
Tracy Zhoued5f3082020-04-20 01:13:26 -0700673 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
674 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700675 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700676 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700677 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700678 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700679 // Table creation sometimes fails silently, which leads to a crash loop.
680 // This way, we will try to create a table every time after crash, so the device
681 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700682 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700683 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
684 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700685 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700686 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700687 databaseHelper.mHotseatRestoreTableExists = tableExists(
688 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700689
Tracy Zhouc0000452020-03-17 18:28:38 -0700690 databaseHelper.initIds();
691 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700692 }
693
694 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700695 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700696 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700697 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800698 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700699 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700700 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700701 }
702
703 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700704 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
705 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700706 if (mMaxItemId == -1) {
707 mMaxItemId = initializeMaxItemId(getWritableDatabase());
708 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800709 }
710
711 @Override
712 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800713 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700714
Adam Cohendcd297f2013-06-18 13:13:40 -0700715 mMaxItemId = 1;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700716
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700717 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800719 // Fresh and clean launcher DB.
720 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700721 if (!mForMigration) {
722 onEmptyDbCreated();
723 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800724 }
725
Sunny Goyal161a2142018-10-29 14:02:20 -0700726 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700727 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700728 dropTable(db, Favorites.BACKUP_TABLE_NAME);
729 mBackupTableExists = false;
730 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700731 if (mHotseatRestoreTableExists) {
732 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
733 mHotseatRestoreTableExists = false;
734 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700735 }
736
Sunny Goyalf076eae2016-01-11 12:25:10 -0800737 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700738 * Re-composite given key in respect to database. If the current db is
739 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
740 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
741 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
742 */
743 String getKey(final String key) {
744 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
745 return key;
746 }
747 return key + "@" + getDatabaseName();
748 }
749
750 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800751 * Overriden in tests.
752 */
753 protected void onEmptyDbCreated() {
754 // Set the flag for empty DB
Stefan Andonian146701c2022-11-10 23:07:40 +0000755 LauncherPrefs.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
Pinyao Ting96186af2020-07-20 11:03:39 -0700756 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800757 }
758
Jon Miranda2bc6b932019-03-07 15:24:46 -0800759 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800760 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800761 }
762
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700763 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800764 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800765 }
766
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700767 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700768 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700769 }
770
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700772 public void onOpen(SQLiteDatabase db) {
773 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700774
775 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
776 if (!schemaFile.exists()) {
777 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700778 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800779 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700780 }
781
782 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700783 * One-time data updated before support of onDowngrade was added. This update is backwards
784 * compatible and can safely be run multiple times.
785 * Note: No new logic should be added here after release, as the new logic might not get
786 * executed on an existing device.
787 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700788 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700789 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
790 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800791 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700792 for (UserHandle user : um.getUserProfiles()) {
793 long serial = um.getSerialNumberForUser(user);
794 String sql = "update favorites set intent = replace(intent, "
795 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
796 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700797 }
798 }
799
800 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800801 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700802 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800803 switch (oldVersion) {
804 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800805 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800806 case 12:
807 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700809 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800810 // Insert new column for holding widget provider name
811 db.execSQL("ALTER TABLE favorites " +
812 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700813 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 } catch (SQLException ex) {
815 Log.e(TAG, ex.getMessage(), ex);
816 // Old version remains, which means we wipe old data
817 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800818 }
819 }
820 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800821 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800822 // Old version remains, which means we wipe old data
823 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 }
825 }
826 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700827 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800828 // Old version remains, which means we wipe old data
829 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800830 }
831 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800832 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700833 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800834 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800835 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800836 case 18:
837 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800838 case 19: {
839 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800840 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800841 // Old version remains, which means we wipe old data
842 break;
843 }
844 }
845 case 20:
846 if (!updateFolderItemsRank(db, true)) {
847 break;
848 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800849 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800850 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800851 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700852 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
853 // Old version remains, which means we wipe old data
854 break;
855 }
856 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700857 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700858 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700859 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000860 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700861 case 25:
862 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700863 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700864 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800865 case 27: {
866 // Update the favorites table so that the screen ids are ordered based on
867 // workspace page rank.
Alex Chauac038432021-11-04 16:49:59 +0000868 IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
869 "workspaceScreens", BaseColumns._ID, null, null, "screenRank");
Sunny Goyalc5939392018-12-07 11:43:47 -0800870 int[] original = finalScreens.toArray();
871 Arrays.sort(original);
872 String updatemap = "";
873 for (int i = 0; i < original.length; i++) {
874 if (finalScreens.get(i) != original[i]) {
875 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
876 Favorites.SCREEN, finalScreens.get(i), original[i]);
877 }
878 }
879 if (!TextUtils.isEmpty(updatemap)) {
880 String query = String.format(Locale.ENGLISH,
881 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
882 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
883 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
884 db.execSQL(query);
885 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700886 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800887 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100888 case 28: {
889 boolean columnAdded = addIntegerColumn(
890 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
891 if (!columnAdded) {
892 // Old version remains, which means we wipe old data
893 break;
894 }
895 }
896 case 29: {
Andras Kloczl929e3a22021-09-06 03:30:30 +0100897 // Remove widget panel related leftover workspace items
898 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
899 Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
900 }
901 case 30: {
Alex Chaue09067c2022-01-10 16:13:13 +0000902 if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
903 // Clean up first row in screen 0 as it might contain junk data.
904 Log.d(TAG, "Cleaning up first row");
905 db.delete(Favorites.TABLE_NAME,
906 String.format(Locale.ENGLISH,
907 "%1$s = %2$d AND %3$s = %4$d AND %5$s = %6$d",
908 Favorites.SCREEN, 0,
909 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP,
910 Favorites.CELLY, 0), null);
911 }
912 return;
913 }
914 case 31: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800915 // DB Upgraded successfully
916 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100917 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400918 }
919
Sunny Goyala2cc6242015-01-14 14:23:02 -0800920 // DB was not upgraded
921 Log.w(TAG, "Destroying all old data.");
922 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800923 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800924
Adam Cohen9b1d0622014-05-21 19:01:57 -0700925 @Override
926 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700927 try {
928 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
929 .onDowngrade(db, oldVersion, newVersion);
930 } catch (Exception e) {
931 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
932 ". Wiping databse.", e);
933 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700934 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700935 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700936
Sunny Goyal42de82f2014-09-26 22:09:29 -0700937 /**
938 * Clears all the data for a fresh start.
939 */
940 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700941 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700942 dropTable(db, Favorites.TABLE_NAME);
943 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800944 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700945 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800946 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700947 }
948
Sunny Goyald2f38192015-02-25 10:46:34 -0800949 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700950 * Removes widgets which are registered to the Launcher's host, but are not present
951 * in our model.
952 */
953 public void removeGhostWidgets(SQLiteDatabase db) {
954 // Get all existing widget ids.
Sihua Maaa2b8722022-10-25 15:17:58 -0700955 final LauncherWidgetHolder holder = newLauncherWidgetHolder();
Sunny Goyal55fddc82017-04-06 15:02:52 -0700956 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700957 final int[] allWidgets;
958 try {
959 // Although the method was defined in O, it has existed since the beginning of
960 // time, so it might work on older platforms as well.
961 allWidgets = holder.getAppWidgetIds();
962 } catch (IncompatibleClassChangeError e) {
963 Log.e(TAG, "getAppWidgetIds not supported", e);
964 // Necessary to destroy the holder to free up possible activity context
965 holder.destroy();
966 return;
967 }
968 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
969 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
970 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
971 boolean isAnyWidgetRemoved = false;
972 for (int widgetId : allWidgets) {
973 if (!validWidgets.contains(widgetId)) {
974 try {
975 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
976 holder.deleteAppWidgetId(widgetId);
977 isAnyWidgetRemoved = true;
978 } catch (RuntimeException e) {
979 // Ignore
980 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700981 }
982 }
Sihua Maaa2b8722022-10-25 15:17:58 -0700983 if (isAnyWidgetRemoved) {
984 final String allWidgetsIds = Arrays.stream(allWidgets).mapToObj(String::valueOf)
985 .collect(Collectors.joining(",", "[", "]"));
986 final String validWidgetsIds = Arrays.stream(
987 validWidgets.getArray().toArray()).mapToObj(String::valueOf)
988 .collect(Collectors.joining(",", "[", "]"));
989 FileLog.d(TAG, "One or more widgets was removed. db_path=" + db.getPath()
990 + " allWidgetsIds=" + allWidgetsIds
991 + ", validWidgetsIds=" + validWidgetsIds);
992 }
993 } finally {
994 holder.destroy();
Pinyao Ting7fd7e512022-10-03 17:46:03 -0700995 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700996 }
997
998 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700999 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
1000 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
1001 */
Sunny Goyal316490e2015-06-02 09:38:28 -07001002 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001003 try (SQLiteTransaction t = new SQLiteTransaction(db);
1004 // Only consider the primary user as other users can't have a shortcut.
1005 Cursor c = db.query(Favorites.TABLE_NAME,
1006 new String[] { Favorites._ID, Favorites.INTENT},
1007 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
1008 " AND profileId=" + getDefaultUserSerial(),
1009 null, null, null, null);
1010 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
1011 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
1012 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001013 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1014 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
1015
1016 while (c.moveToNext()) {
1017 String intentDescription = c.getString(intentIndex);
1018 Intent intent;
1019 try {
1020 intent = Intent.parseUri(intentDescription, 0);
1021 } catch (URISyntaxException e) {
1022 Log.e(TAG, "Unable to parse intent", e);
1023 continue;
1024 }
1025
Sunny Goyal9dbb27c2019-07-17 15:12:56 -07001026 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001027 continue;
1028 }
1029
Sunny Goyalefb7e842018-10-04 15:11:00 -07001030 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001031 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -07001032 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -07001033 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001034 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -07001035 } catch (SQLException ex) {
1036 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001037 }
1038 }
1039
Adam Cohen091440a2015-03-18 14:16:05 -07001040 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001041 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001042 if (addRankColumn) {
1043 // Insert new column for holding rank
1044 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1045 }
1046
1047 // Get a map for folder ID to folder width
1048 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1049 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1050 + " GROUP BY container;",
1051 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1052
1053 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001054 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1055 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001056 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1057 }
1058
1059 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001060 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001061 } catch (SQLException ex) {
1062 // Old version remains, which means we wipe old data
1063 Log.e(TAG, ex.getMessage(), ex);
1064 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001065 }
1066 return true;
1067 }
1068
Sunny Goyal5d85c442015-03-10 13:14:47 -07001069 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001070 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001071 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1072 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001073 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001074 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001075 Log.e(TAG, ex.getMessage(), ex);
1076 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001077 }
1078 return true;
1079 }
1080
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001081 // Generates a new ID to use for an object in your database. This method should be only
1082 // called from the main UI thread. As an exception, we do call it when we call the
1083 // constructor from the worker thread; however, this doesn't extend until after the
1084 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1085 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001086 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001087 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001088 if (mMaxItemId < 0) {
1089 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001090 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001091 mMaxItemId += 1;
1092 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001093 }
1094
Sihua Maaa2b8722022-10-25 15:17:58 -07001095 /**
1096 * @return A new {@link LauncherWidgetHolder} based on the current context
1097 */
1098 @NonNull
1099 public LauncherWidgetHolder newLauncherWidgetHolder() {
Sihua Ma1db8bc22022-11-08 17:13:13 -08001100 return LauncherWidgetHolder.newInstance(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001101 }
1102
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001103 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001104 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001105 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001106 }
1107
Sunny Goyalc5939392018-12-07 11:43:47 -08001108 public void checkId(ContentValues values) {
1109 int id = values.getAsInteger(Favorites._ID);
1110 mMaxItemId = Math.max(id, mMaxItemId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001111 }
1112
Sunny Goyalefb7e842018-10-04 15:11:00 -07001113 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001114 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001115 }
1116
Andras Kloczl953eb802021-10-15 21:16:48 +01001117 // Returns a new ID to use for an workspace screen in your database that is greater than all
1118 // existing screen IDs.
1119 private int getNewScreenId() {
1120 return getMaxId(getWritableDatabase(),
1121 "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001122 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Andras Kloczl953eb802021-10-15 21:16:48 +01001123 Favorites.CONTAINER_DESKTOP) + 1;
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001124 }
1125
Adam Cohen091440a2015-03-18 14:16:05 -07001126 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001127 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001128 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001129
1130 // Ensure that the max ids are initialized
1131 mMaxItemId = initializeMaxItemId(db);
Adam Cohen71483f42014-05-15 14:04:01 -07001132 return count;
1133 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001134 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001135
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001136 /**
1137 * @return the max _id in the provided table.
1138 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001139 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001140 int max = 0;
1141 try (SQLiteStatement prog = db.compileStatement(
1142 String.format(Locale.ENGLISH, query, args))) {
1143 max = (int) DatabaseUtils.longForQuery(prog, null);
1144 if (max < 0) {
1145 throw new RuntimeException("Error: could not query max id");
1146 }
1147 } catch (IllegalArgumentException exception) {
1148 String message = exception.getMessage();
1149 if (message.contains("re-open") && message.contains("already-closed")) {
1150 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1151 } else {
1152 throw exception;
1153 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001154 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001155 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001156 }
1157
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001158 static class SqlArguments {
1159 public final String table;
1160 public final String where;
1161 public final String[] args;
1162
1163 SqlArguments(Uri url, String where, String[] args) {
1164 if (url.getPathSegments().size() == 1) {
1165 this.table = url.getPathSegments().get(0);
1166 this.where = where;
1167 this.args = args;
1168 } else if (url.getPathSegments().size() != 2) {
1169 throw new IllegalArgumentException("Invalid URI: " + url);
1170 } else if (!TextUtils.isEmpty(where)) {
1171 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1172 } else {
1173 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001174 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001175 this.args = null;
1176 }
1177 }
1178
1179 SqlArguments(Uri url) {
1180 if (url.getPathSegments().size() == 1) {
1181 table = url.getPathSegments().get(0);
1182 where = null;
1183 args = null;
1184 } else {
1185 throw new IllegalArgumentException("Invalid URI: " + url);
1186 }
1187 }
1188 }
Adam Cohen72960972014-01-15 18:13:55 -08001189}