blob: b0ab35c5b011d87d5e4aa7b9abeb2727b1cd623d [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyal161a2142018-10-29 14:02:20 -070019import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
20import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
Pinyao Tingad5f2402019-12-10 14:56:34 -080021import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
Sunny Goyal161a2142018-10-29 14:02:20 -070022
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070023import android.annotation.TargetApi;
Jon Miranda2bc6b932019-03-07 15:24:46 -080024import android.app.backup.BackupManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070025import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070026import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080027import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070028import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000029import android.content.ContentProviderOperation;
30import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070031import android.content.ContentUris;
32import android.content.ContentValues;
33import android.content.Context;
34import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000035import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070036import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070037import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070038import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080040import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070042import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070044import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070045import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070047import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.Bundle;
Pinyao Tingad5f2402019-12-10 14:56:34 -080049import android.os.Handler;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070088 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080089 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Sunny Goyal05f30882017-05-03 12:42:18 -070091 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
Pinyao Tingad5f2402019-12-10 14:56:34 -080092 private static final String TOKEN_RESTORE_BACKUP_TABLE = "restore_backup_table";
93 private static final long RESTORE_BACKUP_TABLE_DELAY = 60000;
Sunny Goyal05f30882017-05-03 12:42:18 -070094
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070095 /**
96 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080097 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070098 */
Sunny Goyalc5939392018-12-07 11:43:47 -080099 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Sunny Goyal4276e7b2018-11-26 23:44:41 -0800101 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -0700102
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800103 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104
Sunny Goyalf076eae2016-01-11 12:25:10 -0800105 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800107 /**
108 * $ adb shell dumpsys activity provider com.android.launcher3
109 */
110 @Override
111 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
112 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
113 if (appState == null || !appState.getModel().isModelLoaded()) {
114 return;
115 }
116 appState.getModel().dumpState("", fd, writer, args);
117 }
118
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119 @Override
120 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800121 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700122 Log.d(TAG, "Launcher process started");
123 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700124
Sunny Goyalfdbef272017-02-01 12:52:54 -0800125 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800126 // is the first component to get created.
127 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800128 return true;
129 }
130
131 @Override
132 public String getType(Uri uri) {
133 SqlArguments args = new SqlArguments(uri, null, null);
134 if (TextUtils.isEmpty(args.where)) {
135 return "vnd.android.cursor.dir/" + args.table;
136 } else {
137 return "vnd.android.cursor.item/" + args.table;
138 }
139 }
140
Sunny Goyalf076eae2016-01-11 12:25:10 -0800141 /**
142 * Overridden in tests
143 */
144 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700145 if (mOpenHelper == null) {
Sunny Goyal01615a62019-09-20 12:00:07 -0700146 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700147
148 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700149 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
150 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700151 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
152 }
153 // Set is pending to false irrespective of the result, so that it doesn't get
154 // executed again.
155 RestoreDbTask.setPending(getContext(), false);
156 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Cursor query(Uri uri, String[] projection, String selection,
162 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
166 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
167 qb.setTables(args.table);
168
Romain Guy73b979d2009-06-09 12:57:21 -0700169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
171 result.setNotificationUri(getContext().getContentResolver(), uri);
172
173 return result;
174 }
175
Sunny Goyalefb7e842018-10-04 15:11:00 -0700176 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500178 if (values == null) {
179 throw new RuntimeException("Error: attempting to insert null values");
180 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800181 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 throw new RuntimeException("Error: attempting to add item without specifying an id");
183 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800184 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700185 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700186 }
187
Sunny Goyald1064182015-08-13 12:08:30 -0700188 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800189 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700190 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
191 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800192 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700193 }
194 }
195 }
196
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 @Override
198 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700199 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 SqlArguments args = new SqlArguments(uri);
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 // In very limited cases, we support system|signature permission apps to modify the db.
203 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700204 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700205 return null;
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700211 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800212 if (rowId < 0) return null;
Sunny Goyal161a2142018-10-29 14:02:20 -0700213 mOpenHelper.onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214
215 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800216 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 return uri;
218 }
219
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700220 private boolean initializeExternalAdd(ContentValues values) {
221 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700222 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700223 values.put(LauncherSettings.Favorites._ID, id);
224
225 // 2. In the case of an app widget, and if no app widget id is specified, we
226 // attempt allocate and bind the widget.
227 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
228 if (itemType != null &&
229 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
230 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
231
232 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
233 ComponentName cn = ComponentName.unflattenFromString(
234 values.getAsString(Favorites.APPWIDGET_PROVIDER));
235
236 if (cn != null) {
237 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700238 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
239 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700240 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
241 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700242 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700243 return false;
244 }
245 } catch (RuntimeException e) {
246 Log.e(TAG, "Failed to initialize external widget", e);
247 return false;
248 }
249 } else {
250 return false;
251 }
252 }
253
Sunny Goyalc5939392018-12-07 11:43:47 -0800254 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700255 }
256
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800257 @Override
258 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700259 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800260 SqlArguments args = new SqlArguments(uri);
261
262 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700263 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 int numValues = values.length;
265 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400266 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700267 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
268 return 0;
269 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800270 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700271 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700272 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800273 }
274
Sunny Goyald1064182015-08-13 12:08:30 -0700275 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800276 return values.length;
277 }
278
Sunny Goyal161a2142018-10-29 14:02:20 -0700279 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800280 @Override
Yura085c8532014-02-11 15:15:29 +0000281 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
282 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700283 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700284 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800285 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700286
287 final int numOperations = operations.size();
288 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
289 for (int i = 0; i < numOperations; i++) {
290 ContentProviderOperation op = operations.get(i);
291 results[i] = op.apply(this, results, i);
292
293 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
294 results[i].count != null && results[i].count > 0;
295 }
296 if (isAddOrDelete) {
297 mOpenHelper.onAddOrDeleteOp(t.getDb());
298 }
299
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700300 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700301 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700302 return results;
Yura085c8532014-02-11 15:15:29 +0000303 }
304 }
305
306 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700308 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800309 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
310
311 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800312
Louis Begina9c21c62016-08-15 15:18:41 -0700313 if (Binder.getCallingPid() != Process.myPid()
314 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700315 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700316 }
317 int count = db.delete(args.table, args.where, args.args);
318 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700319 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700320 reloadLauncherIfExternal();
321 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 return count;
323 }
324
325 @Override
326 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700327 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
329
Chris Wren1ada10d2013-09-13 18:01:38 -0400330 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
332 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700333 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 return count;
335 }
336
Sunny Goyal7779d622015-06-11 16:18:39 -0700337 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700338 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700339 if (Binder.getCallingUid() != Process.myUid()) {
340 return null;
341 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700342 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700343
344 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700345 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
346 clearFlagEmptyDbCreated();
347 return null;
348 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700349 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
350 Bundle result = new Bundle();
351 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
352 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
353 return result;
354 }
Sunny Goyald2497482015-09-22 18:24:19 -0700355 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
356 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700357 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
358 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700359 return result;
360 }
361 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
362 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700363 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700364 return result;
365 }
366 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
367 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700368 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700369 return result;
370 }
371 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800372 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700373 return null;
374 }
375 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
376 loadDefaultFavoritesIfNecessary();
377 return null;
378 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700379 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
380 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
381 return null;
382 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700383 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
384 Bundle result = new Bundle();
385 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
386 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
387 return result;
388 }
389 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
390 mOpenHelper.mBackupTableExists =
391 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
392 return null;
393 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700394 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
Pinyao Tingad5f2402019-12-10 14:56:34 -0800395 final Handler handler = MODEL_EXECUTOR.getHandler();
396 handler.removeCallbacksAndMessages(TOKEN_RESTORE_BACKUP_TABLE);
397 handler.postDelayed(() -> RestoreDbTask.restoreIfPossible(
398 getContext(), mOpenHelper, new BackupManager(getContext())),
399 TOKEN_RESTORE_BACKUP_TABLE, RESTORE_BACKUP_TABLE_DELAY);
Pinyao Tingba9c5572019-09-24 14:25:46 -0700400 return null;
401 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700402 }
403 return null;
404 }
405
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700406 /**
407 * Deletes any empty folder from the DB.
408 * @return Ids of deleted folders.
409 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700410 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700411 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700412 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700413 // Select folders whose id do not match any container value.
414 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
415 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
416 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
417 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700418 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800419
420 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
421 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700422 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700423 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700424 LauncherSettings.Favorites._ID, folderIds), null);
425 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700426 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800427 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 } catch (SQLException ex) {
429 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800430 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700431 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 }
433
Adam Cohen091440a2015-03-18 14:16:05 -0700434 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800435 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800436 }
437
Sunny Goyald2497482015-09-22 18:24:19 -0700438 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700439 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700440 }
441
Sunny Goyal42de82f2014-09-26 22:09:29 -0700442 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700443 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700444 * 1) From the app restrictions
445 * 2) From a package provided by play store
446 * 3) From a partner configuration APK, already in the system image
447 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700448 */
Sunny Goyald2497482015-09-22 18:24:19 -0700449 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700450 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700451
Winson Chungc763c4e2013-07-19 13:49:06 -0700452 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500453 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200454
Sunny Goyal55fddc82017-04-06 15:02:52 -0700455 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700456 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700457 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700458 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700459 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700460 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700461 final Partner partner = Partner.get(getContext().getPackageManager());
462 if (partner != null && partner.hasDefaultLayout()) {
463 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700464 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700465 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700466 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700467 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700468 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700469 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700470 }
471 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700472
Sunny Goyal9d219682014-10-23 14:21:02 -0700473 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700474 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700475 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700476 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800477
478 // There might be some partially restored DB items, due to buggy restore logic in
479 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800480 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700481 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700482 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
483 && usingExternallyProvidedLayout) {
484 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800485 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700486 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700487 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700488 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700489 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700490 }
491 }
492
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700493 /**
494 * Creates workspace loader from an XML resource listed in the app restrictions.
495 *
496 * @return the loader if the restrictions are set and the resource exists; null otherwise.
497 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700498 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700499 Context ctx = getContext();
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700500 String authority = Settings.Secure.getString(ctx.getContentResolver(),
501 "launcher3.layout.provider");
502 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700503 return null;
504 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700505
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700506 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
507 if (pi == null) {
508 Log.e(TAG, "No provider found for authority " + authority);
509 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700510 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800511 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700512 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
513 // Read the full xml so that we fail early in case of any IO error.
514 String layout = new String(IOUtils.toByteArray(in));
515 XmlPullParser parser = Xml.newPullParser();
516 parser.setInput(new StringReader(layout));
517
518 Log.d(TAG, "Loading layout from " + authority);
519 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
520 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
521 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
522 } catch (Exception e) {
523 Log.e(TAG, "Error getting layout stream from: " + authority , e);
524 return null;
525 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526 }
527
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800528 public static Uri getLayoutUri(String authority, Context ctx) {
529 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
530 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
531 .appendQueryParameter("version", "1")
532 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
533 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
534 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
535 .build();
536 }
537
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700538 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700539 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
540 int defaultLayout = idp.defaultLayoutId;
541
Sunny Goyal337c81f2019-12-10 12:19:13 -0800542 if (getContext().getSystemService(UserManager.class).isDemoUser()
543 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700544 defaultLayout = idp.demoModeLayoutId;
545 }
546
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700547 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700548 mOpenHelper, getContext().getResources(), defaultLayout);
549 }
550
Sunny Goyald3849d12015-10-29 10:28:32 -0700551 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800552 * The class is subclassed in tests to create an in-memory db.
553 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800554 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800555 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700556 private int mMaxItemId = -1;
557 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700558 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559
Sunny Goyal01615a62019-09-20 12:00:07 -0700560 DatabaseHelper(Context context) {
561 this(context, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700562 // Table creation sometimes fails silently, which leads to a crash loop.
563 // This way, we will try to create a table every time after crash, so the device
564 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700565 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700566 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
567 // This operation is a no-op if the table already exists.
568 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700569 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700570 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700571
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 initIds();
573 }
574
575 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700576 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 */
Sunny Goyal01615a62019-09-20 12:00:07 -0700578 public DatabaseHelper(Context context, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800579 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700580 mContext = context;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700581 }
582
583 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700584 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
585 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700586 if (mMaxItemId == -1) {
587 mMaxItemId = initializeMaxItemId(getWritableDatabase());
588 }
589 if (mMaxScreenId == -1) {
590 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700591 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800592 }
593
594 @Override
595 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800596 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700597
Adam Cohendcd297f2013-06-18 13:13:40 -0700598 mMaxItemId = 1;
599 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700600
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700601 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800603 // Fresh and clean launcher DB.
604 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800605 onEmptyDbCreated();
606 }
607
Sunny Goyal161a2142018-10-29 14:02:20 -0700608 protected void onAddOrDeleteOp(SQLiteDatabase db) {
609 if (mBackupTableExists) {
610 dropTable(db, Favorites.BACKUP_TABLE_NAME);
611 mBackupTableExists = false;
612 }
613 }
614
Sunny Goyalf076eae2016-01-11 12:25:10 -0800615 /**
616 * Overriden in tests.
617 */
618 protected void onEmptyDbCreated() {
619 // Set the flag for empty DB
620 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800621 }
622
Jon Miranda2bc6b932019-03-07 15:24:46 -0800623 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800624 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800625 }
626
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700627 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800628 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 }
630
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700631 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700632 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700633 }
634
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700636 public void onOpen(SQLiteDatabase db) {
637 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700638
639 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
640 if (!schemaFile.exists()) {
641 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700642 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800643 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700644 }
645
646 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700647 * One-time data updated before support of onDowngrade was added. This update is backwards
648 * compatible and can safely be run multiple times.
649 * Note: No new logic should be added here after release, as the new logic might not get
650 * executed on an existing device.
651 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700652 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700653 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
654 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800655 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700656 for (UserHandle user : um.getUserProfiles()) {
657 long serial = um.getSerialNumberForUser(user);
658 String sql = "update favorites set intent = replace(intent, "
659 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
660 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700661 }
662 }
663
664 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800665 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700666 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800667 switch (oldVersion) {
668 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800669 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800670 case 12:
671 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800672 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700673 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800674 // Insert new column for holding widget provider name
675 db.execSQL("ALTER TABLE favorites " +
676 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700677 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800678 } catch (SQLException ex) {
679 Log.e(TAG, ex.getMessage(), ex);
680 // Old version remains, which means we wipe old data
681 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800682 }
683 }
684 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800685 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800686 // Old version remains, which means we wipe old data
687 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800688 }
689 }
690 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700691 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800692 // Old version remains, which means we wipe old data
693 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800694 }
695 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800696 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700697 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800698 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800699 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800700 case 18:
701 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 case 19: {
703 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800704 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800705 // Old version remains, which means we wipe old data
706 break;
707 }
708 }
709 case 20:
710 if (!updateFolderItemsRank(db, true)) {
711 break;
712 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800713 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800714 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800715 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700716 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
717 // Old version remains, which means we wipe old data
718 break;
719 }
720 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700721 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700722 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700723 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000724 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700725 case 25:
726 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700727 case 26:
728 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700729 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800730 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700731 break;
732 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800733 case 27: {
734 // Update the favorites table so that the screen ids are ordered based on
735 // workspace page rank.
736 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
737 BaseColumns._ID, null, null, "screenRank");
738 int[] original = finalScreens.toArray();
739 Arrays.sort(original);
740 String updatemap = "";
741 for (int i = 0; i < original.length; i++) {
742 if (finalScreens.get(i) != original[i]) {
743 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
744 Favorites.SCREEN, finalScreens.get(i), original[i]);
745 }
746 }
747 if (!TextUtils.isEmpty(updatemap)) {
748 String query = String.format(Locale.ENGLISH,
749 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
750 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
751 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
752 db.execSQL(query);
753 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700754 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800755 }
756 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 // DB Upgraded successfully
758 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400759 }
760
Sunny Goyala2cc6242015-01-14 14:23:02 -0800761 // DB was not upgraded
762 Log.w(TAG, "Destroying all old data.");
763 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800764 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800765
Adam Cohen9b1d0622014-05-21 19:01:57 -0700766 @Override
767 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700768 try {
769 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
770 .onDowngrade(db, oldVersion, newVersion);
771 } catch (Exception e) {
772 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
773 ". Wiping databse.", e);
774 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700775 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700776 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700777
Sunny Goyal42de82f2014-09-26 22:09:29 -0700778 /**
779 * Clears all the data for a fresh start.
780 */
781 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700782 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700783 dropTable(db, Favorites.TABLE_NAME);
784 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800785 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700786 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800787 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700788 }
789
Sunny Goyald2f38192015-02-25 10:46:34 -0800790 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700791 * Removes widgets which are registered to the Launcher's host, but are not present
792 * in our model.
793 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700794 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700795 public void removeGhostWidgets(SQLiteDatabase db) {
796 // Get all existing widget ids.
797 final AppWidgetHost host = newLauncherWidgetHost();
798 final int[] allWidgets;
799 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700800 // Although the method was defined in O, it has existed since the beginning of time,
801 // so it might work on older platforms as well.
802 allWidgets = host.getAppWidgetIds();
803 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700804 Log.e(TAG, "getAppWidgetIds not supported", e);
805 return;
806 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800807 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
808 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
809 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700810 for (int widgetId : allWidgets) {
811 if (!validWidgets.contains(widgetId)) {
812 try {
813 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
814 host.deleteAppWidgetId(widgetId);
815 } catch (RuntimeException e) {
816 // Ignore
817 }
818 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700819 }
820 }
821
822 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700823 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
824 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
825 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700826 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700827 try (SQLiteTransaction t = new SQLiteTransaction(db);
828 // Only consider the primary user as other users can't have a shortcut.
829 Cursor c = db.query(Favorites.TABLE_NAME,
830 new String[] { Favorites._ID, Favorites.INTENT},
831 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
832 " AND profileId=" + getDefaultUserSerial(),
833 null, null, null, null);
834 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
835 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
836 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700837 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
838 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
839
840 while (c.moveToNext()) {
841 String intentDescription = c.getString(intentIndex);
842 Intent intent;
843 try {
844 intent = Intent.parseUri(intentDescription, 0);
845 } catch (URISyntaxException e) {
846 Log.e(TAG, "Unable to parse intent", e);
847 continue;
848 }
849
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700850 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700851 continue;
852 }
853
Sunny Goyalefb7e842018-10-04 15:11:00 -0700854 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700855 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700856 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700857 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700858 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700859 } catch (SQLException ex) {
860 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700861 }
862 }
863
Adam Cohen091440a2015-03-18 14:16:05 -0700864 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700865 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800866 if (addRankColumn) {
867 // Insert new column for holding rank
868 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
869 }
870
871 // Get a map for folder ID to folder width
872 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
873 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
874 + " GROUP BY container;",
875 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
876
877 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800878 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
879 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800880 new Object[] {c.getLong(1) + 1, c.getLong(0)});
881 }
882
883 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700884 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800885 } catch (SQLException ex) {
886 // Old version remains, which means we wipe old data
887 Log.e(TAG, ex.getMessage(), ex);
888 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800889 }
890 return true;
891 }
892
Sunny Goyal5d85c442015-03-10 13:14:47 -0700893 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700894 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700895 db.execSQL("ALTER TABLE favorites ADD COLUMN "
896 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700897 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100898 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100899 Log.e(TAG, ex.getMessage(), ex);
900 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100901 }
902 return true;
903 }
904
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700905 // Generates a new ID to use for an object in your database. This method should be only
906 // called from the main UI thread. As an exception, we do call it when we call the
907 // constructor from the worker thread; however, this doesn't extend until after the
908 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
909 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700910 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700911 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700912 if (mMaxItemId < 0) {
913 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700914 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700915 mMaxItemId += 1;
916 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700917 }
918
Sunny Goyal55fddc82017-04-06 15:02:52 -0700919 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700920 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700921 }
922
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700923 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700924 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700925 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700926 }
927
Sunny Goyalc5939392018-12-07 11:43:47 -0800928 public void checkId(ContentValues values) {
929 int id = values.getAsInteger(Favorites._ID);
930 mMaxItemId = Math.max(id, mMaxItemId);
931
932 Integer screen = values.getAsInteger(Favorites.SCREEN);
933 Integer container = values.getAsInteger(Favorites.CONTAINER);
934 if (screen != null && container != null
935 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
936 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500937 }
938 }
939
Sunny Goyalefb7e842018-10-04 15:11:00 -0700940 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800941 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700942 }
943
944 // Generates a new ID to use for an workspace screen in your database. This method
945 // should be only called from the main UI thread. As an exception, we do call it when we
946 // call the constructor from the worker thread; however, this doesn't extend until after the
947 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
948 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700949 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700950 if (mMaxScreenId < 0) {
951 throw new RuntimeException("Error: max screen id was not initialized");
952 }
953 mMaxScreenId += 1;
954 return mMaxScreenId;
955 }
956
Sunny Goyalefb7e842018-10-04 15:11:00 -0700957 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800958 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
959 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
960 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700961 }
962
Adam Cohen091440a2015-03-18 14:16:05 -0700963 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700964 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800965 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700966
967 // Ensure that the max ids are initialized
968 mMaxItemId = initializeMaxItemId(db);
969 mMaxScreenId = initializeMaxScreenId(db);
970 return count;
971 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700972 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700973
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800974 /**
975 * @return the max _id in the provided table.
976 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800977 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
978 int max = (int) DatabaseUtils.longForQuery(db,
979 String.format(Locale.ENGLISH, query, args),
980 null);
981 if (max < 0) {
982 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800983 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800984 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800985 }
986
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800987 static class SqlArguments {
988 public final String table;
989 public final String where;
990 public final String[] args;
991
992 SqlArguments(Uri url, String where, String[] args) {
993 if (url.getPathSegments().size() == 1) {
994 this.table = url.getPathSegments().get(0);
995 this.where = where;
996 this.args = args;
997 } else if (url.getPathSegments().size() != 2) {
998 throw new IllegalArgumentException("Invalid URI: " + url);
999 } else if (!TextUtils.isEmpty(where)) {
1000 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1001 } else {
1002 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001003 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001004 this.args = null;
1005 }
1006 }
1007
1008 SqlArguments(Uri url) {
1009 if (url.getPathSegments().size() == 1) {
1010 table = url.getPathSegments().get(0);
1011 where = null;
1012 args = null;
1013 } else {
1014 throw new IllegalArgumentException("Invalid URI: " + url);
1015 }
1016 }
1017 }
Adam Cohen72960972014-01-15 18:13:55 -08001018}