blob: 19a314ffe26c454d1635291fca281ace9a991cc1 [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);
191 result.setNotificationUri(getContext().getContentResolver(), uri);
192
193 return result;
194 }
195
Sunny Goyalefb7e842018-10-04 15:11:00 -0700196 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700197 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500198 if (values == null) {
199 throw new RuntimeException("Error: attempting to insert null values");
200 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800201 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700202 throw new RuntimeException("Error: attempting to add item without specifying an id");
203 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800204 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700205 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700206 }
207
Sunny Goyald1064182015-08-13 12:08:30 -0700208 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800209 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700210 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
211 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800212 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700213 }
214 }
215 }
216
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 @Override
218 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700219 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 SqlArguments args = new SqlArguments(uri);
221
Sunny Goyald1064182015-08-13 12:08:30 -0700222 // In very limited cases, we support system|signature permission apps to modify the db.
223 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700224 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700225 return null;
226 }
227 }
228
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400230 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700231 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800232 if (rowId < 0) return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800233 onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800234
235 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800236 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800237 return uri;
238 }
239
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700240 private boolean initializeExternalAdd(ContentValues values) {
241 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700242 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700243 values.put(LauncherSettings.Favorites._ID, id);
244
245 // 2. In the case of an app widget, and if no app widget id is specified, we
246 // attempt allocate and bind the widget.
247 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
248 if (itemType != null &&
249 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
250 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
251
252 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
253 ComponentName cn = ComponentName.unflattenFromString(
254 values.getAsString(Favorites.APPWIDGET_PROVIDER));
255
256 if (cn != null) {
257 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700258 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
259 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700260 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
261 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700262 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700263 return false;
264 }
265 } catch (RuntimeException e) {
266 Log.e(TAG, "Failed to initialize external widget", e);
267 return false;
268 }
269 } else {
270 return false;
271 }
272 }
273
Sunny Goyalc5939392018-12-07 11:43:47 -0800274 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700275 }
276
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800277 @Override
278 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700279 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800280 SqlArguments args = new SqlArguments(uri);
281
282 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700283 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800284 int numValues = values.length;
285 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400286 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700287 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
288 return 0;
289 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800291 onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700292 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800293 }
294
Sunny Goyald1064182015-08-13 12:08:30 -0700295 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800296 return values.length;
297 }
298
Sunny Goyal161a2142018-10-29 14:02:20 -0700299 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 @Override
Yura085c8532014-02-11 15:15:29 +0000301 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
302 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700303 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700304 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800305 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700306
307 final int numOperations = operations.size();
308 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
309 for (int i = 0; i < numOperations; i++) {
310 ContentProviderOperation op = operations.get(i);
311 results[i] = op.apply(this, results, i);
312
313 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
314 results[i].count != null && results[i].count > 0;
315 }
316 if (isAddOrDelete) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800317 onAddOrDeleteOp(t.getDb());
Sunny Goyal161a2142018-10-29 14:02:20 -0700318 }
319
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700320 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700321 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700322 return results;
Yura085c8532014-02-11 15:15:29 +0000323 }
324 }
325
326 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700328 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
330
331 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332
Louis Begina9c21c62016-08-15 15:18:41 -0700333 if (Binder.getCallingPid() != Process.myPid()
334 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700335 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700336 }
337 int count = db.delete(args.table, args.where, args.args);
338 if (count > 0) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800339 onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700340 reloadLauncherIfExternal();
341 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 return count;
343 }
344
345 @Override
346 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700347 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
349
Chris Wren1ada10d2013-09-13 18:01:38 -0400350 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
352 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700353 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354 return count;
355 }
356
Sunny Goyal7779d622015-06-11 16:18:39 -0700357 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700358 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700359 if (Binder.getCallingUid() != Process.myUid()) {
360 return null;
361 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700362 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700363
364 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700365 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
366 clearFlagEmptyDbCreated();
367 return null;
368 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700369 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
370 Bundle result = new Bundle();
371 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Pinyao Ting96186af2020-07-20 11:03:39 -0700372 Utilities.getPrefs(getContext()).getBoolean(
373 mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false));
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700374 return result;
375 }
Sunny Goyald2497482015-09-22 18:24:19 -0700376 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
377 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700378 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
379 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700380 return result;
381 }
382 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
383 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800384 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
385 mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700386 return result;
387 }
388 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
389 Bundle result = new Bundle();
Tracy Zhou7df93d22020-01-27 13:44:06 -0800390 result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
391 mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700392 return result;
393 }
394 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800395 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700396 return null;
397 }
398 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
399 loadDefaultFavoritesIfNecessary();
400 return null;
401 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700402 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
403 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
404 return null;
405 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700406 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
407 Bundle result = new Bundle();
408 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
409 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
410 return result;
411 }
412 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700413 mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
414 Favorites.BACKUP_TABLE_NAME);
Sunny Goyal161a2142018-10-29 14:02:20 -0700415 return null;
416 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700417 case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
418 mOpenHelper.mHotseatRestoreTableExists = tableExists(
419 mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
420 return null;
421 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700422 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Ting0807c942020-04-28 13:58:45 -0700423 final long ts = System.currentTimeMillis();
424 if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
425 mLastRestoreTimestamp = ts;
426 RestoreDbTask.restoreIfPossible(
427 getContext(), mOpenHelper, new BackupManager(getContext()));
428 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700429 return null;
430 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800431 case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
432 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
433 Bundle result = new Bundle();
434 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
Tracy Zhouc0000452020-03-17 18:28:38 -0700435 prepForMigration(
436 InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
437 Favorites.TMP_TABLE,
438 () -> mOpenHelper,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700439 () -> DatabaseHelper.createDatabaseHelper(
440 getContext(), true /* forMigration */)));
Tracy Zhouc0000452020-03-17 18:28:38 -0700441 return result;
442 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700443 return null;
Tracy Zhouc0000452020-03-17 18:28:38 -0700444 }
445 case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
446 if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
447 Bundle result = new Bundle();
448 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
449 prepForMigration(
450 arg /* dbFile */,
451 Favorites.PREVIEW_TABLE_NAME,
Tracy Zhoued5f3082020-04-20 01:13:26 -0700452 () -> DatabaseHelper.createDatabaseHelper(
453 getContext(), arg, true /* forMigration */),
Tracy Zhouc0000452020-03-17 18:28:38 -0700454 () -> mOpenHelper));
Tracy Zhou7df93d22020-01-27 13:44:06 -0800455 return result;
456 }
Pinyao Ting96186af2020-07-20 11:03:39 -0700457 return null;
458 }
459 case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
460 if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
461 final DatabaseHelper helper = mOpenHelper;
462 if (extras == null || !extras.containsKey(KEY_LAYOUT_PROVIDER_AUTHORITY)) {
463 mProviderAuthority = null;
464 } else {
465 mProviderAuthority = extras.getString(KEY_LAYOUT_PROVIDER_AUTHORITY);
466 }
467 mOpenHelper = DatabaseHelper.createDatabaseHelper(
468 getContext(), arg, false /* forMigration */);
469 helper.close();
470 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
471 if (app == null) return null;
472 app.getModel().forceReload();
473 return null;
Tracy Zhou7df93d22020-01-27 13:44:06 -0800474 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700475 }
476 return null;
477 }
478
Tracy Zhou7df93d22020-01-27 13:44:06 -0800479 private void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700480 mOpenHelper.onAddOrDeleteOp(db);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800481 }
482
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700483 /**
484 * Deletes any empty folder from the DB.
485 * @return Ids of deleted folders.
486 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700487 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700488 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700489 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700490 // Select folders whose id do not match any container value.
491 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
492 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
493 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
494 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700495 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800496
497 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
498 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700499 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700500 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700501 LauncherSettings.Favorites._ID, folderIds), null);
502 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700503 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800504 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700505 } catch (SQLException ex) {
506 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800507 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700508 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700509 }
510
Adam Cohen091440a2015-03-18 14:16:05 -0700511 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800512 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800513 }
514
Sunny Goyald2497482015-09-22 18:24:19 -0700515 private void clearFlagEmptyDbCreated() {
Pinyao Ting96186af2020-07-20 11:03:39 -0700516 Utilities.getPrefs(getContext()).edit()
517 .remove(mOpenHelper.getKey(EMPTY_DATABASE_CREATED)).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700518 }
519
Sunny Goyal42de82f2014-09-26 22:09:29 -0700520 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700521 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700522 * 1) From the app restrictions
523 * 2) From a package provided by play store
524 * 3) From a partner configuration APK, already in the system image
525 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700526 */
Sunny Goyald2497482015-09-22 18:24:19 -0700527 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700528 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700529
Pinyao Ting96186af2020-07-20 11:03:39 -0700530 if (sp.getBoolean(mOpenHelper.getKey(EMPTY_DATABASE_CREATED), false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500531 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200532
Sunny Goyal55fddc82017-04-06 15:02:52 -0700533 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700535 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700536 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700537 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700538 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700539 final Partner partner = Partner.get(getContext().getPackageManager());
540 if (partner != null && partner.hasDefaultLayout()) {
541 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700542 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700543 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700544 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700546 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700547 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700548 }
549 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700550
Sunny Goyal9d219682014-10-23 14:21:02 -0700551 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700552 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700553 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700554 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800555
556 // There might be some partially restored DB items, due to buggy restore logic in
557 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800558 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700559 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700560 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
561 && usingExternallyProvidedLayout) {
562 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800563 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700564 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700565 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700566 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700567 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700568 }
569 }
570
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700571 /**
572 * Creates workspace loader from an XML resource listed in the app restrictions.
573 *
574 * @return the loader if the restrictions are set and the resource exists; null otherwise.
575 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700576 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700577 Context ctx = getContext();
Pinyao Ting96186af2020-07-20 11:03:39 -0700578 final String authority;
579 if (!TextUtils.isEmpty(mProviderAuthority)) {
580 authority = mProviderAuthority;
581 } else {
582 authority = Settings.Secure.getString(ctx.getContentResolver(),
583 "launcher3.layout.provider");
584 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700585 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700586 return null;
587 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700588
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700589 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
590 if (pi == null) {
591 Log.e(TAG, "No provider found for authority " + authority);
592 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700593 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800594 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700595 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
596 // Read the full xml so that we fail early in case of any IO error.
597 String layout = new String(IOUtils.toByteArray(in));
598 XmlPullParser parser = Xml.newPullParser();
599 parser.setInput(new StringReader(layout));
600
601 Log.d(TAG, "Loading layout from " + authority);
602 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
603 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
604 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
605 } catch (Exception e) {
606 Log.e(TAG, "Error getting layout stream from: " + authority , e);
607 return null;
608 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700609 }
610
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800611 public static Uri getLayoutUri(String authority, Context ctx) {
612 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
613 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
614 .appendQueryParameter("version", "1")
615 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
616 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
617 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
618 .build();
619 }
620
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700621 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700622 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
623 int defaultLayout = idp.defaultLayoutId;
624
Sunny Goyal337c81f2019-12-10 12:19:13 -0800625 if (getContext().getSystemService(UserManager.class).isDemoUser()
626 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700627 defaultLayout = idp.demoModeLayoutId;
628 }
629
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700630 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700631 mOpenHelper, getContext().getResources(), defaultLayout);
632 }
633
Sunny Goyald3849d12015-10-29 10:28:32 -0700634 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800635 * The class is subclassed in tests to create an in-memory db.
636 */
Tracy Zhou7df93d22020-01-27 13:44:06 -0800637 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
638 LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 private final Context mContext;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700640 private final boolean mForMigration;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700641 private int mMaxItemId = -1;
642 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700643 private boolean mBackupTableExists;
Samuel Fufaf667a132020-05-29 14:47:42 -0700644 private boolean mHotseatRestoreTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645
Tracy Zhoued5f3082020-04-20 01:13:26 -0700646 static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
647 return createDatabaseHelper(context, null, forMigration);
Tracy Zhouc0000452020-03-17 18:28:38 -0700648 }
649
Tracy Zhoued5f3082020-04-20 01:13:26 -0700650 static DatabaseHelper createDatabaseHelper(Context context, String dbName,
651 boolean forMigration) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700652 if (dbName == null) {
653 dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
654 context).dbFile : LauncherFiles.LAUNCHER_DB;
655 }
Tracy Zhoued5f3082020-04-20 01:13:26 -0700656 DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700657 // Table creation sometimes fails silently, which leads to a crash loop.
658 // This way, we will try to create a table every time after crash, so the device
659 // would eventually be able to recover.
Tracy Zhouc0000452020-03-17 18:28:38 -0700660 if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700661 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
662 // This operation is a no-op if the table already exists.
Tracy Zhouc0000452020-03-17 18:28:38 -0700663 databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700664 }
Tracy Zhou7df93d22020-01-27 13:44:06 -0800665 if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
Tracy Zhouc0000452020-03-17 18:28:38 -0700666 databaseHelper.mBackupTableExists = tableExists(
667 databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Tracy Zhou7df93d22020-01-27 13:44:06 -0800668 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700669 databaseHelper.mHotseatRestoreTableExists = tableExists(
670 databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700671
Tracy Zhouc0000452020-03-17 18:28:38 -0700672 databaseHelper.initIds();
673 return databaseHelper;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700674 }
675
676 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700677 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700678 */
Tracy Zhoued5f3082020-04-20 01:13:26 -0700679 public DatabaseHelper(Context context, String dbName, boolean forMigration) {
Tracy Zhou7df93d22020-01-27 13:44:06 -0800680 super(context, dbName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700681 mContext = context;
Tracy Zhoued5f3082020-04-20 01:13:26 -0700682 mForMigration = forMigration;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700683 }
684
685 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700686 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
687 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700688 if (mMaxItemId == -1) {
689 mMaxItemId = initializeMaxItemId(getWritableDatabase());
690 }
691 if (mMaxScreenId == -1) {
692 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700693 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800694 }
695
696 @Override
697 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800698 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700699
Adam Cohendcd297f2013-06-18 13:13:40 -0700700 mMaxItemId = 1;
701 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700702
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700703 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800704
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800705 // Fresh and clean launcher DB.
706 mMaxItemId = initializeMaxItemId(db);
Tracy Zhoued5f3082020-04-20 01:13:26 -0700707 if (!mForMigration) {
708 onEmptyDbCreated();
709 }
Sunny Goyalf076eae2016-01-11 12:25:10 -0800710 }
711
Sunny Goyal161a2142018-10-29 14:02:20 -0700712 protected void onAddOrDeleteOp(SQLiteDatabase db) {
Pinyao Ting26c4e232020-04-15 22:25:06 -0700713 if (mBackupTableExists) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700714 dropTable(db, Favorites.BACKUP_TABLE_NAME);
715 mBackupTableExists = false;
716 }
Samuel Fufaf667a132020-05-29 14:47:42 -0700717 if (mHotseatRestoreTableExists) {
718 dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
719 mHotseatRestoreTableExists = false;
720 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700721 }
722
Sunny Goyalf076eae2016-01-11 12:25:10 -0800723 /**
Pinyao Ting96186af2020-07-20 11:03:39 -0700724 * Re-composite given key in respect to database. If the current db is
725 * {@link LauncherFiles#LAUNCHER_DB}, return the key as-is. Otherwise append the db name to
726 * given key. e.g. consider key="EMPTY_DATABASE_CREATED", dbName="minimal.db", the returning
727 * string will be "EMPTY_DATABASE_CREATED@minimal.db".
728 */
729 String getKey(final String key) {
730 if (TextUtils.equals(getDatabaseName(), LauncherFiles.LAUNCHER_DB)) {
731 return key;
732 }
733 return key + "@" + getDatabaseName();
734 }
735
736 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800737 * Overriden in tests.
738 */
739 protected void onEmptyDbCreated() {
740 // Set the flag for empty DB
Pinyao Ting96186af2020-07-20 11:03:39 -0700741 Utilities.getPrefs(mContext).edit().putBoolean(getKey(EMPTY_DATABASE_CREATED), true)
742 .commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800743 }
744
Jon Miranda2bc6b932019-03-07 15:24:46 -0800745 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800746 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800747 }
748
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700749 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800750 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800751 }
752
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700753 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700754 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700755 }
756
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700758 public void onOpen(SQLiteDatabase db) {
759 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700760
761 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
762 if (!schemaFile.exists()) {
763 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700764 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800765 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700766 }
767
768 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700769 * One-time data updated before support of onDowngrade was added. This update is backwards
770 * compatible and can safely be run multiple times.
771 * Note: No new logic should be added here after release, as the new logic might not get
772 * executed on an existing device.
773 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700774 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700775 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
776 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800777 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700778 for (UserHandle user : um.getUserProfiles()) {
779 long serial = um.getSerialNumberForUser(user);
780 String sql = "update favorites set intent = replace(intent, "
781 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
782 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700783 }
784 }
785
786 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800787 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700788 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800789 switch (oldVersion) {
790 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800791 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800792 case 12:
793 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800794 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700795 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800796 // Insert new column for holding widget provider name
797 db.execSQL("ALTER TABLE favorites " +
798 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700799 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800800 } catch (SQLException ex) {
801 Log.e(TAG, ex.getMessage(), ex);
802 // Old version remains, which means we wipe old data
803 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800804 }
805 }
806 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800807 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800808 // Old version remains, which means we wipe old data
809 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800810 }
811 }
812 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700813 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800814 // Old version remains, which means we wipe old data
815 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800816 }
817 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800818 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700819 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800820 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800821 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800822 case 18:
823 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800824 case 19: {
825 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800826 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800827 // Old version remains, which means we wipe old data
828 break;
829 }
830 }
831 case 20:
832 if (!updateFolderItemsRank(db, true)) {
833 break;
834 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800835 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800836 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800837 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700838 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
839 // Old version remains, which means we wipe old data
840 break;
841 }
842 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700843 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700844 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700845 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000846 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700847 case 25:
848 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700849 case 26:
850 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700851 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800852 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700853 break;
854 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800855 case 27: {
856 // Update the favorites table so that the screen ids are ordered based on
857 // workspace page rank.
858 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
859 BaseColumns._ID, null, null, "screenRank");
860 int[] original = finalScreens.toArray();
861 Arrays.sort(original);
862 String updatemap = "";
863 for (int i = 0; i < original.length; i++) {
864 if (finalScreens.get(i) != original[i]) {
865 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
866 Favorites.SCREEN, finalScreens.get(i), original[i]);
867 }
868 }
869 if (!TextUtils.isEmpty(updatemap)) {
870 String query = String.format(Locale.ENGLISH,
871 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
872 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
873 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
874 db.execSQL(query);
875 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700876 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800877 }
878 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800879 // DB Upgraded successfully
880 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400881 }
882
Sunny Goyala2cc6242015-01-14 14:23:02 -0800883 // DB was not upgraded
884 Log.w(TAG, "Destroying all old data.");
885 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800886 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800887
Adam Cohen9b1d0622014-05-21 19:01:57 -0700888 @Override
889 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700890 try {
891 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
892 .onDowngrade(db, oldVersion, newVersion);
893 } catch (Exception e) {
894 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
895 ". Wiping databse.", e);
896 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700897 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700898 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700899
Sunny Goyal42de82f2014-09-26 22:09:29 -0700900 /**
901 * Clears all the data for a fresh start.
902 */
903 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700904 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700905 dropTable(db, Favorites.TABLE_NAME);
906 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800907 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700908 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800909 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700910 }
911
Sunny Goyald2f38192015-02-25 10:46:34 -0800912 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700913 * Removes widgets which are registered to the Launcher's host, but are not present
914 * in our model.
915 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700916 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700917 public void removeGhostWidgets(SQLiteDatabase db) {
918 // Get all existing widget ids.
919 final AppWidgetHost host = newLauncherWidgetHost();
920 final int[] allWidgets;
921 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700922 // Although the method was defined in O, it has existed since the beginning of time,
923 // so it might work on older platforms as well.
924 allWidgets = host.getAppWidgetIds();
925 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700926 Log.e(TAG, "getAppWidgetIds not supported", e);
927 return;
928 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800929 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
930 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
931 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700932 for (int widgetId : allWidgets) {
933 if (!validWidgets.contains(widgetId)) {
934 try {
935 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
936 host.deleteAppWidgetId(widgetId);
937 } catch (RuntimeException e) {
938 // Ignore
939 }
940 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700941 }
942 }
943
944 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700945 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
946 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
947 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700948 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700949 try (SQLiteTransaction t = new SQLiteTransaction(db);
950 // Only consider the primary user as other users can't have a shortcut.
951 Cursor c = db.query(Favorites.TABLE_NAME,
952 new String[] { Favorites._ID, Favorites.INTENT},
953 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
954 " AND profileId=" + getDefaultUserSerial(),
955 null, null, null, null);
956 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
957 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
958 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700959 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
960 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
961
962 while (c.moveToNext()) {
963 String intentDescription = c.getString(intentIndex);
964 Intent intent;
965 try {
966 intent = Intent.parseUri(intentDescription, 0);
967 } catch (URISyntaxException e) {
968 Log.e(TAG, "Unable to parse intent", e);
969 continue;
970 }
971
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700972 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700973 continue;
974 }
975
Sunny Goyalefb7e842018-10-04 15:11:00 -0700976 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700977 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700978 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700979 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700980 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700981 } catch (SQLException ex) {
982 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700983 }
984 }
985
Adam Cohen091440a2015-03-18 14:16:05 -0700986 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700987 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800988 if (addRankColumn) {
989 // Insert new column for holding rank
990 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
991 }
992
993 // Get a map for folder ID to folder width
994 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
995 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
996 + " GROUP BY container;",
997 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
998
999 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -08001000 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
1001 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -08001002 new Object[] {c.getLong(1) + 1, c.getLong(0)});
1003 }
1004
1005 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001006 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -08001007 } catch (SQLException ex) {
1008 // Old version remains, which means we wipe old data
1009 Log.e(TAG, ex.getMessage(), ex);
1010 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -08001011 }
1012 return true;
1013 }
1014
Sunny Goyal5d85c442015-03-10 13:14:47 -07001015 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001016 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -07001017 db.execSQL("ALTER TABLE favorites ADD COLUMN "
1018 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -07001019 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +01001020 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +01001021 Log.e(TAG, ex.getMessage(), ex);
1022 return false;
Kenny Guyed131872014-04-30 03:02:21 +01001023 }
1024 return true;
1025 }
1026
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001027 // Generates a new ID to use for an object in your database. This method should be only
1028 // called from the main UI thread. As an exception, we do call it when we call the
1029 // constructor from the worker thread; however, this doesn't extend until after the
1030 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1031 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001032 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001033 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001034 if (mMaxItemId < 0) {
1035 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001036 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001037 mMaxItemId += 1;
1038 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001039 }
1040
Sunny Goyal55fddc82017-04-06 15:02:52 -07001041 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001042 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001043 }
1044
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001045 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001046 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001047 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001048 }
1049
Sunny Goyalc5939392018-12-07 11:43:47 -08001050 public void checkId(ContentValues values) {
1051 int id = values.getAsInteger(Favorites._ID);
1052 mMaxItemId = Math.max(id, mMaxItemId);
1053
1054 Integer screen = values.getAsInteger(Favorites.SCREEN);
1055 Integer container = values.getAsInteger(Favorites.CONTAINER);
1056 if (screen != null && container != null
1057 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
1058 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -05001059 }
1060 }
1061
Sunny Goyalefb7e842018-10-04 15:11:00 -07001062 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001063 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001064 }
1065
1066 // Generates a new ID to use for an workspace screen in your database. This method
1067 // should be only called from the main UI thread. As an exception, we do call it when we
1068 // call the constructor from the worker thread; however, this doesn't extend until after the
1069 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1070 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001071 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001072 if (mMaxScreenId < 0) {
1073 throw new RuntimeException("Error: max screen id was not initialized");
1074 }
1075 mMaxScreenId += 1;
1076 return mMaxScreenId;
1077 }
1078
Sunny Goyalefb7e842018-10-04 15:11:00 -07001079 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -08001080 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
1081 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
1082 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001083 }
1084
Adam Cohen091440a2015-03-18 14:16:05 -07001085 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001086 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -08001087 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -07001088
1089 // Ensure that the max ids are initialized
1090 mMaxItemId = initializeMaxItemId(db);
1091 mMaxScreenId = initializeMaxScreenId(db);
1092 return count;
1093 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001094 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001095
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001096 /**
1097 * @return the max _id in the provided table.
1098 */
Sunny Goyalc5939392018-12-07 11:43:47 -08001099 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
1100 int max = (int) DatabaseUtils.longForQuery(db,
1101 String.format(Locale.ENGLISH, query, args),
1102 null);
1103 if (max < 0) {
1104 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001105 }
Sunny Goyalc5939392018-12-07 11:43:47 -08001106 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001107 }
1108
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001109 static class SqlArguments {
1110 public final String table;
1111 public final String where;
1112 public final String[] args;
1113
1114 SqlArguments(Uri url, String where, String[] args) {
1115 if (url.getPathSegments().size() == 1) {
1116 this.table = url.getPathSegments().get(0);
1117 this.where = where;
1118 this.args = args;
1119 } else if (url.getPathSegments().size() != 2) {
1120 throw new IllegalArgumentException("Invalid URI: " + url);
1121 } else if (!TextUtils.isEmpty(where)) {
1122 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1123 } else {
1124 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001125 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001126 this.args = null;
1127 }
1128 }
1129
1130 SqlArguments(Uri url) {
1131 if (url.getPathSegments().size() == 1) {
1132 table = url.getPathSegments().get(0);
1133 where = null;
1134 args = null;
1135 } else {
1136 throw new IllegalArgumentException("Invalid URI: " + url);
1137 }
1138 }
1139 }
Adam Cohen72960972014-01-15 18:13:55 -08001140}