blob: 67fe0384b009dc7f59312c8a2795256fd090f74f [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;
21
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070022import android.annotation.TargetApi;
Jon Miranda2bc6b932019-03-07 15:24:46 -080023import android.app.backup.BackupManager;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070024import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070025import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070027import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000028import android.content.ContentProviderOperation;
29import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070030import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
33import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000034import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070035import android.content.SharedPreferences;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070036import android.content.pm.ProviderInfo;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080039import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070042import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070043import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070044import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070046import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.Bundle;
Sunny Goyal7779d622015-06-11 16:18:39 -070048import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080049import android.os.UserHandle;
Sunny Goyalc5939392018-12-07 11:43:47 -080050import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070051import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070052import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080053import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070054import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070055
Sunny Goyal0fe505b2014-08-06 09:55:36 -070056import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
57import com.android.launcher3.LauncherSettings.Favorites;
Kenny Guyed131872014-04-30 03:02:21 +010058import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070059import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080060import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070061import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070062import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070063import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070064import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070065import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070066import com.android.launcher3.util.IntArray;
67import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080068import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070069import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070070import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070071
Sunny Goyalc0f03d92019-03-22 14:13:36 -070072import org.xmlpull.v1.XmlPullParser;
73
Sunny Goyal05f30882017-05-03 12:42:18 -070074import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080075import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070076import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080077import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070078import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070079import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070080import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070081import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080082import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070085 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080086 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Sunny Goyal05f30882017-05-03 12:42:18 -070088 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
89
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070090 /**
91 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080092 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070093 */
Sunny Goyalc5939392018-12-07 11:43:47 -080094 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
Sunny Goyal4276e7b2018-11-26 23:44:41 -080096 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070097
Sunny Goyale87e6ab2014-11-21 22:42:53 -080098 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080099
Sunny Goyalf076eae2016-01-11 12:25:10 -0800100 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800102 /**
103 * $ adb shell dumpsys activity provider com.android.launcher3
104 */
105 @Override
106 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
107 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
108 if (appState == null || !appState.getModel().isModelLoaded()) {
109 return;
110 }
111 appState.getModel().dumpState("", fd, writer, args);
112 }
113
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114 @Override
115 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800116 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700117 Log.d(TAG, "Launcher process started");
118 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700119
Sunny Goyalfdbef272017-02-01 12:52:54 -0800120 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800121 // is the first component to get created.
122 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123 return true;
124 }
125
126 @Override
127 public String getType(Uri uri) {
128 SqlArguments args = new SqlArguments(uri, null, null);
129 if (TextUtils.isEmpty(args.where)) {
130 return "vnd.android.cursor.dir/" + args.table;
131 } else {
132 return "vnd.android.cursor.item/" + args.table;
133 }
134 }
135
Sunny Goyalf076eae2016-01-11 12:25:10 -0800136 /**
137 * Overridden in tests
138 */
139 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700140 if (mOpenHelper == null) {
Sunny Goyal01615a62019-09-20 12:00:07 -0700141 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700142
143 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700144 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
145 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700146 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
147 }
148 // Set is pending to false irrespective of the result, so that it doesn't get
149 // executed again.
150 RestoreDbTask.setPending(getContext(), false);
151 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700152 }
153 }
154
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800155 @Override
156 public Cursor query(Uri uri, String[] projection, String selection,
157 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700158 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159
160 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
161 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
162 qb.setTables(args.table);
163
Romain Guy73b979d2009-06-09 12:57:21 -0700164 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800165 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
166 result.setNotificationUri(getContext().getContentResolver(), uri);
167
168 return result;
169 }
170
Sunny Goyalefb7e842018-10-04 15:11:00 -0700171 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700172 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500173 if (values == null) {
174 throw new RuntimeException("Error: attempting to insert null values");
175 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800176 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 throw new RuntimeException("Error: attempting to add item without specifying an id");
178 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800179 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700180 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 }
182
Sunny Goyald1064182015-08-13 12:08:30 -0700183 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800184 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700185 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
186 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800187 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700188 }
189 }
190 }
191
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192 @Override
193 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700194 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 SqlArguments args = new SqlArguments(uri);
196
Sunny Goyald1064182015-08-13 12:08:30 -0700197 // In very limited cases, we support system|signature permission apps to modify the db.
198 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700199 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700200 return null;
201 }
202 }
203
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400205 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700206 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800207 if (rowId < 0) return null;
Sunny Goyal161a2142018-10-29 14:02:20 -0700208 mOpenHelper.onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209
210 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800211 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 return uri;
213 }
214
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700215 private boolean initializeExternalAdd(ContentValues values) {
216 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700217 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700218 values.put(LauncherSettings.Favorites._ID, id);
219
220 // 2. In the case of an app widget, and if no app widget id is specified, we
221 // attempt allocate and bind the widget.
222 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
223 if (itemType != null &&
224 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
225 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
226
227 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
228 ComponentName cn = ComponentName.unflattenFromString(
229 values.getAsString(Favorites.APPWIDGET_PROVIDER));
230
231 if (cn != null) {
232 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700233 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
234 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700235 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
236 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700237 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700238 return false;
239 }
240 } catch (RuntimeException e) {
241 Log.e(TAG, "Failed to initialize external widget", e);
242 return false;
243 }
244 } else {
245 return false;
246 }
247 }
248
Sunny Goyalc5939392018-12-07 11:43:47 -0800249 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700250 }
251
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800252 @Override
253 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700254 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800255 SqlArguments args = new SqlArguments(uri);
256
257 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700258 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800259 int numValues = values.length;
260 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400261 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700262 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
263 return 0;
264 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800265 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700266 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700267 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800268 }
269
Sunny Goyald1064182015-08-13 12:08:30 -0700270 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800271 return values.length;
272 }
273
Sunny Goyal161a2142018-10-29 14:02:20 -0700274 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 @Override
Yura085c8532014-02-11 15:15:29 +0000276 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
277 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700278 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700279 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800280 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700281
282 final int numOperations = operations.size();
283 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
284 for (int i = 0; i < numOperations; i++) {
285 ContentProviderOperation op = operations.get(i);
286 results[i] = op.apply(this, results, i);
287
288 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
289 results[i].count != null && results[i].count > 0;
290 }
291 if (isAddOrDelete) {
292 mOpenHelper.onAddOrDeleteOp(t.getDb());
293 }
294
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700295 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700296 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700297 return results;
Yura085c8532014-02-11 15:15:29 +0000298 }
299 }
300
301 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700303 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
305
306 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307
Louis Begina9c21c62016-08-15 15:18:41 -0700308 if (Binder.getCallingPid() != Process.myPid()
309 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700310 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700311 }
312 int count = db.delete(args.table, args.where, args.args);
313 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700314 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700315 reloadLauncherIfExternal();
316 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800317 return count;
318 }
319
320 @Override
321 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700322 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800323 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
324
Chris Wren1ada10d2013-09-13 18:01:38 -0400325 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800326 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
327 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700328 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 return count;
330 }
331
Sunny Goyal7779d622015-06-11 16:18:39 -0700332 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700333 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700334 if (Binder.getCallingUid() != Process.myUid()) {
335 return null;
336 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700337 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700338
339 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700340 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
341 clearFlagEmptyDbCreated();
342 return null;
343 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700344 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
345 Bundle result = new Bundle();
346 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
347 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
348 return result;
349 }
Sunny Goyald2497482015-09-22 18:24:19 -0700350 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
351 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700352 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
353 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700354 return result;
355 }
356 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
357 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700358 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700359 return result;
360 }
361 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
362 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700363 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700364 return result;
365 }
366 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800367 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700368 return null;
369 }
370 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
371 loadDefaultFavoritesIfNecessary();
372 return null;
373 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700374 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
375 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
376 return null;
377 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700378 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
379 Bundle result = new Bundle();
380 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
381 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
382 return result;
383 }
384 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
385 mOpenHelper.mBackupTableExists =
386 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
387 return null;
388 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700389 }
390 return null;
391 }
392
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700393 /**
394 * Deletes any empty folder from the DB.
395 * @return Ids of deleted folders.
396 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700397 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700398 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700399 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700400 // Select folders whose id do not match any container value.
401 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
402 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
403 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
404 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700405 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800406
407 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
408 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700409 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700410 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700411 LauncherSettings.Favorites._ID, folderIds), null);
412 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700413 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800414 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700415 } catch (SQLException ex) {
416 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800417 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700418 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700419 }
420
Adam Cohen091440a2015-03-18 14:16:05 -0700421 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800422 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800423 }
424
Sunny Goyald2497482015-09-22 18:24:19 -0700425 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700426 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700427 }
428
Sunny Goyal42de82f2014-09-26 22:09:29 -0700429 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700430 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700431 * 1) From the app restrictions
432 * 2) From a package provided by play store
433 * 3) From a partner configuration APK, already in the system image
434 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700435 */
Sunny Goyald2497482015-09-22 18:24:19 -0700436 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700437 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700438
Winson Chungc763c4e2013-07-19 13:49:06 -0700439 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500440 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200441
Sunny Goyal55fddc82017-04-06 15:02:52 -0700442 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700443 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700444 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700445 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700446 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700447 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700448 final Partner partner = Partner.get(getContext().getPackageManager());
449 if (partner != null && partner.hasDefaultLayout()) {
450 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700451 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700452 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700453 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700454 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700455 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700456 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700457 }
458 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700459
Sunny Goyal9d219682014-10-23 14:21:02 -0700460 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700461 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700462 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700463 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800464
465 // There might be some partially restored DB items, due to buggy restore logic in
466 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800467 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700468 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700469 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
470 && usingExternallyProvidedLayout) {
471 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800472 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700473 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700474 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700475 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700476 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700477 }
478 }
479
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700480 /**
481 * Creates workspace loader from an XML resource listed in the app restrictions.
482 *
483 * @return the loader if the restrictions are set and the resource exists; null otherwise.
484 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700485 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700486 Context ctx = getContext();
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700487 String authority = Settings.Secure.getString(ctx.getContentResolver(),
488 "launcher3.layout.provider");
489 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700490 return null;
491 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700492
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700493 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
494 if (pi == null) {
495 Log.e(TAG, "No provider found for authority " + authority);
496 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700497 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800498 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700499 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
500 // Read the full xml so that we fail early in case of any IO error.
501 String layout = new String(IOUtils.toByteArray(in));
502 XmlPullParser parser = Xml.newPullParser();
503 parser.setInput(new StringReader(layout));
504
505 Log.d(TAG, "Loading layout from " + authority);
506 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
507 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
508 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
509 } catch (Exception e) {
510 Log.e(TAG, "Error getting layout stream from: " + authority , e);
511 return null;
512 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700513 }
514
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800515 public static Uri getLayoutUri(String authority, Context ctx) {
516 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
517 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
518 .appendQueryParameter("version", "1")
519 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
520 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
521 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
522 .build();
523 }
524
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700525 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700526 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
527 int defaultLayout = idp.defaultLayoutId;
528
529 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
530 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
531 defaultLayout = idp.demoModeLayoutId;
532 }
533
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700534 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700535 mOpenHelper, getContext().getResources(), defaultLayout);
536 }
537
Sunny Goyald3849d12015-10-29 10:28:32 -0700538 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800539 * The class is subclassed in tests to create an in-memory db.
540 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800541 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700543 private int mMaxItemId = -1;
544 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700545 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546
Sunny Goyal01615a62019-09-20 12:00:07 -0700547 DatabaseHelper(Context context) {
548 this(context, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700549 // Table creation sometimes fails silently, which leads to a crash loop.
550 // This way, we will try to create a table every time after crash, so the device
551 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700552 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700553 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
554 // This operation is a no-op if the table already exists.
555 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700556 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700557 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700558
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700559 initIds();
560 }
561
562 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700563 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700564 */
Sunny Goyal01615a62019-09-20 12:00:07 -0700565 public DatabaseHelper(Context context, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800566 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700567 mContext = context;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700568 }
569
570 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700571 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
572 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700573 if (mMaxItemId == -1) {
574 mMaxItemId = initializeMaxItemId(getWritableDatabase());
575 }
576 if (mMaxScreenId == -1) {
577 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700578 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800579 }
580
581 @Override
582 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800583 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700584
Adam Cohendcd297f2013-06-18 13:13:40 -0700585 mMaxItemId = 1;
586 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700587
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700588 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800589
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800590 // Fresh and clean launcher DB.
591 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800592 onEmptyDbCreated();
593 }
594
Sunny Goyal161a2142018-10-29 14:02:20 -0700595 protected void onAddOrDeleteOp(SQLiteDatabase db) {
596 if (mBackupTableExists) {
597 dropTable(db, Favorites.BACKUP_TABLE_NAME);
598 mBackupTableExists = false;
599 }
600 }
601
Sunny Goyalf076eae2016-01-11 12:25:10 -0800602 /**
603 * Overriden in tests.
604 */
605 protected void onEmptyDbCreated() {
606 // Set the flag for empty DB
607 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800608 }
609
Jon Miranda2bc6b932019-03-07 15:24:46 -0800610 public long getSerialNumberForUser(UserHandle user) {
611 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user);
612 }
613
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700614 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800615 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800616 }
617
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700619 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700620 }
621
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700623 public void onOpen(SQLiteDatabase db) {
624 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700625
626 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
627 if (!schemaFile.exists()) {
628 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700629 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800630 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700631 }
632
633 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700634 * One-time data updated before support of onDowngrade was added. This update is backwards
635 * compatible and can safely be run multiple times.
636 * Note: No new logic should be added here after release, as the new logic might not get
637 * executed on an existing device.
638 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700639 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700640 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
641 // Remove "profile extra"
642 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
643 for (UserHandle user : um.getUserProfiles()) {
644 long serial = um.getSerialNumberForUser(user);
645 String sql = "update favorites set intent = replace(intent, "
646 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
647 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700648 }
649 }
650
651 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700653 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800654 switch (oldVersion) {
655 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800656 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800657 case 12:
658 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700660 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800661 // Insert new column for holding widget provider name
662 db.execSQL("ALTER TABLE favorites " +
663 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700664 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800665 } catch (SQLException ex) {
666 Log.e(TAG, ex.getMessage(), ex);
667 // Old version remains, which means we wipe old data
668 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800669 }
670 }
671 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800672 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800673 // Old version remains, which means we wipe old data
674 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800675 }
676 }
677 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700678 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800679 // Old version remains, which means we wipe old data
680 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 }
682 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800683 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700684 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800685 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800686 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800687 case 18:
688 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 case 19: {
690 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800691 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800692 // Old version remains, which means we wipe old data
693 break;
694 }
695 }
696 case 20:
697 if (!updateFolderItemsRank(db, true)) {
698 break;
699 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800700 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800701 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800702 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700703 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
704 // Old version remains, which means we wipe old data
705 break;
706 }
707 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700708 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700709 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700710 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000711 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700712 case 25:
713 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700714 case 26:
715 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700716 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800717 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700718 break;
719 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800720 case 27: {
721 // Update the favorites table so that the screen ids are ordered based on
722 // workspace page rank.
723 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
724 BaseColumns._ID, null, null, "screenRank");
725 int[] original = finalScreens.toArray();
726 Arrays.sort(original);
727 String updatemap = "";
728 for (int i = 0; i < original.length; i++) {
729 if (finalScreens.get(i) != original[i]) {
730 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
731 Favorites.SCREEN, finalScreens.get(i), original[i]);
732 }
733 }
734 if (!TextUtils.isEmpty(updatemap)) {
735 String query = String.format(Locale.ENGLISH,
736 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
737 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
738 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
739 db.execSQL(query);
740 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700741 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800742 }
743 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800744 // DB Upgraded successfully
745 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400746 }
747
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 // DB was not upgraded
749 Log.w(TAG, "Destroying all old data.");
750 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800751 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800752
Adam Cohen9b1d0622014-05-21 19:01:57 -0700753 @Override
754 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700755 try {
756 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
757 .onDowngrade(db, oldVersion, newVersion);
758 } catch (Exception e) {
759 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
760 ". Wiping databse.", e);
761 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700762 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700763 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700764
Sunny Goyal42de82f2014-09-26 22:09:29 -0700765 /**
766 * Clears all the data for a fresh start.
767 */
768 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700769 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700770 dropTable(db, Favorites.TABLE_NAME);
771 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800772 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700773 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800774 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700775 }
776
Sunny Goyald2f38192015-02-25 10:46:34 -0800777 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700778 * Removes widgets which are registered to the Launcher's host, but are not present
779 * in our model.
780 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700781 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700782 public void removeGhostWidgets(SQLiteDatabase db) {
783 // Get all existing widget ids.
784 final AppWidgetHost host = newLauncherWidgetHost();
785 final int[] allWidgets;
786 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700787 // Although the method was defined in O, it has existed since the beginning of time,
788 // so it might work on older platforms as well.
789 allWidgets = host.getAppWidgetIds();
790 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700791 Log.e(TAG, "getAppWidgetIds not supported", e);
792 return;
793 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800794 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
795 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
796 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700797 for (int widgetId : allWidgets) {
798 if (!validWidgets.contains(widgetId)) {
799 try {
800 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
801 host.deleteAppWidgetId(widgetId);
802 } catch (RuntimeException e) {
803 // Ignore
804 }
805 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700806 }
807 }
808
809 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700810 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
811 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
812 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700813 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700814 try (SQLiteTransaction t = new SQLiteTransaction(db);
815 // Only consider the primary user as other users can't have a shortcut.
816 Cursor c = db.query(Favorites.TABLE_NAME,
817 new String[] { Favorites._ID, Favorites.INTENT},
818 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
819 " AND profileId=" + getDefaultUserSerial(),
820 null, null, null, null);
821 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
822 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
823 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700824 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
825 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
826
827 while (c.moveToNext()) {
828 String intentDescription = c.getString(intentIndex);
829 Intent intent;
830 try {
831 intent = Intent.parseUri(intentDescription, 0);
832 } catch (URISyntaxException e) {
833 Log.e(TAG, "Unable to parse intent", e);
834 continue;
835 }
836
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700837 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700838 continue;
839 }
840
Sunny Goyalefb7e842018-10-04 15:11:00 -0700841 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700842 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700843 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700844 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700845 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700846 } catch (SQLException ex) {
847 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 }
849 }
850
Adam Cohen091440a2015-03-18 14:16:05 -0700851 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700852 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800853 if (addRankColumn) {
854 // Insert new column for holding rank
855 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
856 }
857
858 // Get a map for folder ID to folder width
859 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
860 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
861 + " GROUP BY container;",
862 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
863
864 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800865 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
866 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800867 new Object[] {c.getLong(1) + 1, c.getLong(0)});
868 }
869
870 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700871 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800872 } catch (SQLException ex) {
873 // Old version remains, which means we wipe old data
874 Log.e(TAG, ex.getMessage(), ex);
875 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800876 }
877 return true;
878 }
879
Sunny Goyal5d85c442015-03-10 13:14:47 -0700880 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700881 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700882 db.execSQL("ALTER TABLE favorites ADD COLUMN "
883 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700884 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100885 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100886 Log.e(TAG, ex.getMessage(), ex);
887 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100888 }
889 return true;
890 }
891
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700892 // Generates a new ID to use for an object in your database. This method should be only
893 // called from the main UI thread. As an exception, we do call it when we call the
894 // constructor from the worker thread; however, this doesn't extend until after the
895 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
896 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700897 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700898 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700899 if (mMaxItemId < 0) {
900 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700901 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700902 mMaxItemId += 1;
903 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700904 }
905
Sunny Goyal55fddc82017-04-06 15:02:52 -0700906 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700907 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700908 }
909
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700910 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700911 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700912 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700913 }
914
Sunny Goyalc5939392018-12-07 11:43:47 -0800915 public void checkId(ContentValues values) {
916 int id = values.getAsInteger(Favorites._ID);
917 mMaxItemId = Math.max(id, mMaxItemId);
918
919 Integer screen = values.getAsInteger(Favorites.SCREEN);
920 Integer container = values.getAsInteger(Favorites.CONTAINER);
921 if (screen != null && container != null
922 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
923 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500924 }
925 }
926
Sunny Goyalefb7e842018-10-04 15:11:00 -0700927 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800928 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700929 }
930
931 // Generates a new ID to use for an workspace screen in your database. This method
932 // should be only called from the main UI thread. As an exception, we do call it when we
933 // call the constructor from the worker thread; however, this doesn't extend until after the
934 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
935 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700936 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700937 if (mMaxScreenId < 0) {
938 throw new RuntimeException("Error: max screen id was not initialized");
939 }
940 mMaxScreenId += 1;
941 return mMaxScreenId;
942 }
943
Sunny Goyalefb7e842018-10-04 15:11:00 -0700944 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800945 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
946 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
947 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700948 }
949
Adam Cohen091440a2015-03-18 14:16:05 -0700950 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700951 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800952 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700953
954 // Ensure that the max ids are initialized
955 mMaxItemId = initializeMaxItemId(db);
956 mMaxScreenId = initializeMaxScreenId(db);
957 return count;
958 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700959 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700960
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800961 /**
962 * @return the max _id in the provided table.
963 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800964 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
965 int max = (int) DatabaseUtils.longForQuery(db,
966 String.format(Locale.ENGLISH, query, args),
967 null);
968 if (max < 0) {
969 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800970 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800971 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800972 }
973
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800974 static class SqlArguments {
975 public final String table;
976 public final String where;
977 public final String[] args;
978
979 SqlArguments(Uri url, String where, String[] args) {
980 if (url.getPathSegments().size() == 1) {
981 this.table = url.getPathSegments().get(0);
982 this.where = where;
983 this.args = args;
984 } else if (url.getPathSegments().size() != 2) {
985 throw new IllegalArgumentException("Invalid URI: " + url);
986 } else if (!TextUtils.isEmpty(where)) {
987 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
988 } else {
989 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700990 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800991 this.args = null;
992 }
993 }
994
995 SqlArguments(Uri url) {
996 if (url.getPathSegments().size() == 1) {
997 table = url.getPathSegments().get(0);
998 where = null;
999 args = null;
1000 } else {
1001 throw new IllegalArgumentException("Invalid URI: " + url);
1002 }
1003 }
1004 }
Adam Cohen72960972014-01-15 18:13:55 -08001005}