blob: aeed16aa28b5aef911e2c4362ce8a2d51b53f123 [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;
Michael Jurka8b805b12012-04-18 14:23:14 -070074
Sunny Goyalc0f03d92019-03-22 14:13:36 -070075import org.xmlpull.v1.XmlPullParser;
76
Sunny Goyal05f30882017-05-03 12:42:18 -070077import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080078import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070079import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080080import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070081import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070082import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070083import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070084import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080085import java.util.Locale;
Pinyao Ting0807c942020-04-28 13:58:45 -070086import java.util.concurrent.TimeUnit;
Tracy Zhouc0000452020-03-17 18:28:38 -070087import java.util.function.Supplier;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070090 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080091 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Sunny Goyal05f30882017-05-03 12:42:18 -070093 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Ting0807c942020-04-28 13:58:45 -070094 private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
Sunny Goyal05f30882017-05-03 12:42:18 -070095
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070096 /**
97 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080098 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070099 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800100 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800102 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Pinyao Ting96186af2020-07-20 11:03:39 -0700103 public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
Winson Chung3d503fb2011-07-13 17:25:49 -0700104
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800105 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106
Sunny Goyalf076eae2016-01-11 12:25:10 -0800107 protected DatabaseHelper mOpenHelper;
Pinyao Ting96186af2020-07-20 11:03:39 -0700108 protected String mProviderAuthority;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109
Pinyao Ting0807c942020-04-28 13:58:45 -0700110 private long mLastRestoreTimestamp = 0L;
111
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800112 /**
113 * $ adb shell dumpsys activity provider com.android.launcher3
114 */
115 @Override
116 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
117 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
118 if (appState == null || !appState.getModel().isModelLoaded()) {
119 return;
120 }
121 appState.getModel().dumpState("", fd, writer, args);
122 }
123
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800124 @Override
125 public boolean onCreate() {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800126 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700127 Log.d(TAG, "Launcher process started");
128 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700129
Sunny Goyalfdbef272017-02-01 12:52:54 -0800130 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800131 // is the first component to get created.
132 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133 return true;
134 }
135
136 @Override
137 public String getType(Uri uri) {
138 SqlArguments args = new SqlArguments(uri, null, null);
139 if (TextUtils.isEmpty(args.where)) {
140 return "vnd.android.cursor.dir/" + args.table;
141 } else {
142 return "vnd.android.cursor.item/" + args.table;
143 }
144 }
145
Sunny Goyalf076eae2016-01-11 12:25:10 -0800146 /**
147 * Overridden in tests
148 */
149 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700150 if (mOpenHelper == null) {
Tracy Zhoued5f3082020-04-20 01:13:26 -0700151 mOpenHelper = DatabaseHelper.createDatabaseHelper(
152 getContext(), false /* forMigration */);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700153
154 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700155 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
156 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700157 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
158 }
159 // Set is pending to false irrespective of the result, so that it doesn't get
160 // executed again.
161 RestoreDbTask.setPending(getContext(), false);
162 }
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())) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800169 return false;
170 }
171
Tracy Zhouc0000452020-03-17 18:28:38 -0700172 final DatabaseHelper helper = src.get();
173 mOpenHelper = dst.get();
174 copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
175 mOpenHelper.getWritableDatabase(), targetTableName, getContext());
176 helper.close();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800177 return true;
178 }
179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 @Override
181 public Cursor query(Uri uri, String[] projection, String selection,
182 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700183 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
185 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
186 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
187 qb.setTables(args.table);
188
Romain Guy73b979d2009-06-09 12:57:21 -0700189 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
Pinyao Ting0960b452020-10-14 11:17:04 -0700191 final Bundle extra = new Bundle();
192 extra.putString(LauncherSettings.Settings.EXTRA_DB_NAME, mOpenHelper.getDatabaseName());
193 result.setExtras(extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 result.setNotificationUri(getContext().getContentResolver(), uri);
195
196 return result;
197 }
198
Sunny Goyalefb7e842018-10-04 15:11:00 -0700199 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700200 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500201 if (values == null) {
202 throw new RuntimeException("Error: attempting to insert null values");
203 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800204 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700205 throw new RuntimeException("Error: attempting to add item without specifying an id");
206 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800207 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700208 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700209 }
210
Sunny Goyald1064182015-08-13 12:08:30 -0700211 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800212 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700213 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
214 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800215 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700216 }
217 }
218 }
219
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 @Override
221 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700222 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800223 SqlArguments args = new SqlArguments(uri);
224
Sunny Goyald1064182015-08-13 12:08:30 -0700225 // In very limited cases, we support system|signature permission apps to modify the db.
226 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700227 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700228 return null;
229 }
230 }
231
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800232 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400233 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700234 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800235 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800236 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237
238 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800239 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800240 return uri;
241 }
242
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700243 private boolean initializeExternalAdd(ContentValues values) {
244 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700245 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700246 values.put(LauncherSettings.Favorites._ID, id);
247
248 // 2. In the case of an app widget, and if no app widget id is specified, we
249 // attempt allocate and bind the widget.
250 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
251 if (itemType != null &&
252 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
253 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
254
255 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
256 ComponentName cn = ComponentName.unflattenFromString(
257 values.getAsString(Favorites.APPWIDGET_PROVIDER));
258
259 if (cn != null) {
260 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700261 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
262 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700263 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
264 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700265 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700266 return false;
267 }
268 } catch (RuntimeException e) {
269 Log.e(TAG, "Failed to initialize external widget", e);
270 return false;
271 }
272 } else {
273 return false;
274 }
275 }
276
Sunny Goyalc5939392018-12-07 11:43:47 -0800277 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700278 }
279
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800280 @Override
281 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700282 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800283 SqlArguments args = new SqlArguments(uri);
284
285 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700286 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 int numValues = values.length;
288 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400289 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700290 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
291 return 0;
292 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800293 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800294 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700295 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800296 }
297
Sunny Goyald1064182015-08-13 12:08:30 -0700298 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 return values.length;
300 }
301
Sunny Goyal161a2142018-10-29 14:02:20 -0700302 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 @Override
Yura085c8532014-02-11 15:15:29 +0000304 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
305 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700306 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700307 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800308 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700309
310 final int numOperations = operations.size();
311 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
312 for (int i = 0; i < numOperations; i++) {
313 ContentProviderOperation op = operations.get(i);
314 results[i] = op.apply(this, results, i);
315
316 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
317 results[i].count != null && results[i].count > 0;
318 }
319 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800320 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700321 }
322
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700323 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700324 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700325 return results;
Yura085c8532014-02-11 15:15:29 +0000326 }
327 }
328
329 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700331 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
333
334 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335
Louis Begina9c21c62016-08-15 15:18:41 -0700336 if (Binder.getCallingPid() != Process.myPid()
337 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700338 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700339 }
340 int count = db.delete(args.table, args.where, args.args);
341 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800342 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700343 reloadLauncherIfExternal();
344 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 return count;
346 }
347
348 @Override
349 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700350 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
352
Chris Wren1ada10d2013-09-13 18:01:38 -0400353 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
355 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700356 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800357 return count;
358 }
359
Sunny Goyal7779d622015-06-11 16:18:39 -0700360 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700361 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700362 if (Binder.getCallingUid() != Process.myUid()) {
363 return null;
364 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700365 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700366
367 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700368 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
369 clearFlagEmptyDbCreated();
370 return null;
371 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700372 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
373 Bundle result = new Bundle();
374 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Pinyao Ting96186af2020-07-20 11:03:39 -0700375 Utilities.getPrefs(getContext()).getBoolean(
376 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700377 return result;
378 }
Sunny Goyald2497482015-09-22 18:24:19 -0700379 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
380 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700381 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
382 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700383 return result;
384 }
385 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
386 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800387 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
388 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700389 return result;
390 }
391 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
392 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800393 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
394 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700395 return result;
396 }
397 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800398 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700399 return null;
400 }
401 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
402 loadDefaultFavoritesIfNecessary();
403 return null;
404 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700405 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
406 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
407 return null;
408 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700409 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
410 Bundle result = new Bundle();
411 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
412 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
413 return result;
414 }
415 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700416 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
417 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700418 return null;
419 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700420 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
421 mOpenHelper.mHotseatRestoreTableExists = tableExists(
422 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
423 return null;
424 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700425 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700426 final long ts = System.currentTimeMillis();
427 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
428 mLastRestoreTimestamp = ts;
429 RestoreDbTask.restoreIfPossible(
430 getContext(), mOpenHelper, new BackupManager(getContext()));
431 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700432 return null;
433 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800434 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
435 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
436 Bundle result = new Bundle();
437 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Tracy Zhouc0000452020-03-17 18:28:38 -0700438 prepForMigration(
439 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
440 Favorites.TMP_TABLE,
441 () -> mOpenHelper,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700442 () -> DatabaseHelper.createDatabaseHelper(
443 getContext(), true /* forMigration */)));
Tracy Zhouc0000452020-03-17 18:28:38 -0700444 return result;
445 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700446 return null;
Tracy Zhouc0000452020-03-17 18:28:38 -0700447 }
448 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
449 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
450 Bundle result = new Bundle();
451 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
452 prepForMigration(
453 arg /* dbFile */,
454 Favorites.PREVIEW_TABLE_NAME,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700455 () -> DatabaseHelper.createDatabaseHelper(
456 getContext(), arg, true /* forMigration */),
Tracy Zhouc0000452020-03-17 18:28:38 -0700457 () -> mOpenHelper));
Tracy Zhou7df93d22020-01-27 13:44:06 -0800458 return result;
459 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700460 return null;
461 }
462 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
463 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
464 final DatabaseHelper helper = mOpenHelper;
465 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
466 mProviderAuthority = null;
467 } else {
468 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
469 }
470 mOpenHelper = DatabaseHelper.createDatabaseHelper(
471 getContext(), arg, false /* forMigration */);
472 helper.close();
473 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
474 if (app == null) return null;
475 app.getModel().forceReload();
476 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800477 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700478 }
479 return null;
480 }
481
Tracy Zhou7df93d22020-01-27 13:44:06 -0800482 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700483 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800484 }
485
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700486 /**
487 * Deletes any empty folder from the DB.
488 * @return Ids of deleted folders.
489 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700490 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700491 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700492 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700493 // Select folders whose id do not match any container value.
494 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
495 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
496 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
497 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700498 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800499
500 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
501 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700502 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700503 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700504 LauncherSettings.Favorites._ID, folderIds), null);
505 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700506 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800507 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700508 } catch (SQLException ex) {
509 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800510 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700511 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700512 }
513
Adam Cohen091440a2015-03-18 14:16:05 -0700514 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800515 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800516 }
517
Sunny Goyald2497482015-09-22 18:24:19 -0700518 private void clearFlagEmptyDbCreated() {
Pinyao Ting96186af2020-07-20 11:03:39 -0700519 Utilities.getPrefs(getContext()).edit()
520 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700521 }
522
Sunny Goyal42de82f2014-09-26 22:09:29 -0700523 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700524 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700525 * 1) From the app restrictions
526 * 2) From a package provided by play store
527 * 3) From a partner configuration APK, already in the system image
528 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700529 */
Sunny Goyald2497482015-09-22 18:24:19 -0700530 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700531 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700532
Pinyao Ting96186af2020-07-20 11:03:39 -0700533 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500534 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200535
Sunny Goyal55fddc82017-04-06 15:02:52 -0700536 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700537 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700538 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700539 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700540 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700541 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700542 final Partner partner = Partner.get(getContext().getPackageManager());
543 if (partner != null && partner.hasDefaultLayout()) {
544 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700545 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700546 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700547 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700549 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700550 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700551 }
552 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700553
Sunny Goyal9d219682014-10-23 14:21:02 -0700554 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700555 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700556 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700557 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800558
559 // There might be some partially restored DB items, due to buggy restore logic in
560 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800561 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700562 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700563 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
564 && usingExternallyProvidedLayout) {
565 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800566 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700567 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700569 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700570 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700571 }
572 }
573
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700574 /**
575 * Creates workspace loader from an XML resource listed in the app restrictions.
576 *
577 * @return the loader if the restrictions are set and the resource exists; null otherwise.
578 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700579 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700580 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700581 final String authority;
582 if (!TextUtils.isEmpty(mProviderAuthority)) {
583 authority = mProviderAuthority;
584 } else {
585 authority = Settings.Secure.getString(ctx.getContentResolver(),
586 "launcher3.layout.provider");
587 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700588 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700589 return null;
590 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700591
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700592 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
593 if (pi == null) {
594 Log.e(TAG, "No provider found for authority " + authority);
595 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700596 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800597 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700598 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
599 // Read the full xml so that we fail early in case of any IO error.
600 String layout = new String(IOUtils.toByteArray(in));
601 XmlPullParser parser = Xml.newPullParser();
602 parser.setInput(new StringReader(layout));
603
604 Log.d(TAG, "Loading layout from " + authority);
605 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
606 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
607 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
608 } catch (Exception e) {
609 Log.e(TAG, "Error getting layout stream from: " + authority , e);
610 return null;
611 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700612 }
613
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800614 public static Uri getLayoutUri(String authority, Context ctx) {
615 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
616 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
617 .appendQueryParameter("version", "1")
618 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
619 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
620 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
621 .build();
622 }
623
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700624 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700625 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
626 int defaultLayout = idp.defaultLayoutId;
627
Sunny Goyal337c81f2019-12-10 12:19:13 -0800628 if (getContext().getSystemService(UserManager.class).isDemoUser()
629 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700630 defaultLayout = idp.demoModeLayoutId;
631 }
632
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700633 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700634 mOpenHelper, getContext().getResources(), defaultLayout);
635 }
636
Sunny Goyald3849d12015-10-29 10:28:32 -0700637 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800638 * The class is subclassed in tests to create an in-memory db.
639 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800640 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
641 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800642 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700643 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700644 private int mMaxItemId = -1;
645 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700646 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700647 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648
Tracy Zhoued5f3082020-04-20 01:13:26 -0700649 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
650 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700651 }
652
Tracy Zhoued5f3082020-04-20 01:13:26 -0700653 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
654 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700655 if (dbName == null) {
656 dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
657 context).dbFile : LauncherFiles.LAUNCHER_DB;
658 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700659 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700660 // Table creation sometimes fails silently, which leads to a crash loop.
661 // This way, we will try to create a table every time after crash, so the device
662 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700663 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700664 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
665 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700666 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700667 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800668 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700669 databaseHelper.mBackupTableExists = tableExists(
670 databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800671 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700672 databaseHelper.mHotseatRestoreTableExists = tableExists(
673 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700674
Tracy Zhouc0000452020-03-17 18:28:38 -0700675 databaseHelper.initIds();
676 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700677 }
678
679 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700680 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700681 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700682 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800683 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700684 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700685 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700686 }
687
688 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700689 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
690 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700691 if (mMaxItemId == -1) {
692 mMaxItemId = initializeMaxItemId(getWritableDatabase());
693 }
694 if (mMaxScreenId == -1) {
695 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700696 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 }
698
699 @Override
700 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800701 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700702
Adam Cohendcd297f2013-06-18 13:13:40 -0700703 mMaxItemId = 1;
704 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700705
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700706 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800708 // Fresh and clean launcher DB.
709 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700710 if (!mForMigration) {
711 onEmptyDbCreated();
712 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800713 }
714
Sunny Goyal161a2142018-10-29 14:02:20 -0700715 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700716 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700717 dropTable(db, Favorites.BACKUP_TABLE_NAME);
718 mBackupTableExists = false;
719 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700720 if (mHotseatRestoreTableExists) {
721 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
722 mHotseatRestoreTableExists = false;
723 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700724 }
725
Sunny Goyalf076eae2016-01-11 12:25:10 -0800726 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700727 * Re-composite given key in respect to database. If the current db is
728 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
729 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
730 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
731 */
732 String getKey(final String key) {
733 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
734 return key;
735 }
736 return key + "@" + getDatabaseName();
737 }
738
739 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800740 * Overriden in tests.
741 */
742 protected void onEmptyDbCreated() {
743 // Set the flag for empty DB
Pinyao Ting96186af2020-07-20 11:03:39 -0700744 Utilities.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
745 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800746 }
747
Jon Miranda2bc6b932019-03-07 15:24:46 -0800748 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800749 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800750 }
751
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700752 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800753 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800754 }
755
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700756 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700757 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700758 }
759
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800760 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700761 public void onOpen(SQLiteDatabase db) {
762 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700763
764 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
765 if (!schemaFile.exists()) {
766 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700767 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800768 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700769 }
770
771 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700772 * One-time data updated before support of onDowngrade was added. This update is backwards
773 * compatible and can safely be run multiple times.
774 * Note: No new logic should be added here after release, as the new logic might not get
775 * executed on an existing device.
776 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700777 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700778 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
779 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800780 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700781 for (UserHandle user : um.getUserProfiles()) {
782 long serial = um.getSerialNumberForUser(user);
783 String sql = "update favorites set intent = replace(intent, "
784 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
785 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700786 }
787 }
788
789 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800790 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700791 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800792 switch (oldVersion) {
793 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800794 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800795 case 12:
796 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800797 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700798 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800799 // Insert new column for holding widget provider name
800 db.execSQL("ALTER TABLE favorites " +
801 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700802 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800803 } catch (SQLException ex) {
804 Log.e(TAG, ex.getMessage(), ex);
805 // Old version remains, which means we wipe old data
806 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800807 }
808 }
809 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800810 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800811 // Old version remains, which means we wipe old data
812 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800813 }
814 }
815 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700816 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800817 // Old version remains, which means we wipe old data
818 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800819 }
820 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800821 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700822 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800823 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800825 case 18:
826 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800827 case 19: {
828 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800829 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800830 // Old version remains, which means we wipe old data
831 break;
832 }
833 }
834 case 20:
835 if (!updateFolderItemsRank(db, true)) {
836 break;
837 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800838 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800839 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800840 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700841 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
842 // Old version remains, which means we wipe old data
843 break;
844 }
845 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700846 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700847 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700848 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000849 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700850 case 25:
851 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700852 case 26:
853 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700854 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800855 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700856 break;
857 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800858 case 27: {
859 // Update the favorites table so that the screen ids are ordered based on
860 // workspace page rank.
861 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
862 BaseColumns._ID, null, null, "screenRank");
863 int[] original = finalScreens.toArray();
864 Arrays.sort(original);
865 String updatemap = "";
866 for (int i = 0; i < original.length; i++) {
867 if (finalScreens.get(i) != original[i]) {
868 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
869 Favorites.SCREEN, finalScreens.get(i), original[i]);
870 }
871 }
872 if (!TextUtils.isEmpty(updatemap)) {
873 String query = String.format(Locale.ENGLISH,
874 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
875 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
876 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
877 db.execSQL(query);
878 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700879 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800880 }
881 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800882 // DB Upgraded successfully
883 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400884 }
885
Sunny Goyala2cc6242015-01-14 14:23:02 -0800886 // DB was not upgraded
887 Log.w(TAG, "Destroying all old data.");
888 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800889 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800890
Adam Cohen9b1d0622014-05-21 19:01:57 -0700891 @Override
892 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700893 try {
894 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
895 .onDowngrade(db, oldVersion, newVersion);
896 } catch (Exception e) {
897 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
898 ". Wiping databse.", e);
899 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700900 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700901 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700902
Sunny Goyal42de82f2014-09-26 22:09:29 -0700903 /**
904 * Clears all the data for a fresh start.
905 */
906 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700907 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700908 dropTable(db, Favorites.TABLE_NAME);
909 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800910 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700911 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800912 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700913 }
914
Sunny Goyald2f38192015-02-25 10:46:34 -0800915 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700916 * Removes widgets which are registered to the Launcher's host, but are not present
917 * in our model.
918 */
919 public void removeGhostWidgets(SQLiteDatabase db) {
920 // Get all existing widget ids.
921 final AppWidgetHost host = newLauncherWidgetHost();
922 final int[] allWidgets;
923 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700924 // Although the method was defined in O, it has existed since the beginning of time,
925 // so it might work on older platforms as well.
926 allWidgets = host.getAppWidgetIds();
927 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700928 Log.e(TAG, "getAppWidgetIds not supported", e);
929 return;
930 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800931 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
932 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
933 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700934 for (int widgetId : allWidgets) {
935 if (!validWidgets.contains(widgetId)) {
936 try {
937 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
938 host.deleteAppWidgetId(widgetId);
939 } catch (RuntimeException e) {
940 // Ignore
941 }
942 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700943 }
944 }
945
946 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700947 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
948 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
949 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700950 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700951 try (SQLiteTransaction t = new SQLiteTransaction(db);
952 // Only consider the primary user as other users can't have a shortcut.
953 Cursor c = db.query(Favorites.TABLE_NAME,
954 new String[] { Favorites._ID, Favorites.INTENT},
955 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
956 " AND profileId=" + getDefaultUserSerial(),
957 null, null, null, null);
958 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
959 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
960 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700961 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
962 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
963
964 while (c.moveToNext()) {
965 String intentDescription = c.getString(intentIndex);
966 Intent intent;
967 try {
968 intent = Intent.parseUri(intentDescription, 0);
969 } catch (URISyntaxException e) {
970 Log.e(TAG, "Unable to parse intent", e);
971 continue;
972 }
973
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700974 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700975 continue;
976 }
977
Sunny Goyalefb7e842018-10-04 15:11:00 -0700978 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700979 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700980 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700981 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700982 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700983 } catch (SQLException ex) {
984 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700985 }
986 }
987
Adam Cohen091440a2015-03-18 14:16:05 -0700988 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700989 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800990 if (addRankColumn) {
991 // Insert new column for holding rank
992 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
993 }
994
995 // Get a map for folder ID to folder width
996 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
997 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
998 + " GROUP BY container;",
999 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
1000
1001 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001002 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1003 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001004 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1005 }
1006
1007 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001008 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001009 } catch (SQLException ex) {
1010 // Old version remains, which means we wipe old data
1011 Log.e(TAG, ex.getMessage(), ex);
1012 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001013 }
1014 return true;
1015 }
1016
Sunny Goyal5d85c442015-03-10 13:14:47 -07001017 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001018 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001019 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1020 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001021 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001022 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001023 Log.e(TAG, ex.getMessage(), ex);
1024 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001025 }
1026 return true;
1027 }
1028
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001029 // Generates a new ID to use for an object in your database. This method should be only
1030 // called from the main UI thread. As an exception, we do call it when we call the
1031 // constructor from the worker thread; however, this doesn't extend until after the
1032 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1033 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001034 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001035 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001036 if (mMaxItemId < 0) {
1037 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001038 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001039 mMaxItemId += 1;
1040 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001041 }
1042
Sunny Goyal55fddc82017-04-06 15:02:52 -07001043 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001044 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001045 }
1046
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001047 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001048 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001049 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001050 }
1051
Sunny Goyalc5939392018-12-07 11:43:47 -08001052 public void checkId(ContentValues values) {
1053 int id = values.getAsInteger(Favorites._ID);
1054 mMaxItemId = Math.max(id, mMaxItemId);
1055
1056 Integer screen = values.getAsInteger(Favorites.SCREEN);
1057 Integer container = values.getAsInteger(Favorites.CONTAINER);
1058 if (screen != null && container != null
1059 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1060 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001061 }
1062 }
1063
Sunny Goyalefb7e842018-10-04 15:11:00 -07001064 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001065 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001066 }
1067
1068 // Generates a new ID to use for an workspace screen in your database. This method
1069 // should be only called from the main UI thread. As an exception, we do call it when we
1070 // call the constructor from the worker thread; however, this doesn't extend until after the
1071 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1072 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001073 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001074 if (mMaxScreenId < 0) {
1075 throw new RuntimeException("Error: max screen id was not initialized");
1076 }
1077 mMaxScreenId += 1;
1078 return mMaxScreenId;
1079 }
1080
Sunny Goyalefb7e842018-10-04 15:11:00 -07001081 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001082 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
1083 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1084 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001085 }
1086
Adam Cohen091440a2015-03-18 14:16:05 -07001087 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001088 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001089 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001090
1091 // Ensure that the max ids are initialized
1092 mMaxItemId = initializeMaxItemId(db);
1093 mMaxScreenId = initializeMaxScreenId(db);
1094 return count;
1095 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001096 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001097
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001098 /**
1099 * @return the max _id in the provided table.
1100 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001101 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
1102 int max = (int) DatabaseUtils.longForQuery(db,
1103 String.format(Locale.ENGLISH, query, args),
1104 null);
1105 if (max < 0) {
1106 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001107 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001108 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001109 }
1110
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001111 static class SqlArguments {
1112 public final String table;
1113 public final String where;
1114 public final String[] args;
1115
1116 SqlArguments(Uri url, String where, String[] args) {
1117 if (url.getPathSegments().size() == 1) {
1118 this.table = url.getPathSegments().get(0);
1119 this.where = where;
1120 this.args = args;
1121 } else if (url.getPathSegments().size() != 2) {
1122 throw new IllegalArgumentException("Invalid URI: " + url);
1123 } else if (!TextUtils.isEmpty(where)) {
1124 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1125 } else {
1126 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001127 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001128 this.args = null;
1129 }
1130 }
1131
1132 SqlArguments(Uri url) {
1133 if (url.getPathSegments().size() == 1) {
1134 table = url.getPathSegments().get(0);
1135 where = null;
1136 args = null;
1137 } else {
1138 throw new IllegalArgumentException("Invalid URI: " + url);
1139 }
1140 }
1141 }
Adam Cohen72960972014-01-15 18:13:55 -08001142}