blob: 767c3d986e4030f11fc9efd11a1394b28deb18f0 [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;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800110
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800111 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Sunny Goyalf076eae2016-01-11 12:25:10 -0800113 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700114 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115
Pinyao Ting0807c942020-04-28 13:58:45 -0700116 private long mLastRestoreTimestamp = 0L;
117
Alex Chauf8b79d42022-12-15 13:41:49 +0000118 private int mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800119
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800120 /**
121 * $ adb shell dumpsys activity provider com.android.launcher3
122 */
123 @Override
124 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
125 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
126 if (appState == null || !appState.getModel().isModelLoaded()) {
127 return;
128 }
129 appState.getModel().dumpState("", fd, writer, args);
130 }
131
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 @Override
133 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800134 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700135 Log.d(TAG, "Launcher process started");
136 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700137
Sunny Goyalfdbef272017-02-01 12:52:54 -0800138 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800139 // is the first component to get created.
140 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800141 return true;
142 }
143
144 @Override
145 public String getType(Uri uri) {
146 SqlArguments args = new SqlArguments(uri, null, null);
147 if (TextUtils.isEmpty(args.where)) {
148 return "vnd.android.cursor.dir/" + args.table;
149 } else {
150 return "vnd.android.cursor.item/" + args.table;
151 }
152 }
153
Sunny Goyalf076eae2016-01-11 12:25:10 -0800154 /**
155 * Overridden in tests
156 */
157 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700158 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700159 mOpenHelper = DatabaseHelper.createDatabaseHelper(
160 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700161
Sunny Goyal68031ca2021-08-02 12:23:44 -0700162 RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 }
164 }
165
Tracy Zhouc0000452020-03-17 18:28:38 -0700166 private synchronized boolean prepForMigration(String dbFile, String targetTableName,
167 Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
168 if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
Alex Chau0adc3662022-07-04 13:05:38 +0100169 Log.e(TAG, "prepForMigration - target db is same as current: " + dbFile);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800170 return false;
171 }
172
Tracy Zhouc0000452020-03-17 18:28:38 -0700173 final DatabaseHelper helper = src.get();
174 mOpenHelper = dst.get();
175 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
176 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
177 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800178 return true;
179 }
180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 @Override
182 public Cursor query(Uri uri, String[] projection, String selection,
183 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700184 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185
186 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
187 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
188 qb.setTables(args.table);
189
Romain Guy73b979d2009-06-09 12:57:21 -0700190 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700192 final Bundle extra = new Bundle();
193 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
194 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 result.setNotificationUri(getContext().getContentResolver(), uri);
196
197 return result;
198 }
199
Sunny Goyalefb7e842018-10-04 15:11:00 -0700200 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700201 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500202 if (values == null) {
203 throw new RuntimeException("Error: attempting to insert null values");
204 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800205 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700206 throw new RuntimeException("Error: attempting to add item without specifying an id");
207 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800208 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700209 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700210 }
211
Sunny Goyald1064182015-08-13 12:08:30 -0700212 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800213 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700214 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
215 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800216 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700217 }
218 }
219 }
220
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 @Override
222 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700223 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224 SqlArguments args = new SqlArguments(uri);
225
Sunny Goyald1064182015-08-13 12:08:30 -0700226 // In very limited cases, we support system|signature permission apps to modify the db.
227 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700228 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700229 return null;
230 }
231 }
232
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400234 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700235 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800236 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800237 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238
239 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800240 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 return uri;
242 }
243
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700244 private boolean initializeExternalAdd(ContentValues values) {
245 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700246 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700247 values.put(LauncherSettings.Favorites._ID, id);
248
249 // 2. In the case of an app widget, and if no app widget id is specified, we
250 // attempt allocate and bind the widget.
251 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
252 if (itemType != null &&
253 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
254 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
255
256 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
257 ComponentName cn = ComponentName.unflattenFromString(
258 values.getAsString(Favorites.APPWIDGET_PROVIDER));
259
260 if (cn != null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700261 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700262 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700263 int appWidgetId = widgetHolder.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700264 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
265 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700266 widgetHolder.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700267 return false;
268 }
269 } catch (RuntimeException e) {
270 Log.e(TAG, "Failed to initialize external widget", e);
271 return false;
Sihua Maaa2b8722022-10-25 15:17:58 -0700272 } finally {
273 // Necessary to destroy the holder to free up possible activity context
274 widgetHolder.destroy();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700275 }
276 } else {
277 return false;
278 }
279 }
280
Sunny Goyalc5939392018-12-07 11:43:47 -0800281 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700282 }
283
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 @Override
285 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700286 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 SqlArguments args = new SqlArguments(uri);
288
289 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700290 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 int numValues = values.length;
292 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400293 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700294 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
295 return 0;
296 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800297 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800298 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700299 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 }
301
Sunny Goyald1064182015-08-13 12:08:30 -0700302 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 return values.length;
304 }
305
Sunny Goyal161a2142018-10-29 14:02:20 -0700306 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 @Override
Yura085c8532014-02-11 15:15:29 +0000308 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
309 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700310 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700311 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800312 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700313
314 final int numOperations = operations.size();
315 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
316 for (int i = 0; i < numOperations; i++) {
317 ContentProviderOperation op = operations.get(i);
318 results[i] = op.apply(this, results, i);
319
320 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
321 results[i].count != null && results[i].count > 0;
322 }
323 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800324 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700325 }
326
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700327 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700328 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700329 return results;
Yura085c8532014-02-11 15:15:29 +0000330 }
331 }
332
333 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700335 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
337
338 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339
Louis Begina9c21c62016-08-15 15:18:41 -0700340 if (Binder.getCallingPid() != Process.myPid()
341 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700342 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700343 }
344 int count = db.delete(args.table, args.where, args.args);
345 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800346 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700347 reloadLauncherIfExternal();
348 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 return count;
350 }
351
352 @Override
353 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700354 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
356
Chris Wren1ada10d2013-09-13 18:01:38 -0400357 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800358 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
359 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700360 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800361 return count;
362 }
363
Sunny Goyal7779d622015-06-11 16:18:39 -0700364 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700365 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700366 if (Binder.getCallingUid() != Process.myUid()) {
367 return null;
368 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700369 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700370
371 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700372 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
373 clearFlagEmptyDbCreated();
374 return null;
375 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700376 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
377 Bundle result = new Bundle();
378 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Stefan Andonian146701c2022-11-10 23:07:40 +0000379 LauncherPrefs.getPrefs(getContext()).getBoolean(
Pinyao Ting96186af2020-07-20 11:03:39 -0700380 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700381 return result;
382 }
Sunny Goyald2497482015-09-22 18:24:19 -0700383 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
384 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700385 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
386 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700387 return result;
388 }
389 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
390 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800391 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
392 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700393 return result;
394 }
395 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
396 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800397 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
Andras Kloczl953eb802021-10-15 21:16:48 +0100398 mOpenHelper.getNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700399 return result;
400 }
401 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800402 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700403 return null;
404 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800405 case LauncherSettings.Settings.METHOD_SET_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000406 switch (arg) {
407 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST:
408 mDefaultWorkspaceLayoutOverride = TEST_WORKSPACE_LAYOUT_RES_XML;
409 break;
410 case LauncherSettings.Settings.ARG_DEFAULT_WORKSPACE_LAYOUT_TEST2:
411 mDefaultWorkspaceLayoutOverride = TEST2_WORKSPACE_LAYOUT_RES_XML;
412 break;
413 default:
414 mDefaultWorkspaceLayoutOverride = 0;
415 break;
416 }
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800417 return null;
418 }
419 case LauncherSettings.Settings.METHOD_CLEAR_USE_TEST_WORKSPACE_LAYOUT_FLAG: {
Alex Chauf8b79d42022-12-15 13:41:49 +0000420 mDefaultWorkspaceLayoutOverride = 0;
Schneider Victor-tuliasfb252e72022-02-10 11:10:21 -0800421 return null;
422 }
Sunny Goyald2497482015-09-22 18:24:19 -0700423 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
424 loadDefaultFavoritesIfNecessary();
425 return null;
426 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700427 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
428 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
429 return null;
430 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700431 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
432 Bundle result = new Bundle();
433 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
434 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
435 return result;
436 }
437 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700438 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
439 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700440 return null;
441 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700442 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
443 mOpenHelper.mHotseatRestoreTableExists = tableExists(
444 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
445 return null;
446 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700447 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700448 final long ts = System.currentTimeMillis();
449 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
450 mLastRestoreTimestamp = ts;
451 RestoreDbTask.restoreIfPossible(
452 getContext(), mOpenHelper, new BackupManager(getContext()));
453 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700454 return null;
455 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800456 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700457 Bundle result = new Bundle();
458 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
459 prepForMigration(
Alex Chaufe9a07b2022-03-08 21:48:34 +0000460 arg /* dbFile */,
Sunny Goyal278939f2021-07-28 14:35:47 -0700461 Favorites.TMP_TABLE,
462 () -> mOpenHelper,
463 () -> DatabaseHelper.createDatabaseHelper(
464 getContext(), true /* forMigration */)));
465 return result;
Tracy Zhouc0000452020-03-17 18:28:38 -0700466 }
467 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
Sunny Goyal278939f2021-07-28 14:35:47 -0700468 Bundle result = new Bundle();
469 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
470 prepForMigration(
471 arg /* dbFile */,
472 Favorites.PREVIEW_TABLE_NAME,
473 () -> DatabaseHelper.createDatabaseHelper(
474 getContext(), arg, true /* forMigration */),
475 () -> mOpenHelper));
476 return result;
Pinyao Ting96186af2020-07-20 11:03:39 -0700477 }
478 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
479 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
480 final DatabaseHelper helper = mOpenHelper;
481 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
482 mProviderAuthority = null;
483 } else {
484 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
485 }
486 mOpenHelper = DatabaseHelper.createDatabaseHelper(
487 getContext(), arg, false /* forMigration */);
488 helper.close();
489 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
490 if (app == null) return null;
491 app.getModel().forceReload();
492 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800493 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700494 }
495 return null;
496 }
497
Tracy Zhou7df93d22020-01-27 13:44:06 -0800498 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700499 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800500 }
501
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700502 /**
503 * Deletes any empty folder from the DB.
504 * @return Ids of deleted folders.
505 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700506 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700507 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700508 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700509 // Select folders whose id do not match any container value.
510 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
511 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
512 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
513 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700514 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800515
Alex Chauac038432021-11-04 16:49:59 +0000516 IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Sunny Goyalc5939392018-12-07 11:43:47 -0800517 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700518 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700520 LauncherSettings.Favorites._ID, folderIds), null);
521 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700522 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800523 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700524 } catch (SQLException ex) {
525 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800526 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700527 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700528 }
529
Adam Cohen091440a2015-03-18 14:16:05 -0700530 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800531 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800532 }
533
Sunny Goyald2497482015-09-22 18:24:19 -0700534 private void clearFlagEmptyDbCreated() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000535 LauncherPrefs.getPrefs(getContext()).edit()
Pinyao Ting96186af2020-07-20 11:03:39 -0700536 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700537 }
538
Sunny Goyal42de82f2014-09-26 22:09:29 -0700539 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700540 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541 * 1) From the app restrictions
542 * 2) From a package provided by play store
543 * 3) From a partner configuration APK, already in the system image
544 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700545 */
Sunny Goyald2497482015-09-22 18:24:19 -0700546 synchronized private void loadDefaultFavoritesIfNecessary() {
Stefan Andonian146701c2022-11-10 23:07:40 +0000547 SharedPreferences sp = LauncherPrefs.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700548
Pinyao Ting96186af2020-07-20 11:03:39 -0700549 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500550 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200551
Sihua Maaa2b8722022-10-25 15:17:58 -0700552 LauncherWidgetHolder widgetHolder = mOpenHelper.newLauncherWidgetHolder();
553 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHolder);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700554 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700555 loader = AutoInstallsLayout.get(getContext(), widgetHolder, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700556 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700557 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700558 final Partner partner = Partner.get(getContext().getPackageManager());
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800559 if (partner != null) {
560 int workspaceResId = partner.getXmlResId(RES_PARTNER_DEFAULT_LAYOUT);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700561 if (workspaceResId != 0) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700562 loader = new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal3e58eea2022-11-14 14:30:07 -0800563 mOpenHelper, partner.getResources(), workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700564 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700565 }
566 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700567
Sunny Goyal9d219682014-10-23 14:21:02 -0700568 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700569 if (loader == null) {
Sihua Maaa2b8722022-10-25 15:17:58 -0700570 loader = getDefaultLayoutParser(widgetHolder);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700571 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800572
573 // There might be some partially restored DB items, due to buggy restore logic in
574 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800575 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700576 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700577 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
578 && usingExternallyProvidedLayout) {
579 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800580 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700581 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sihua Maaa2b8722022-10-25 15:17:58 -0700582 getDefaultLayoutParser(widgetHolder));
Sunny Goyal9d219682014-10-23 14:21:02 -0700583 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700584 clearFlagEmptyDbCreated();
Sihua Maaa2b8722022-10-25 15:17:58 -0700585 widgetHolder.destroy();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700586 }
587 }
588
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700589 /**
590 * Creates workspace loader from an XML resource listed in the app restrictions.
591 *
592 * @return the loader if the restrictions are set and the resource exists; null otherwise.
593 */
Sihua Maaa2b8722022-10-25 15:17:58 -0700594 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(
595 LauncherWidgetHolder widgetHolder) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700596 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700597 final String authority;
598 if (!TextUtils.isEmpty(mProviderAuthority)) {
599 authority = mProviderAuthority;
600 } else {
601 authority = Settings.Secure.getString(ctx.getContentResolver(),
602 "launcher3.layout.provider");
603 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700604 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700605 return null;
606 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700607
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700608 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
609 if (pi == null) {
610 Log.e(TAG, "No provider found for authority " + authority);
611 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700612 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800613 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700614 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
615 // Read the full xml so that we fail early in case of any IO error.
616 String layout = new String(IOUtils.toByteArray(in));
617 XmlPullParser parser = Xml.newPullParser();
618 parser.setInput(new StringReader(layout));
619
620 Log.d(TAG, "Loading layout from " + authority);
Sihua Maaa2b8722022-10-25 15:17:58 -0700621 return new AutoInstallsLayout(ctx, widgetHolder, mOpenHelper,
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700622 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
623 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
624 } catch (Exception e) {
625 Log.e(TAG, "Error getting layout stream from: " + authority , e);
626 return null;
627 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700628 }
629
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800630 public static Uri getLayoutUri(String authority, Context ctx) {
631 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
632 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
633 .appendQueryParameter("version", "1")
634 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
635 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700636 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800637 .build();
638 }
639
Sihua Maaa2b8722022-10-25 15:17:58 -0700640 private DefaultLayoutParser getDefaultLayoutParser(LauncherWidgetHolder widgetHolder) {
Adam Cohen27824492017-09-22 17:10:55 -0700641 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
Alex Chauf8b79d42022-12-15 13:41:49 +0000642 int defaultLayout = mDefaultWorkspaceLayoutOverride > 0
643 ? mDefaultWorkspaceLayoutOverride : idp.defaultLayoutId;
Adam Cohen27824492017-09-22 17:10:55 -0700644
Sunny Goyal337c81f2019-12-10 12:19:13 -0800645 if (getContext().getSystemService(UserManager.class).isDemoUser()
646 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700647 defaultLayout = idp.demoModeLayoutId;
648 }
649
Sihua Maaa2b8722022-10-25 15:17:58 -0700650 return new DefaultLayoutParser(getContext(), widgetHolder,
Sunny Goyal9d219682014-10-23 14:21:02 -0700651 mOpenHelper, getContext().getResources(), defaultLayout);
652 }
653
Sunny Goyald3849d12015-10-29 10:28:32 -0700654 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800655 * The class is subclassed in tests to create an in-memory db.
656 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800657 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
658 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800659 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700660 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700661 private int mMaxItemId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700662 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700663 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664
Tracy Zhoued5f3082020-04-20 01:13:26 -0700665 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
666 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700667 }
668
Tracy Zhoued5f3082020-04-20 01:13:26 -0700669 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
670 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700671 if (dbName == null) {
Sunny Goyal278939f2021-07-28 14:35:47 -0700672 dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
Tracy Zhouc0000452020-03-17 18:28:38 -0700673 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700674 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700675 // Table creation sometimes fails silently, which leads to a crash loop.
676 // This way, we will try to create a table every time after crash, so the device
677 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700678 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700679 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
680 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700681 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700682 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700683 databaseHelper.mHotseatRestoreTableExists = tableExists(
684 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700685
Tracy Zhouc0000452020-03-17 18:28:38 -0700686 databaseHelper.initIds();
687 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700688 }
689
690 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700691 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700692 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700693 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800694 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700695 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700696 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700697 }
698
699 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700700 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
701 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700702 if (mMaxItemId == -1) {
703 mMaxItemId = initializeMaxItemId(getWritableDatabase());
704 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800705 }
706
707 @Override
708 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800709 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700710
Adam Cohendcd297f2013-06-18 13:13:40 -0700711 mMaxItemId = 1;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700712
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700713 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800714
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800715 // Fresh and clean launcher DB.
716 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700717 if (!mForMigration) {
718 onEmptyDbCreated();
719 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800720 }
721
Sunny Goyal161a2142018-10-29 14:02:20 -0700722 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700723 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700724 dropTable(db, Favorites.BACKUP_TABLE_NAME);
725 mBackupTableExists = false;
726 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700727 if (mHotseatRestoreTableExists) {
728 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
729 mHotseatRestoreTableExists = false;
730 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700731 }
732
Sunny Goyalf076eae2016-01-11 12:25:10 -0800733 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700734 * Re-composite given key in respect to database. If the current db is
735 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
736 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
737 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
738 */
739 String getKey(final String key) {
740 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
741 return key;
742 }
743 return key + "@" + getDatabaseName();
744 }
745
746 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800747 * Overriden in tests.
748 */
749 protected void onEmptyDbCreated() {
750 // Set the flag for empty DB
Stefan Andonian146701c2022-11-10 23:07:40 +0000751 LauncherPrefs.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
Pinyao Ting96186af2020-07-20 11:03:39 -0700752 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800753 }
754
Jon Miranda2bc6b932019-03-07 15:24:46 -0800755 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800756 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800757 }
758
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700759 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800760 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800761 }
762
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700763 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700764 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700765 }
766
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800767 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700768 public void onOpen(SQLiteDatabase db) {
769 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700770
771 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
772 if (!schemaFile.exists()) {
773 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700774 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800775 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700776 }
777
778 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700779 * One-time data updated before support of onDowngrade was added. This update is backwards
780 * compatible and can safely be run multiple times.
781 * Note: No new logic should be added here after release, as the new logic might not get
782 * executed on an existing device.
783 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700784 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700785 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
786 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800787 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700788 for (UserHandle user : um.getUserProfiles()) {
789 long serial = um.getSerialNumberForUser(user);
790 String sql = "update favorites set intent = replace(intent, "
791 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
792 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700793 }
794 }
795
796 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800797 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700798 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800799 switch (oldVersion) {
800 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800801 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800802 case 12:
803 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700805 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800806 // Insert new column for holding widget provider name
807 db.execSQL("ALTER TABLE favorites " +
808 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700809 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800810 } catch (SQLException ex) {
811 Log.e(TAG, ex.getMessage(), ex);
812 // Old version remains, which means we wipe old data
813 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 }
815 }
816 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800817 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800818 // Old version remains, which means we wipe old data
819 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800820 }
821 }
822 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700823 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 // Old version remains, which means we wipe old data
825 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800826 }
827 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800828 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700829 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800830 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800831 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800832 case 18:
833 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800834 case 19: {
835 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800836 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800837 // Old version remains, which means we wipe old data
838 break;
839 }
840 }
841 case 20:
842 if (!updateFolderItemsRank(db, true)) {
843 break;
844 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800845 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800846 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800847 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700848 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
849 // Old version remains, which means we wipe old data
850 break;
851 }
852 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700853 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700854 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700855 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000856 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700857 case 25:
858 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700859 case 26:
Sunny Goyal278939f2021-07-28 14:35:47 -0700860 // QSB was moved to the grid. Ignore overlapping items
Sunny Goyalc5939392018-12-07 11:43:47 -0800861 case 27: {
862 // Update the favorites table so that the screen ids are ordered based on
863 // workspace page rank.
Alex Chauac038432021-11-04 16:49:59 +0000864 IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
865 "workspaceScreens", BaseColumns._ID, null, null, "screenRank");
Sunny Goyalc5939392018-12-07 11:43:47 -0800866 int[] original = finalScreens.toArray();
867 Arrays.sort(original);
868 String updatemap = "";
869 for (int i = 0; i < original.length; i++) {
870 if (finalScreens.get(i) != original[i]) {
871 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
872 Favorites.SCREEN, finalScreens.get(i), original[i]);
873 }
874 }
875 if (!TextUtils.isEmpty(updatemap)) {
876 String query = String.format(Locale.ENGLISH,
877 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
878 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
879 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
880 db.execSQL(query);
881 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700882 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800883 }
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100884 case 28: {
885 boolean columnAdded = addIntegerColumn(
886 db, Favorites.APPWIDGET_SOURCE, Favorites.CONTAINER_UNKNOWN);
887 if (!columnAdded) {
888 // Old version remains, which means we wipe old data
889 break;
890 }
891 }
892 case 29: {
Andras Kloczl929e3a22021-09-06 03:30:30 +0100893 // Remove widget panel related leftover workspace items
894 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
895 Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
896 }
897 case 30: {
Alex Chaue09067c2022-01-10 16:13:13 +0000898 if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
899 // Clean up first row in screen 0 as it might contain junk data.
900 Log.d(TAG, "Cleaning up first row");
901 db.delete(Favorites.TABLE_NAME,
902 String.format(Locale.ENGLISH,
903 "%1$s = %2$d AND %3$s = %4$d AND %5$s = %6$d",
904 Favorites.SCREEN, 0,
905 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP,
906 Favorites.CELLY, 0), null);
907 }
908 return;
909 }
910 case 31: {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800911 // DB Upgraded successfully
912 return;
Yogisha Dixit658c5da2021-05-24 23:23:15 +0100913 }
Chris Wrend5e66bf2013-09-16 14:02:29 -0400914 }
915
Sunny Goyala2cc6242015-01-14 14:23:02 -0800916 // DB was not upgraded
917 Log.w(TAG, "Destroying all old data.");
918 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800919 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800920
Adam Cohen9b1d0622014-05-21 19:01:57 -0700921 @Override
922 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700923 try {
924 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
925 .onDowngrade(db, oldVersion, newVersion);
926 } catch (Exception e) {
927 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
928 ". Wiping databse.", e);
929 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700930 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700931 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700932
Sunny Goyal42de82f2014-09-26 22:09:29 -0700933 /**
934 * Clears all the data for a fresh start.
935 */
936 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700937 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700938 dropTable(db, Favorites.TABLE_NAME);
939 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800940 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700941 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800942 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700943 }
944
Sunny Goyald2f38192015-02-25 10:46:34 -0800945 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700946 * Removes widgets which are registered to the Launcher's host, but are not present
947 * in our model.
948 */
949 public void removeGhostWidgets(SQLiteDatabase db) {
950 // Get all existing widget ids.
Sihua Maaa2b8722022-10-25 15:17:58 -0700951 final LauncherWidgetHolder holder = newLauncherWidgetHolder();
Sunny Goyal55fddc82017-04-06 15:02:52 -0700952 try {
Sihua Maaa2b8722022-10-25 15:17:58 -0700953 final int[] allWidgets;
954 try {
955 // Although the method was defined in O, it has existed since the beginning of
956 // time, so it might work on older platforms as well.
957 allWidgets = holder.getAppWidgetIds();
958 } catch (IncompatibleClassChangeError e) {
959 Log.e(TAG, "getAppWidgetIds not supported", e);
960 // Necessary to destroy the holder to free up possible activity context
961 holder.destroy();
962 return;
963 }
964 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
965 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
966 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
967 boolean isAnyWidgetRemoved = false;
968 for (int widgetId : allWidgets) {
969 if (!validWidgets.contains(widgetId)) {
970 try {
971 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
972 holder.deleteAppWidgetId(widgetId);
973 isAnyWidgetRemoved = true;
974 } catch (RuntimeException e) {
975 // Ignore
976 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700977 }
978 }
Sihua Maaa2b8722022-10-25 15:17:58 -0700979 if (isAnyWidgetRemoved) {
980 final String allWidgetsIds = Arrays.stream(allWidgets).mapToObj(String::valueOf)
981 .collect(Collectors.joining(",", "[", "]"));
982 final String validWidgetsIds = Arrays.stream(
983 validWidgets.getArray().toArray()).mapToObj(String::valueOf)
984 .collect(Collectors.joining(",", "[", "]"));
985 FileLog.d(TAG, "One or more widgets was removed. db_path=" + db.getPath()
986 + " allWidgetsIds=" + allWidgetsIds
987 + ", validWidgetsIds=" + validWidgetsIds);
988 }
989 } finally {
990 holder.destroy();
Pinyao Ting7fd7e512022-10-03 17:46:03 -0700991 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700992 }
993
994 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700995 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
996 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
997 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700998 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700999 try (SQLiteTransaction t = new SQLiteTransaction(db);
1000 // Only consider the primary user as other users can't have a shortcut.
1001 Cursor c = db.query(Favorites.TABLE_NAME,
1002 new String[] { Favorites._ID, Favorites.INTENT},
1003 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
1004 " AND profileId=" + getDefaultUserSerial(),
1005 null, null, null, null);
1006 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
1007 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
1008 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001009 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
1010 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
1011
1012 while (c.moveToNext()) {
1013 String intentDescription = c.getString(intentIndex);
1014 Intent intent;
1015 try {
1016 intent = Intent.parseUri(intentDescription, 0);
1017 } catch (URISyntaxException e) {
1018 Log.e(TAG, "Unable to parse intent", e);
1019 continue;
1020 }
1021
Sunny Goyal9dbb27c2019-07-17 15:12:56 -07001022 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -07001023 continue;
1024 }
1025
Sunny Goyalefb7e842018-10-04 15:11:00 -07001026 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001027 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -07001028 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -07001029 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001030 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -07001031 } catch (SQLException ex) {
1032 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -07001033 }
1034 }
1035
Adam Cohen091440a2015-03-18 14:16:05 -07001036 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001037 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -08001038 if (addRankColumn) {
1039 // Insert new column for holding rank
1040 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
1041 }
1042
1043 // Get a map for folder ID to folder width
1044 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
1045 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
1046 + " GROUP BY container;",
1047 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1048
1049 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001050 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1051 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001052 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1053 }
1054
1055 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001056 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001057 } catch (SQLException ex) {
1058 // Old version remains, which means we wipe old data
1059 Log.e(TAG, ex.getMessage(), ex);
1060 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001061 }
1062 return true;
1063 }
1064
Sunny Goyal5d85c442015-03-10 13:14:47 -07001065 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001066 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001067 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1068 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001069 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001070 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001071 Log.e(TAG, ex.getMessage(), ex);
1072 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001073 }
1074 return true;
1075 }
1076
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001077 // Generates a new ID to use for an object in your database. This method should be only
1078 // called from the main UI thread. As an exception, we do call it when we call the
1079 // constructor from the worker thread; however, this doesn't extend until after the
1080 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1081 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001082 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001083 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001084 if (mMaxItemId < 0) {
1085 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001086 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001087 mMaxItemId += 1;
1088 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001089 }
1090
Sihua Maaa2b8722022-10-25 15:17:58 -07001091 /**
1092 * @return A new {@link LauncherWidgetHolder} based on the current context
1093 */
1094 @NonNull
1095 public LauncherWidgetHolder newLauncherWidgetHolder() {
Sihua Ma1db8bc22022-11-08 17:13:13 -08001096 return LauncherWidgetHolder.newInstance(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001097 }
1098
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001099 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001100 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001101 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001102 }
1103
Sunny Goyalc5939392018-12-07 11:43:47 -08001104 public void checkId(ContentValues values) {
1105 int id = values.getAsInteger(Favorites._ID);
1106 mMaxItemId = Math.max(id, mMaxItemId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001107 }
1108
Sunny Goyalefb7e842018-10-04 15:11:00 -07001109 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001110 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001111 }
1112
Andras Kloczl953eb802021-10-15 21:16:48 +01001113 // Returns a new ID to use for an workspace screen in your database that is greater than all
1114 // existing screen IDs.
1115 private int getNewScreenId() {
1116 return getMaxId(getWritableDatabase(),
1117 "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Sunny Goyalc5939392018-12-07 11:43:47 -08001118 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Andras Kloczl953eb802021-10-15 21:16:48 +01001119 Favorites.CONTAINER_DESKTOP) + 1;
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001120 }
1121
Adam Cohen091440a2015-03-18 14:16:05 -07001122 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001123 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001124 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001125
1126 // Ensure that the max ids are initialized
1127 mMaxItemId = initializeMaxItemId(db);
Adam Cohen71483f42014-05-15 14:04:01 -07001128 return count;
1129 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001130 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001131
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001132 /**
1133 * @return the max _id in the provided table.
1134 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001135 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001136 int max = 0;
1137 try (SQLiteStatement prog = db.compileStatement(
1138 String.format(Locale.ENGLISH, query, args))) {
1139 max = (int) DatabaseUtils.longForQuery(prog, null);
1140 if (max < 0) {
1141 throw new RuntimeException("Error: could not query max id");
1142 }
1143 } catch (IllegalArgumentException exception) {
1144 String message = exception.getMessage();
1145 if (message.contains("re-open") && message.contains("already-closed")) {
1146 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1147 } else {
1148 throw exception;
1149 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001150 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001151 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001152 }
1153
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001154 static class SqlArguments {
1155 public final String table;
1156 public final String where;
1157 public final String[] args;
1158
1159 SqlArguments(Uri url, String where, String[] args) {
1160 if (url.getPathSegments().size() == 1) {
1161 this.table = url.getPathSegments().get(0);
1162 this.where = where;
1163 this.args = args;
1164 } else if (url.getPathSegments().size() != 2) {
1165 throw new IllegalArgumentException("Invalid URI: " + url);
1166 } else if (!TextUtils.isEmpty(where)) {
1167 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1168 } else {
1169 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001170 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001171 this.args = null;
1172 }
1173 }
1174
1175 SqlArguments(Uri url) {
1176 if (url.getPathSegments().size() == 1) {
1177 table = url.getPathSegments().get(0);
1178 where = null;
1179 args = null;
1180 } else {
1181 throw new IllegalArgumentException("Invalid URI: " + url);
1182 }
1183 }
1184 }
Adam Cohen72960972014-01-15 18:13:55 -08001185}