blob: 42927ea1cfb4cfd4425b925035ca280923bb3943 [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 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
488
489 String authority = Settings.Secure.getString(ctx.getContentResolver(),
490 "launcher3.layout.provider");
491 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700492 return null;
493 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700494
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700495 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
496 if (pi == null) {
497 Log.e(TAG, "No provider found for authority " + authority);
498 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700499 }
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700500 Uri uri = new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
501 .appendQueryParameter("version", "1")
502 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
503 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
504 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
505 .build();
506
507 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
508 // Read the full xml so that we fail early in case of any IO error.
509 String layout = new String(IOUtils.toByteArray(in));
510 XmlPullParser parser = Xml.newPullParser();
511 parser.setInput(new StringReader(layout));
512
513 Log.d(TAG, "Loading layout from " + authority);
514 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
515 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
516 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
517 } catch (Exception e) {
518 Log.e(TAG, "Error getting layout stream from: " + authority , e);
519 return null;
520 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700521 }
522
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700523 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700524 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
525 int defaultLayout = idp.defaultLayoutId;
526
527 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
528 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
529 defaultLayout = idp.demoModeLayoutId;
530 }
531
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700532 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700533 mOpenHelper, getContext().getResources(), defaultLayout);
534 }
535
Sunny Goyald3849d12015-10-29 10:28:32 -0700536 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800537 * The class is subclassed in tests to create an in-memory db.
538 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800539 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800540 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700541 private int mMaxItemId = -1;
542 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700543 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800544
Sunny Goyal01615a62019-09-20 12:00:07 -0700545 DatabaseHelper(Context context) {
546 this(context, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700547 // Table creation sometimes fails silently, which leads to a crash loop.
548 // This way, we will try to create a table every time after crash, so the device
549 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700550 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700551 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
552 // This operation is a no-op if the table already exists.
553 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700554 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700555 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700556
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700557 initIds();
558 }
559
560 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700561 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700562 */
Sunny Goyal01615a62019-09-20 12:00:07 -0700563 public DatabaseHelper(Context context, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800564 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700565 mContext = context;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700566 }
567
568 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700569 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
570 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700571 if (mMaxItemId == -1) {
572 mMaxItemId = initializeMaxItemId(getWritableDatabase());
573 }
574 if (mMaxScreenId == -1) {
575 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700576 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800577 }
578
579 @Override
580 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800581 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700582
Adam Cohendcd297f2013-06-18 13:13:40 -0700583 mMaxItemId = 1;
584 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800588 // Fresh and clean launcher DB.
589 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800590 onEmptyDbCreated();
591 }
592
Sunny Goyal161a2142018-10-29 14:02:20 -0700593 protected void onAddOrDeleteOp(SQLiteDatabase db) {
594 if (mBackupTableExists) {
595 dropTable(db, Favorites.BACKUP_TABLE_NAME);
596 mBackupTableExists = false;
597 }
598 }
599
Sunny Goyalf076eae2016-01-11 12:25:10 -0800600 /**
601 * Overriden in tests.
602 */
603 protected void onEmptyDbCreated() {
604 // Set the flag for empty DB
605 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800606 }
607
Jon Miranda2bc6b932019-03-07 15:24:46 -0800608 public long getSerialNumberForUser(UserHandle user) {
609 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user);
610 }
611
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700612 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800613 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 }
615
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700616 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700617 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700618 }
619
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700621 public void onOpen(SQLiteDatabase db) {
622 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700623
624 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
625 if (!schemaFile.exists()) {
626 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700627 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800628 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700629 }
630
631 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700632 * One-time data updated before support of onDowngrade was added. This update is backwards
633 * compatible and can safely be run multiple times.
634 * Note: No new logic should be added here after release, as the new logic might not get
635 * executed on an existing device.
636 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700637 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700638 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
639 // Remove "profile extra"
640 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
641 for (UserHandle user : um.getUserProfiles()) {
642 long serial = um.getSerialNumberForUser(user);
643 String sql = "update favorites set intent = replace(intent, "
644 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
645 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700646 }
647 }
648
649 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700651 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800652 switch (oldVersion) {
653 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800654 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800655 case 12:
656 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800657 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700658 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800659 // Insert new column for holding widget provider name
660 db.execSQL("ALTER TABLE favorites " +
661 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700662 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800663 } catch (SQLException ex) {
664 Log.e(TAG, ex.getMessage(), ex);
665 // Old version remains, which means we wipe old data
666 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800667 }
668 }
669 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800670 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 // Old version remains, which means we wipe old data
672 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800673 }
674 }
675 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700676 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800677 // Old version remains, which means we wipe old data
678 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800679 }
680 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800681 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700682 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800683 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800684 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800685 case 18:
686 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800687 case 19: {
688 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800689 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800690 // Old version remains, which means we wipe old data
691 break;
692 }
693 }
694 case 20:
695 if (!updateFolderItemsRank(db, true)) {
696 break;
697 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800698 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800699 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800700 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700701 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
702 // Old version remains, which means we wipe old data
703 break;
704 }
705 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700706 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700707 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700708 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000709 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700710 case 25:
711 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700712 case 26:
713 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700714 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800715 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700716 break;
717 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800718 case 27: {
719 // Update the favorites table so that the screen ids are ordered based on
720 // workspace page rank.
721 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
722 BaseColumns._ID, null, null, "screenRank");
723 int[] original = finalScreens.toArray();
724 Arrays.sort(original);
725 String updatemap = "";
726 for (int i = 0; i < original.length; i++) {
727 if (finalScreens.get(i) != original[i]) {
728 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
729 Favorites.SCREEN, finalScreens.get(i), original[i]);
730 }
731 }
732 if (!TextUtils.isEmpty(updatemap)) {
733 String query = String.format(Locale.ENGLISH,
734 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
735 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
736 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
737 db.execSQL(query);
738 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700739 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800740 }
741 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 // DB Upgraded successfully
743 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400744 }
745
Sunny Goyala2cc6242015-01-14 14:23:02 -0800746 // DB was not upgraded
747 Log.w(TAG, "Destroying all old data.");
748 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800750
Adam Cohen9b1d0622014-05-21 19:01:57 -0700751 @Override
752 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700753 try {
754 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
755 .onDowngrade(db, oldVersion, newVersion);
756 } catch (Exception e) {
757 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
758 ". Wiping databse.", e);
759 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700760 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700761 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700762
Sunny Goyal42de82f2014-09-26 22:09:29 -0700763 /**
764 * Clears all the data for a fresh start.
765 */
766 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700767 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700768 dropTable(db, Favorites.TABLE_NAME);
769 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800770 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700771 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800772 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700773 }
774
Sunny Goyald2f38192015-02-25 10:46:34 -0800775 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700776 * Removes widgets which are registered to the Launcher's host, but are not present
777 * in our model.
778 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700779 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700780 public void removeGhostWidgets(SQLiteDatabase db) {
781 // Get all existing widget ids.
782 final AppWidgetHost host = newLauncherWidgetHost();
783 final int[] allWidgets;
784 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700785 // Although the method was defined in O, it has existed since the beginning of time,
786 // so it might work on older platforms as well.
787 allWidgets = host.getAppWidgetIds();
788 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700789 Log.e(TAG, "getAppWidgetIds not supported", e);
790 return;
791 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800792 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
793 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
794 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700795 for (int widgetId : allWidgets) {
796 if (!validWidgets.contains(widgetId)) {
797 try {
798 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
799 host.deleteAppWidgetId(widgetId);
800 } catch (RuntimeException e) {
801 // Ignore
802 }
803 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700804 }
805 }
806
807 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700808 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
809 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
810 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700811 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700812 try (SQLiteTransaction t = new SQLiteTransaction(db);
813 // Only consider the primary user as other users can't have a shortcut.
814 Cursor c = db.query(Favorites.TABLE_NAME,
815 new String[] { Favorites._ID, Favorites.INTENT},
816 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
817 " AND profileId=" + getDefaultUserSerial(),
818 null, null, null, null);
819 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
820 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
821 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700822 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
823 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
824
825 while (c.moveToNext()) {
826 String intentDescription = c.getString(intentIndex);
827 Intent intent;
828 try {
829 intent = Intent.parseUri(intentDescription, 0);
830 } catch (URISyntaxException e) {
831 Log.e(TAG, "Unable to parse intent", e);
832 continue;
833 }
834
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700835 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700836 continue;
837 }
838
Sunny Goyalefb7e842018-10-04 15:11:00 -0700839 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700840 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700841 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700842 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700843 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700844 } catch (SQLException ex) {
845 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700846 }
847 }
848
Adam Cohen091440a2015-03-18 14:16:05 -0700849 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700850 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800851 if (addRankColumn) {
852 // Insert new column for holding rank
853 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
854 }
855
856 // Get a map for folder ID to folder width
857 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
858 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
859 + " GROUP BY container;",
860 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
861
862 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800863 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
864 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800865 new Object[] {c.getLong(1) + 1, c.getLong(0)});
866 }
867
868 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700869 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800870 } catch (SQLException ex) {
871 // Old version remains, which means we wipe old data
872 Log.e(TAG, ex.getMessage(), ex);
873 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800874 }
875 return true;
876 }
877
Sunny Goyal5d85c442015-03-10 13:14:47 -0700878 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700879 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700880 db.execSQL("ALTER TABLE favorites ADD COLUMN "
881 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700882 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100883 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100884 Log.e(TAG, ex.getMessage(), ex);
885 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100886 }
887 return true;
888 }
889
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700890 // Generates a new ID to use for an object in your database. This method should be only
891 // called from the main UI thread. As an exception, we do call it when we call the
892 // constructor from the worker thread; however, this doesn't extend until after the
893 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
894 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700895 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700896 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700897 if (mMaxItemId < 0) {
898 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700899 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700900 mMaxItemId += 1;
901 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700902 }
903
Sunny Goyal55fddc82017-04-06 15:02:52 -0700904 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700905 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700906 }
907
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700908 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700909 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700910 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700911 }
912
Sunny Goyalc5939392018-12-07 11:43:47 -0800913 public void checkId(ContentValues values) {
914 int id = values.getAsInteger(Favorites._ID);
915 mMaxItemId = Math.max(id, mMaxItemId);
916
917 Integer screen = values.getAsInteger(Favorites.SCREEN);
918 Integer container = values.getAsInteger(Favorites.CONTAINER);
919 if (screen != null && container != null
920 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
921 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500922 }
923 }
924
Sunny Goyalefb7e842018-10-04 15:11:00 -0700925 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800926 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700927 }
928
929 // Generates a new ID to use for an workspace screen in your database. This method
930 // should be only called from the main UI thread. As an exception, we do call it when we
931 // call the constructor from the worker thread; however, this doesn't extend until after the
932 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
933 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700934 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700935 if (mMaxScreenId < 0) {
936 throw new RuntimeException("Error: max screen id was not initialized");
937 }
938 mMaxScreenId += 1;
939 return mMaxScreenId;
940 }
941
Sunny Goyalefb7e842018-10-04 15:11:00 -0700942 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800943 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
944 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
945 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700946 }
947
Adam Cohen091440a2015-03-18 14:16:05 -0700948 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700949 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800950 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700951
952 // Ensure that the max ids are initialized
953 mMaxItemId = initializeMaxItemId(db);
954 mMaxScreenId = initializeMaxScreenId(db);
955 return count;
956 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700957 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700958
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800959 /**
960 * @return the max _id in the provided table.
961 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800962 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
963 int max = (int) DatabaseUtils.longForQuery(db,
964 String.format(Locale.ENGLISH, query, args),
965 null);
966 if (max < 0) {
967 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800968 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800969 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800970 }
971
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800972 static class SqlArguments {
973 public final String table;
974 public final String where;
975 public final String[] args;
976
977 SqlArguments(Uri url, String where, String[] args) {
978 if (url.getPathSegments().size() == 1) {
979 this.table = url.getPathSegments().get(0);
980 this.where = where;
981 this.args = args;
982 } else if (url.getPathSegments().size() != 2) {
983 throw new IllegalArgumentException("Invalid URI: " + url);
984 } else if (!TextUtils.isEmpty(where)) {
985 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
986 } else {
987 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700988 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800989 this.args = null;
990 }
991 }
992
993 SqlArguments(Uri url) {
994 if (url.getPathSegments().size() == 1) {
995 table = url.getPathSegments().get(0);
996 where = null;
997 args = null;
998 } else {
999 throw new IllegalArgumentException("Invalid URI: " + url);
1000 }
1001 }
1002 }
Adam Cohen72960972014-01-15 18:13:55 -08001003}