blob: 39b16fd8d6c8ee42394991e25c4792d4970204a4 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Tracy Zhou7df93d22020-01-27 13:44:06 -080019import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
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;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070026import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070027import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070029import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000030import android.content.ContentProviderOperation;
31import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070032import android.content.ContentUris;
33import android.content.ContentValues;
34import android.content.Context;
35import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000036import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070037import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070038import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080041import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070045import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070046import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070047import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070048import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070049import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070050import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080051import android.os.UserHandle;
Sunny Goyal337c81f2019-12-10 12:19:13 -080052import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080053import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070054import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070055import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080056import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070057import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070058
Sunny Goyal0fe505b2014-08-06 09:55:36 -070059import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
60import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070061import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080062import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070063import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyal337c81f2019-12-10 12:19:13 -080064import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070065import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070066import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070067import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070068import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070069import com.android.launcher3.util.IntArray;
70import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080071import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070072import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070073import com.android.launcher3.util.Thunk;
Yogisha Dixit741fae92021-02-22 14:03:44 +000074import com.android.launcher3.widget.LauncherAppWidgetHost;
Michael Jurka8b805b12012-04-18 14:23:14 -070075
Sunny Goyalc0f03d92019-03-22 14:13:36 -070076import org.xmlpull.v1.XmlPullParser;
77
Sunny Goyal05f30882017-05-03 12:42:18 -070078import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080079import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070080import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080081import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070082import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070083import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070084import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070085import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080086import java.util.Locale;
Pinyao Ting0807c942020-04-28 13:58:45 -070087import java.util.concurrent.TimeUnit;
Tracy Zhouc0000452020-03-17 18:28:38 -070088import java.util.function.Supplier;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070091 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080092 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Sunny Goyal05f30882017-05-03 12:42:18 -070094 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Ting0807c942020-04-28 13:58:45 -070095 private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
Sunny Goyal05f30882017-05-03 12:42:18 -070096
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070097 /**
98 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080099 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700100 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800101 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800103 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Pinyao Ting96186af2020-07-20 11:03:39 -0700104 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700105
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800106 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800107
Sunny Goyalf076eae2016-01-11 12:25:10 -0800108 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700109 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110
Pinyao Ting0807c942020-04-28 13:58:45 -0700111 private long mLastRestoreTimestamp = 0L;
112
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800113 /**
114 * $ adb shell dumpsys activity provider com.android.launcher3
115 */
116 @Override
117 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
118 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
119 if (appState == null || !appState.getModel().isModelLoaded()) {
120 return;
121 }
122 appState.getModel().dumpState("", fd, writer, args);
123 }
124
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 @Override
126 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800127 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700128 Log.d(TAG, "Launcher process started");
129 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700130
Sunny Goyalfdbef272017-02-01 12:52:54 -0800131 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800132 // is the first component to get created.
133 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800134 return true;
135 }
136
137 @Override
138 public String getType(Uri uri) {
139 SqlArguments args = new SqlArguments(uri, null, null);
140 if (TextUtils.isEmpty(args.where)) {
141 return "vnd.android.cursor.dir/" + args.table;
142 } else {
143 return "vnd.android.cursor.item/" + args.table;
144 }
145 }
146
Sunny Goyalf076eae2016-01-11 12:25:10 -0800147 /**
148 * Overridden in tests
149 */
150 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700151 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700152 mOpenHelper = DatabaseHelper.createDatabaseHelper(
153 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700154
155 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700156 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
157 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700158 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
159 }
160 // Set is pending to false irrespective of the result, so that it doesn't get
161 // executed again.
162 RestoreDbTask.setPending(getContext(), false);
163 }
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())) {
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) {
261 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700262 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
263 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700264 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
265 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700266 widgetHost.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;
272 }
273 } else {
274 return false;
275 }
276 }
277
Sunny Goyalc5939392018-12-07 11:43:47 -0800278 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700279 }
280
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800281 @Override
282 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700283 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 SqlArguments args = new SqlArguments(uri);
285
286 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700287 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 int numValues = values.length;
289 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400290 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700291 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
292 return 0;
293 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800295 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700296 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800297 }
298
Sunny Goyald1064182015-08-13 12:08:30 -0700299 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 return values.length;
301 }
302
Sunny Goyal161a2142018-10-29 14:02:20 -0700303 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304 @Override
Yura085c8532014-02-11 15:15:29 +0000305 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
306 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700307 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700308 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800309 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700310
311 final int numOperations = operations.size();
312 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
313 for (int i = 0; i < numOperations; i++) {
314 ContentProviderOperation op = operations.get(i);
315 results[i] = op.apply(this, results, i);
316
317 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
318 results[i].count != null && results[i].count > 0;
319 }
320 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800321 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700322 }
323
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700324 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700325 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700326 return results;
Yura085c8532014-02-11 15:15:29 +0000327 }
328 }
329
330 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700332 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
334
335 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336
Louis Begina9c21c62016-08-15 15:18:41 -0700337 if (Binder.getCallingPid() != Process.myPid()
338 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700339 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700340 }
341 int count = db.delete(args.table, args.where, args.args);
342 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800343 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700344 reloadLauncherIfExternal();
345 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800346 return count;
347 }
348
349 @Override
350 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700351 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
353
Chris Wren1ada10d2013-09-13 18:01:38 -0400354 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800355 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
356 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700357 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800358 return count;
359 }
360
Sunny Goyal7779d622015-06-11 16:18:39 -0700361 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700362 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700363 if (Binder.getCallingUid() != Process.myUid()) {
364 return null;
365 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700366 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700367
368 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700369 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
370 clearFlagEmptyDbCreated();
371 return null;
372 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700373 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
374 Bundle result = new Bundle();
375 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Pinyao Ting96186af2020-07-20 11:03:39 -0700376 Utilities.getPrefs(getContext()).getBoolean(
377 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700378 return result;
379 }
Sunny Goyald2497482015-09-22 18:24:19 -0700380 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
381 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700382 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
383 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700384 return result;
385 }
386 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
387 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800388 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
389 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700390 return result;
391 }
392 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
393 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800394 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
395 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700396 return result;
397 }
398 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800399 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700400 return null;
401 }
402 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
403 loadDefaultFavoritesIfNecessary();
404 return null;
405 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700406 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
407 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
408 return null;
409 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700410 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
411 Bundle result = new Bundle();
412 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
413 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
414 return result;
415 }
416 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700417 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
418 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700419 return null;
420 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700421 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
422 mOpenHelper.mHotseatRestoreTableExists = tableExists(
423 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
424 return null;
425 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700426 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700427 final long ts = System.currentTimeMillis();
428 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
429 mLastRestoreTimestamp = ts;
430 RestoreDbTask.restoreIfPossible(
431 getContext(), mOpenHelper, new BackupManager(getContext()));
432 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700433 return null;
434 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800435 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
436 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
437 Bundle result = new Bundle();
438 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Tracy Zhouc0000452020-03-17 18:28:38 -0700439 prepForMigration(
440 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
441 Favorites.TMP_TABLE,
442 () -> mOpenHelper,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700443 () -> DatabaseHelper.createDatabaseHelper(
444 getContext(), true /* forMigration */)));
Tracy Zhouc0000452020-03-17 18:28:38 -0700445 return result;
446 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700447 return null;
Tracy Zhouc0000452020-03-17 18:28:38 -0700448 }
449 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
450 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
451 Bundle result = new Bundle();
452 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
453 prepForMigration(
454 arg /* dbFile */,
455 Favorites.PREVIEW_TABLE_NAME,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700456 () -> DatabaseHelper.createDatabaseHelper(
457 getContext(), arg, true /* forMigration */),
Tracy Zhouc0000452020-03-17 18:28:38 -0700458 () -> mOpenHelper));
Tracy Zhou7df93d22020-01-27 13:44:06 -0800459 return result;
460 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700461 return null;
462 }
463 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
464 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
465 final DatabaseHelper helper = mOpenHelper;
466 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
467 mProviderAuthority = null;
468 } else {
469 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
470 }
471 mOpenHelper = DatabaseHelper.createDatabaseHelper(
472 getContext(), arg, false /* forMigration */);
473 helper.close();
474 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
475 if (app == null) return null;
476 app.getModel().forceReload();
477 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800478 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700479 }
480 return null;
481 }
482
Tracy Zhou7df93d22020-01-27 13:44:06 -0800483 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700484 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800485 }
486
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700487 /**
488 * Deletes any empty folder from the DB.
489 * @return Ids of deleted folders.
490 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700491 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700492 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700493 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700494 // Select folders whose id do not match any container value.
495 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
496 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
497 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
498 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700499 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800500
501 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
502 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700503 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700504 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700505 LauncherSettings.Favorites._ID, folderIds), null);
506 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700507 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800508 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700509 } catch (SQLException ex) {
510 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800511 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700512 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700513 }
514
Adam Cohen091440a2015-03-18 14:16:05 -0700515 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800516 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800517 }
518
Sunny Goyald2497482015-09-22 18:24:19 -0700519 private void clearFlagEmptyDbCreated() {
Pinyao Ting96186af2020-07-20 11:03:39 -0700520 Utilities.getPrefs(getContext()).edit()
521 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700522 }
523
Sunny Goyal42de82f2014-09-26 22:09:29 -0700524 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700525 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526 * 1) From the app restrictions
527 * 2) From a package provided by play store
528 * 3) From a partner configuration APK, already in the system image
529 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700530 */
Sunny Goyald2497482015-09-22 18:24:19 -0700531 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700532 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700533
Pinyao Ting96186af2020-07-20 11:03:39 -0700534 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500535 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200536
Sunny Goyal55fddc82017-04-06 15:02:52 -0700537 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700538 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700539 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700540 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700541 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700542 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700543 final Partner partner = Partner.get(getContext().getPackageManager());
544 if (partner != null && partner.hasDefaultLayout()) {
545 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700546 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700547 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700548 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700549 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700550 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700551 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700552 }
553 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700554
Sunny Goyal9d219682014-10-23 14:21:02 -0700555 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700556 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700558 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800559
560 // There might be some partially restored DB items, due to buggy restore logic in
561 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800562 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700563 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700564 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
565 && usingExternallyProvidedLayout) {
566 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800567 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700568 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700569 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700570 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700571 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700572 }
573 }
574
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700575 /**
576 * Creates workspace loader from an XML resource listed in the app restrictions.
577 *
578 * @return the loader if the restrictions are set and the resource exists; null otherwise.
579 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700580 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700581 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700582 final String authority;
583 if (!TextUtils.isEmpty(mProviderAuthority)) {
584 authority = mProviderAuthority;
585 } else {
586 authority = Settings.Secure.getString(ctx.getContentResolver(),
587 "launcher3.layout.provider");
588 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700589 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700590 return null;
591 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700592
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700593 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
594 if (pi == null) {
595 Log.e(TAG, "No provider found for authority " + authority);
596 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700597 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800598 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700599 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
600 // Read the full xml so that we fail early in case of any IO error.
601 String layout = new String(IOUtils.toByteArray(in));
602 XmlPullParser parser = Xml.newPullParser();
603 parser.setInput(new StringReader(layout));
604
605 Log.d(TAG, "Loading layout from " + authority);
606 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
607 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
608 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
609 } catch (Exception e) {
610 Log.e(TAG, "Error getting layout stream from: " + authority , e);
611 return null;
612 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700613 }
614
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800615 public static Uri getLayoutUri(String authority, Context ctx) {
616 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
617 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
618 .appendQueryParameter("version", "1")
619 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
620 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
Tony Wickhamb87f3cd2021-04-07 15:02:37 -0700621 .appendQueryParameter("hotseatSize", Integer.toString(grid.numDatabaseHotseatIcons))
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800622 .build();
623 }
624
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700625 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700626 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
627 int defaultLayout = idp.defaultLayoutId;
628
Sunny Goyal337c81f2019-12-10 12:19:13 -0800629 if (getContext().getSystemService(UserManager.class).isDemoUser()
630 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700631 defaultLayout = idp.demoModeLayoutId;
632 }
633
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700634 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700635 mOpenHelper, getContext().getResources(), defaultLayout);
636 }
637
Sunny Goyald3849d12015-10-29 10:28:32 -0700638 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800639 * The class is subclassed in tests to create an in-memory db.
640 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800641 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
642 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800643 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700644 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700645 private int mMaxItemId = -1;
646 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700647 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700648 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649
Tracy Zhoued5f3082020-04-20 01:13:26 -0700650 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
651 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700652 }
653
Tracy Zhoued5f3082020-04-20 01:13:26 -0700654 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
655 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700656 if (dbName == null) {
657 dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
658 context).dbFile : LauncherFiles.LAUNCHER_DB;
659 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700660 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700661 // Table creation sometimes fails silently, which leads to a crash loop.
662 // This way, we will try to create a table every time after crash, so the device
663 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700664 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700665 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
666 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700667 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700668 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800669 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700670 databaseHelper.mBackupTableExists = tableExists(
671 databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800672 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700673 databaseHelper.mHotseatRestoreTableExists = tableExists(
674 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700675
Tracy Zhouc0000452020-03-17 18:28:38 -0700676 databaseHelper.initIds();
677 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700678 }
679
680 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700681 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700682 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700683 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800684 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700685 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700686 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700687 }
688
689 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700690 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
691 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700692 if (mMaxItemId == -1) {
693 mMaxItemId = initializeMaxItemId(getWritableDatabase());
694 }
695 if (mMaxScreenId == -1) {
696 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700697 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800698 }
699
700 @Override
701 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800702 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700703
Adam Cohendcd297f2013-06-18 13:13:40 -0700704 mMaxItemId = 1;
705 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700706
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700707 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800708
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800709 // Fresh and clean launcher DB.
710 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700711 if (!mForMigration) {
712 onEmptyDbCreated();
713 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800714 }
715
Sunny Goyal161a2142018-10-29 14:02:20 -0700716 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700717 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700718 dropTable(db, Favorites.BACKUP_TABLE_NAME);
719 mBackupTableExists = false;
720 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700721 if (mHotseatRestoreTableExists) {
722 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
723 mHotseatRestoreTableExists = false;
724 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700725 }
726
Sunny Goyalf076eae2016-01-11 12:25:10 -0800727 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700728 * Re-composite given key in respect to database. If the current db is
729 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
730 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
731 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
732 */
733 String getKey(final String key) {
734 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
735 return key;
736 }
737 return key + "@" + getDatabaseName();
738 }
739
740 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800741 * Overriden in tests.
742 */
743 protected void onEmptyDbCreated() {
744 // Set the flag for empty DB
Pinyao Ting96186af2020-07-20 11:03:39 -0700745 Utilities.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
746 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800747 }
748
Jon Miranda2bc6b932019-03-07 15:24:46 -0800749 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800750 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800751 }
752
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700753 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800754 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800755 }
756
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700757 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700758 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700759 }
760
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800761 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700762 public void onOpen(SQLiteDatabase db) {
763 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700764
765 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
766 if (!schemaFile.exists()) {
767 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700768 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800769 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700770 }
771
772 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700773 * One-time data updated before support of onDowngrade was added. This update is backwards
774 * compatible and can safely be run multiple times.
775 * Note: No new logic should be added here after release, as the new logic might not get
776 * executed on an existing device.
777 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700778 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700779 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
780 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800781 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700782 for (UserHandle user : um.getUserProfiles()) {
783 long serial = um.getSerialNumberForUser(user);
784 String sql = "update favorites set intent = replace(intent, "
785 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
786 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700787 }
788 }
789
790 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700792 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800793 switch (oldVersion) {
794 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800795 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800796 case 12:
797 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800798 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700799 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800800 // Insert new column for holding widget provider name
801 db.execSQL("ALTER TABLE favorites " +
802 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700803 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 } catch (SQLException ex) {
805 Log.e(TAG, ex.getMessage(), ex);
806 // Old version remains, which means we wipe old data
807 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 }
809 }
810 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800811 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800812 // Old version remains, which means we wipe old data
813 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 }
815 }
816 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700817 if (!addIntegerColumn(db, Favorites.RESTORED, 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 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800822 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700823 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800824 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800825 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800826 case 18:
827 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800828 case 19: {
829 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800830 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800831 // Old version remains, which means we wipe old data
832 break;
833 }
834 }
835 case 20:
836 if (!updateFolderItemsRank(db, true)) {
837 break;
838 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800839 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800840 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800841 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700842 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
843 // Old version remains, which means we wipe old data
844 break;
845 }
846 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700847 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700848 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700849 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000850 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700851 case 25:
852 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700853 case 26:
854 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700855 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800856 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700857 break;
858 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800859 case 27: {
860 // Update the favorites table so that the screen ids are ordered based on
861 // workspace page rank.
862 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
863 BaseColumns._ID, null, null, "screenRank");
864 int[] original = finalScreens.toArray();
865 Arrays.sort(original);
866 String updatemap = "";
867 for (int i = 0; i < original.length; i++) {
868 if (finalScreens.get(i) != original[i]) {
869 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
870 Favorites.SCREEN, finalScreens.get(i), original[i]);
871 }
872 }
873 if (!TextUtils.isEmpty(updatemap)) {
874 String query = String.format(Locale.ENGLISH,
875 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
876 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
877 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
878 db.execSQL(query);
879 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700880 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800881 }
882 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800883 // DB Upgraded successfully
884 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400885 }
886
Sunny Goyala2cc6242015-01-14 14:23:02 -0800887 // DB was not upgraded
888 Log.w(TAG, "Destroying all old data.");
889 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800890 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800891
Adam Cohen9b1d0622014-05-21 19:01:57 -0700892 @Override
893 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700894 try {
895 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
896 .onDowngrade(db, oldVersion, newVersion);
897 } catch (Exception e) {
898 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
899 ". Wiping databse.", e);
900 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700901 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700902 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700903
Sunny Goyal42de82f2014-09-26 22:09:29 -0700904 /**
905 * Clears all the data for a fresh start.
906 */
907 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700908 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700909 dropTable(db, Favorites.TABLE_NAME);
910 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800911 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700912 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800913 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700914 }
915
Sunny Goyald2f38192015-02-25 10:46:34 -0800916 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700917 * Removes widgets which are registered to the Launcher's host, but are not present
918 * in our model.
919 */
920 public void removeGhostWidgets(SQLiteDatabase db) {
921 // Get all existing widget ids.
922 final AppWidgetHost host = newLauncherWidgetHost();
923 final int[] allWidgets;
924 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700925 // Although the method was defined in O, it has existed since the beginning of time,
926 // so it might work on older platforms as well.
927 allWidgets = host.getAppWidgetIds();
928 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700929 Log.e(TAG, "getAppWidgetIds not supported", e);
930 return;
931 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800932 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
933 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
934 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700935 for (int widgetId : allWidgets) {
936 if (!validWidgets.contains(widgetId)) {
937 try {
938 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
939 host.deleteAppWidgetId(widgetId);
940 } catch (RuntimeException e) {
941 // Ignore
942 }
943 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700944 }
945 }
946
947 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700948 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
949 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
950 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700951 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700952 try (SQLiteTransaction t = new SQLiteTransaction(db);
953 // Only consider the primary user as other users can't have a shortcut.
954 Cursor c = db.query(Favorites.TABLE_NAME,
955 new String[] { Favorites._ID, Favorites.INTENT},
956 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
957 " AND profileId=" + getDefaultUserSerial(),
958 null, null, null, null);
959 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
960 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
961 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700962 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
963 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
964
965 while (c.moveToNext()) {
966 String intentDescription = c.getString(intentIndex);
967 Intent intent;
968 try {
969 intent = Intent.parseUri(intentDescription, 0);
970 } catch (URISyntaxException e) {
971 Log.e(TAG, "Unable to parse intent", e);
972 continue;
973 }
974
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700975 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700976 continue;
977 }
978
Sunny Goyalefb7e842018-10-04 15:11:00 -0700979 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700980 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700981 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700982 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700983 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700984 } catch (SQLException ex) {
985 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700986 }
987 }
988
Adam Cohen091440a2015-03-18 14:16:05 -0700989 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700990 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800991 if (addRankColumn) {
992 // Insert new column for holding rank
993 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
994 }
995
996 // Get a map for folder ID to folder width
997 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
998 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
999 + " GROUP BY container;",
1000 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1001
1002 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001003 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1004 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001005 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1006 }
1007
1008 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001009 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001010 } catch (SQLException ex) {
1011 // Old version remains, which means we wipe old data
1012 Log.e(TAG, ex.getMessage(), ex);
1013 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001014 }
1015 return true;
1016 }
1017
Sunny Goyal5d85c442015-03-10 13:14:47 -07001018 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001019 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001020 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1021 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001022 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001023 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001024 Log.e(TAG, ex.getMessage(), ex);
1025 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001026 }
1027 return true;
1028 }
1029
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001030 // Generates a new ID to use for an object in your database. This method should be only
1031 // called from the main UI thread. As an exception, we do call it when we call the
1032 // constructor from the worker thread; however, this doesn't extend until after the
1033 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1034 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001035 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001036 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001037 if (mMaxItemId < 0) {
1038 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001040 mMaxItemId += 1;
1041 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001042 }
1043
Sunny Goyal55fddc82017-04-06 15:02:52 -07001044 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001045 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001046 }
1047
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001048 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001049 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001050 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001051 }
1052
Sunny Goyalc5939392018-12-07 11:43:47 -08001053 public void checkId(ContentValues values) {
1054 int id = values.getAsInteger(Favorites._ID);
1055 mMaxItemId = Math.max(id, mMaxItemId);
1056
1057 Integer screen = values.getAsInteger(Favorites.SCREEN);
1058 Integer container = values.getAsInteger(Favorites.CONTAINER);
1059 if (screen != null && container != null
1060 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1061 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001062 }
1063 }
1064
Sunny Goyalefb7e842018-10-04 15:11:00 -07001065 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001066 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001067 }
1068
1069 // Generates a new ID to use for an workspace screen in your database. This method
1070 // should be only called from the main UI thread. As an exception, we do call it when we
1071 // call the constructor from the worker thread; however, this doesn't extend until after the
1072 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1073 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001074 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001075 if (mMaxScreenId < 0) {
1076 throw new RuntimeException("Error: max screen id was not initialized");
1077 }
1078 mMaxScreenId += 1;
1079 return mMaxScreenId;
1080 }
1081
Sunny Goyalefb7e842018-10-04 15:11:00 -07001082 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001083 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
1084 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1085 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001086 }
1087
Adam Cohen091440a2015-03-18 14:16:05 -07001088 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001089 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001090 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001091
1092 // Ensure that the max ids are initialized
1093 mMaxItemId = initializeMaxItemId(db);
1094 mMaxScreenId = initializeMaxScreenId(db);
1095 return count;
1096 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001097 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001098
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001099 /**
1100 * @return the max _id in the provided table.
1101 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001102 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
Pinyao Ting0646dde2020-11-24 11:35:24 -08001103 int max = 0;
1104 try (SQLiteStatement prog = db.compileStatement(
1105 String.format(Locale.ENGLISH, query, args))) {
1106 max = (int) DatabaseUtils.longForQuery(prog, null);
1107 if (max < 0) {
1108 throw new RuntimeException("Error: could not query max id");
1109 }
1110 } catch (IllegalArgumentException exception) {
1111 String message = exception.getMessage();
1112 if (message.contains("re-open") && message.contains("already-closed")) {
1113 // Don't crash trying to end a transaction an an already closed DB. See b/173162852.
1114 } else {
1115 throw exception;
1116 }
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001117 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001118 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001119 }
1120
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001121 static class SqlArguments {
1122 public final String table;
1123 public final String where;
1124 public final String[] args;
1125
1126 SqlArguments(Uri url, String where, String[] args) {
1127 if (url.getPathSegments().size() == 1) {
1128 this.table = url.getPathSegments().get(0);
1129 this.where = where;
1130 this.args = args;
1131 } else if (url.getPathSegments().size() != 2) {
1132 throw new IllegalArgumentException("Invalid URI: " + url);
1133 } else if (!TextUtils.isEmpty(where)) {
1134 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1135 } else {
1136 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001137 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001138 this.args = null;
1139 }
1140 }
1141
1142 SqlArguments(Uri url) {
1143 if (url.getPathSegments().size() == 1) {
1144 table = url.getPathSegments().get(0);
1145 where = null;
1146 args = null;
1147 } else {
1148 throw new IllegalArgumentException("Invalid URI: " + url);
1149 }
1150 }
1151 }
Adam Cohen72960972014-01-15 18:13:55 -08001152}