blob: b58956078d0b19a3da71083b2e6fdd5c3292a8c0 [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 Goyal337c81f2019-12-10 12:19:13 -080050import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080051import android.provider.BaseColumns;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070052import android.provider.Settings;
Adam Cohen228da5a2011-07-27 22:23:47 -070053import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080054import android.util.Log;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070055import android.util.Xml;
Adam Cohen228da5a2011-07-27 22:23:47 -070056
Sunny Goyal0fe505b2014-08-06 09:55:36 -070057import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
58import com.android.launcher3.LauncherSettings.Favorites;
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 Goyal337c81f2019-12-10 12:19:13 -080062import com.android.launcher3.pm.UserCache;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070063import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070064import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070065import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070066import com.android.launcher3.util.IOUtils;
Sunny Goyalefb7e842018-10-04 15:11:00 -070067import com.android.launcher3.util.IntArray;
68import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080069import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyal9dbb27c2019-07-17 15:12:56 -070070import com.android.launcher3.util.PackageManagerHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070071import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070072
Sunny Goyalc0f03d92019-03-22 14:13:36 -070073import org.xmlpull.v1.XmlPullParser;
74
Sunny Goyal05f30882017-05-03 12:42:18 -070075import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080076import java.io.FileDescriptor;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070077import java.io.InputStream;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080078import java.io.PrintWriter;
Sunny Goyalc0f03d92019-03-22 14:13:36 -070079import java.io.StringReader;
Mike Cleronb87bd162009-10-30 16:36:56 -070080import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070081import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070082import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080083import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070086 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080087 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Sunny Goyal05f30882017-05-03 12:42:18 -070089 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
90
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070091 /**
92 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080093 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070094 */
Sunny Goyalc5939392018-12-07 11:43:47 -080095 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096
Sunny Goyal4276e7b2018-11-26 23:44:41 -080097 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070098
Sunny Goyale87e6ab2014-11-21 22:42:53 -080099 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Sunny Goyalf076eae2016-01-11 12:25:10 -0800101 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800102
Hyunyoung Song6aa37292017-02-06 10:46:24 -0800103 /**
104 * $ adb shell dumpsys activity provider com.android.launcher3
105 */
106 @Override
107 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
108 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
109 if (appState == null || !appState.getModel().isModelLoaded()) {
110 return;
111 }
112 appState.getModel().dumpState("", fd, writer, args);
113 }
114
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115 @Override
116 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800117 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700118 Log.d(TAG, "Launcher process started");
119 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700120
Sunny Goyalfdbef272017-02-01 12:52:54 -0800121 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800122 // is the first component to get created.
123 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800124 return true;
125 }
126
127 @Override
128 public String getType(Uri uri) {
129 SqlArguments args = new SqlArguments(uri, null, null);
130 if (TextUtils.isEmpty(args.where)) {
131 return "vnd.android.cursor.dir/" + args.table;
132 } else {
133 return "vnd.android.cursor.item/" + args.table;
134 }
135 }
136
Sunny Goyalf076eae2016-01-11 12:25:10 -0800137 /**
138 * Overridden in tests
139 */
140 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700141 if (mOpenHelper == null) {
Sunny Goyal01615a62019-09-20 12:00:07 -0700142 mOpenHelper = new DatabaseHelper(getContext());
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700143
144 if (RestoreDbTask.isPending(getContext())) {
Jon Mirandac7206ca2019-05-13 14:57:50 -0700145 if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
146 new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700147 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
148 }
149 // Set is pending to false irrespective of the result, so that it doesn't get
150 // executed again.
151 RestoreDbTask.setPending(getContext(), false);
152 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700153 }
154 }
155
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156 @Override
157 public Cursor query(Uri uri, String[] projection, String selection,
158 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700159 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160
161 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
162 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
163 qb.setTables(args.table);
164
Romain Guy73b979d2009-06-09 12:57:21 -0700165 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
167 result.setNotificationUri(getContext().getContentResolver(), uri);
168
169 return result;
170 }
171
Sunny Goyalefb7e842018-10-04 15:11:00 -0700172 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700173 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500174 if (values == null) {
175 throw new RuntimeException("Error: attempting to insert null values");
176 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800177 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700178 throw new RuntimeException("Error: attempting to add item without specifying an id");
179 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800180 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700181 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 }
183
Sunny Goyald1064182015-08-13 12:08:30 -0700184 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800185 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700186 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
187 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800188 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700189 }
190 }
191 }
192
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193 @Override
194 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700195 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196 SqlArguments args = new SqlArguments(uri);
197
Sunny Goyald1064182015-08-13 12:08:30 -0700198 // In very limited cases, we support system|signature permission apps to modify the db.
199 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700200 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700201 return null;
202 }
203 }
204
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800205 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400206 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700207 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800208 if (rowId < 0) return null;
Sunny Goyal161a2142018-10-29 14:02:20 -0700209 mOpenHelper.onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
211 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800212 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 return uri;
214 }
215
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700216 private boolean initializeExternalAdd(ContentValues values) {
217 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700218 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700219 values.put(LauncherSettings.Favorites._ID, id);
220
221 // 2. In the case of an app widget, and if no app widget id is specified, we
222 // attempt allocate and bind the widget.
223 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
224 if (itemType != null &&
225 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
226 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
227
228 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
229 ComponentName cn = ComponentName.unflattenFromString(
230 values.getAsString(Favorites.APPWIDGET_PROVIDER));
231
232 if (cn != null) {
233 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700234 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
235 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700236 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
237 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700238 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700239 return false;
240 }
241 } catch (RuntimeException e) {
242 Log.e(TAG, "Failed to initialize external widget", e);
243 return false;
244 }
245 } else {
246 return false;
247 }
248 }
249
Sunny Goyalc5939392018-12-07 11:43:47 -0800250 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700251 }
252
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800253 @Override
254 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700255 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800256 SqlArguments args = new SqlArguments(uri);
257
258 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700259 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800260 int numValues = values.length;
261 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400262 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700263 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
264 return 0;
265 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800266 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700267 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700268 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800269 }
270
Sunny Goyald1064182015-08-13 12:08:30 -0700271 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800272 return values.length;
273 }
274
Sunny Goyal161a2142018-10-29 14:02:20 -0700275 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800276 @Override
Yura085c8532014-02-11 15:15:29 +0000277 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
278 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700279 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700280 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800281 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700282
283 final int numOperations = operations.size();
284 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
285 for (int i = 0; i < numOperations; i++) {
286 ContentProviderOperation op = operations.get(i);
287 results[i] = op.apply(this, results, i);
288
289 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
290 results[i].count != null && results[i].count > 0;
291 }
292 if (isAddOrDelete) {
293 mOpenHelper.onAddOrDeleteOp(t.getDb());
294 }
295
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700296 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700297 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700298 return results;
Yura085c8532014-02-11 15:15:29 +0000299 }
300 }
301
302 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700304 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
306
307 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800308
Louis Begina9c21c62016-08-15 15:18:41 -0700309 if (Binder.getCallingPid() != Process.myPid()
310 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700311 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700312 }
313 int count = db.delete(args.table, args.where, args.args);
314 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700315 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700316 reloadLauncherIfExternal();
317 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318 return count;
319 }
320
321 @Override
322 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
325
Chris Wren1ada10d2013-09-13 18:01:38 -0400326 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
328 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyald1064182015-08-13 12:08:30 -0700329 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 return count;
331 }
332
Sunny Goyal7779d622015-06-11 16:18:39 -0700333 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700334 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700335 if (Binder.getCallingUid() != Process.myUid()) {
336 return null;
337 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700338 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700339
340 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700341 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
342 clearFlagEmptyDbCreated();
343 return null;
344 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700345 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
346 Bundle result = new Bundle();
347 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
348 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
349 return result;
350 }
Sunny Goyald2497482015-09-22 18:24:19 -0700351 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
352 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700353 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
354 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700355 return result;
356 }
357 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
358 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700359 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700360 return result;
361 }
362 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
363 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700364 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700365 return result;
366 }
367 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800368 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700369 return null;
370 }
371 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
372 loadDefaultFavoritesIfNecessary();
373 return null;
374 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700375 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
376 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
377 return null;
378 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700379 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
380 Bundle result = new Bundle();
381 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
382 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
383 return result;
384 }
385 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
386 mOpenHelper.mBackupTableExists =
387 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
388 return null;
389 }
Pinyao Tingba9c5572019-09-24 14:25:46 -0700390 case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
391 RestoreDbTask.restoreIfPossible(
392 getContext(), mOpenHelper, new BackupManager(getContext()));
393 return null;
394 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700395 }
396 return null;
397 }
398
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700399 /**
400 * Deletes any empty folder from the DB.
401 * @return Ids of deleted folders.
402 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700403 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700404 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700405 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700406 // Select folders whose id do not match any container value.
407 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
408 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
409 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
410 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700411 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800412
413 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
414 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700415 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700416 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700417 LauncherSettings.Favorites._ID, folderIds), null);
418 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700419 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800420 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700421 } catch (SQLException ex) {
422 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800423 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700424 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700425 }
426
Adam Cohen091440a2015-03-18 14:16:05 -0700427 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800428 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800429 }
430
Sunny Goyald2497482015-09-22 18:24:19 -0700431 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700432 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700433 }
434
Sunny Goyal42de82f2014-09-26 22:09:29 -0700435 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700436 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700437 * 1) From the app restrictions
438 * 2) From a package provided by play store
439 * 3) From a partner configuration APK, already in the system image
440 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700441 */
Sunny Goyald2497482015-09-22 18:24:19 -0700442 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700443 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700444
Winson Chungc763c4e2013-07-19 13:49:06 -0700445 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500446 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200447
Sunny Goyal55fddc82017-04-06 15:02:52 -0700448 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700449 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700450 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700451 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700452 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700453 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700454 final Partner partner = Partner.get(getContext().getPackageManager());
455 if (partner != null && partner.hasDefaultLayout()) {
456 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700457 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700458 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700459 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700460 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700461 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700462 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700463 }
464 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700465
Sunny Goyal9d219682014-10-23 14:21:02 -0700466 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700468 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700469 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800470
471 // There might be some partially restored DB items, due to buggy restore logic in
472 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800473 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700474 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700475 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
476 && usingExternallyProvidedLayout) {
477 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800478 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700479 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700480 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700481 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700482 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700483 }
484 }
485
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700486 /**
487 * Creates workspace loader from an XML resource listed in the app restrictions.
488 *
489 * @return the loader if the restrictions are set and the resource exists; null otherwise.
490 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700491 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700492 Context ctx = getContext();
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700493 String authority = Settings.Secure.getString(ctx.getContentResolver(),
494 "launcher3.layout.provider");
495 if (TextUtils.isEmpty(authority)) {
Sunny Goyal35ca8732015-04-06 10:45:31 -0700496 return null;
497 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700498
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700499 ProviderInfo pi = ctx.getPackageManager().resolveContentProvider(authority, 0);
500 if (pi == null) {
501 Log.e(TAG, "No provider found for authority " + authority);
502 return null;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700503 }
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800504 Uri uri = getLayoutUri(authority, ctx);
Sunny Goyalc0f03d92019-03-22 14:13:36 -0700505 try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
506 // Read the full xml so that we fail early in case of any IO error.
507 String layout = new String(IOUtils.toByteArray(in));
508 XmlPullParser parser = Xml.newPullParser();
509 parser.setInput(new StringReader(layout));
510
511 Log.d(TAG, "Loading layout from " + authority);
512 return new AutoInstallsLayout(ctx, widgetHost, mOpenHelper,
513 ctx.getPackageManager().getResourcesForApplication(pi.applicationInfo),
514 () -> parser, AutoInstallsLayout.TAG_WORKSPACE);
515 } catch (Exception e) {
516 Log.e(TAG, "Error getting layout stream from: " + authority , e);
517 return null;
518 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700519 }
520
Sunny Goyal4b5b0eb2019-12-02 17:00:35 -0800521 public static Uri getLayoutUri(String authority, Context ctx) {
522 InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
523 return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
524 .appendQueryParameter("version", "1")
525 .appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
526 .appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
527 .appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
528 .build();
529 }
530
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700531 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700532 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
533 int defaultLayout = idp.defaultLayoutId;
534
Sunny Goyal337c81f2019-12-10 12:19:13 -0800535 if (getContext().getSystemService(UserManager.class).isDemoUser()
536 && idp.demoModeLayoutId != 0) {
Adam Cohen27824492017-09-22 17:10:55 -0700537 defaultLayout = idp.demoModeLayoutId;
538 }
539
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700540 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700541 mOpenHelper, getContext().getResources(), defaultLayout);
542 }
543
Sunny Goyald3849d12015-10-29 10:28:32 -0700544 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800545 * The class is subclassed in tests to create an in-memory db.
546 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800547 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700549 private int mMaxItemId = -1;
550 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700551 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800552
Sunny Goyal01615a62019-09-20 12:00:07 -0700553 DatabaseHelper(Context context) {
554 this(context, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700555 // Table creation sometimes fails silently, which leads to a crash loop.
556 // This way, we will try to create a table every time after crash, so the device
557 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700558 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700559 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
560 // This operation is a no-op if the table already exists.
561 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700562 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700563 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700564
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700565 initIds();
566 }
567
568 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700569 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700570 */
Sunny Goyal01615a62019-09-20 12:00:07 -0700571 public DatabaseHelper(Context context, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800572 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700573 mContext = context;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700574 }
575
576 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700577 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
578 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 if (mMaxItemId == -1) {
580 mMaxItemId = initializeMaxItemId(getWritableDatabase());
581 }
582 if (mMaxScreenId == -1) {
583 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700584 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 }
586
587 @Override
588 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800589 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700590
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 mMaxItemId = 1;
592 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700593
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700594 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800595
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800596 // Fresh and clean launcher DB.
597 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800598 onEmptyDbCreated();
599 }
600
Sunny Goyal161a2142018-10-29 14:02:20 -0700601 protected void onAddOrDeleteOp(SQLiteDatabase db) {
602 if (mBackupTableExists) {
603 dropTable(db, Favorites.BACKUP_TABLE_NAME);
604 mBackupTableExists = false;
605 }
606 }
607
Sunny Goyalf076eae2016-01-11 12:25:10 -0800608 /**
609 * Overriden in tests.
610 */
611 protected void onEmptyDbCreated() {
612 // Set the flag for empty DB
613 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800614 }
615
Jon Miranda2bc6b932019-03-07 15:24:46 -0800616 public long getSerialNumberForUser(UserHandle user) {
Sunny Goyal337c81f2019-12-10 12:19:13 -0800617 return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
Jon Miranda2bc6b932019-03-07 15:24:46 -0800618 }
619
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700620 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800621 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622 }
623
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700624 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700625 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700626 }
627
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700629 public void onOpen(SQLiteDatabase db) {
630 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700631
632 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
633 if (!schemaFile.exists()) {
634 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700635 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800636 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700637 }
638
639 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700640 * One-time data updated before support of onDowngrade was added. This update is backwards
641 * compatible and can safely be run multiple times.
642 * Note: No new logic should be added here after release, as the new logic might not get
643 * executed on an existing device.
644 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700645 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700646 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
647 // Remove "profile extra"
Sunny Goyal337c81f2019-12-10 12:19:13 -0800648 UserCache um = UserCache.INSTANCE.get(mContext);
Sunny Goyal05f30882017-05-03 12:42:18 -0700649 for (UserHandle user : um.getUserProfiles()) {
650 long serial = um.getSerialNumberForUser(user);
651 String sql = "update favorites set intent = replace(intent, "
652 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
653 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700654 }
655 }
656
657 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700659 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800660 switch (oldVersion) {
661 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800662 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800663 case 12:
664 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800665 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700666 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800667 // Insert new column for holding widget provider name
668 db.execSQL("ALTER TABLE favorites " +
669 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700670 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 } catch (SQLException ex) {
672 Log.e(TAG, ex.getMessage(), ex);
673 // Old version remains, which means we wipe old data
674 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800675 }
676 }
677 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800678 if (!addIntegerColumn(db, Favorites.MODIFIED, 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 }
683 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700684 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800685 // Old version remains, which means we wipe old data
686 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800687 }
688 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800689 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700690 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800691 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800692 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800693 case 18:
694 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800695 case 19: {
696 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800697 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800698 // Old version remains, which means we wipe old data
699 break;
700 }
701 }
702 case 20:
703 if (!updateFolderItemsRank(db, true)) {
704 break;
705 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800706 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800707 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800708 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700709 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
710 // Old version remains, which means we wipe old data
711 break;
712 }
713 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700714 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700715 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700716 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000717 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700718 case 25:
719 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700720 case 26:
721 // QSB was moved to the grid. Clear the first row on screen 0.
Jon Miranda7143ba62019-03-15 09:00:05 -0700722 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800723 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700724 break;
725 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800726 case 27: {
727 // Update the favorites table so that the screen ids are ordered based on
728 // workspace page rank.
729 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
730 BaseColumns._ID, null, null, "screenRank");
731 int[] original = finalScreens.toArray();
732 Arrays.sort(original);
733 String updatemap = "";
734 for (int i = 0; i < original.length; i++) {
735 if (finalScreens.get(i) != original[i]) {
736 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
737 Favorites.SCREEN, finalScreens.get(i), original[i]);
738 }
739 }
740 if (!TextUtils.isEmpty(updatemap)) {
741 String query = String.format(Locale.ENGLISH,
742 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
743 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
744 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
745 db.execSQL(query);
746 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700747 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800748 }
749 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800750 // DB Upgraded successfully
751 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400752 }
753
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 // DB was not upgraded
755 Log.w(TAG, "Destroying all old data.");
756 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800758
Adam Cohen9b1d0622014-05-21 19:01:57 -0700759 @Override
760 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700761 try {
762 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
763 .onDowngrade(db, oldVersion, newVersion);
764 } catch (Exception e) {
765 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
766 ". Wiping databse.", e);
767 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700768 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700769 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700770
Sunny Goyal42de82f2014-09-26 22:09:29 -0700771 /**
772 * Clears all the data for a fresh start.
773 */
774 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700775 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700776 dropTable(db, Favorites.TABLE_NAME);
777 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800778 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700779 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800780 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700781 }
782
Sunny Goyald2f38192015-02-25 10:46:34 -0800783 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700784 * Removes widgets which are registered to the Launcher's host, but are not present
785 * in our model.
786 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700787 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700788 public void removeGhostWidgets(SQLiteDatabase db) {
789 // Get all existing widget ids.
790 final AppWidgetHost host = newLauncherWidgetHost();
791 final int[] allWidgets;
792 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700793 // Although the method was defined in O, it has existed since the beginning of time,
794 // so it might work on older platforms as well.
795 allWidgets = host.getAppWidgetIds();
796 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700797 Log.e(TAG, "getAppWidgetIds not supported", e);
798 return;
799 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800800 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
801 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
802 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700803 for (int widgetId : allWidgets) {
804 if (!validWidgets.contains(widgetId)) {
805 try {
806 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
807 host.deleteAppWidgetId(widgetId);
808 } catch (RuntimeException e) {
809 // Ignore
810 }
811 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700812 }
813 }
814
815 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700816 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
817 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
818 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700819 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700820 try (SQLiteTransaction t = new SQLiteTransaction(db);
821 // Only consider the primary user as other users can't have a shortcut.
822 Cursor c = db.query(Favorites.TABLE_NAME,
823 new String[] { Favorites._ID, Favorites.INTENT},
824 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
825 " AND profileId=" + getDefaultUserSerial(),
826 null, null, null, null);
827 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
828 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
829 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700830 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
831 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
832
833 while (c.moveToNext()) {
834 String intentDescription = c.getString(intentIndex);
835 Intent intent;
836 try {
837 intent = Intent.parseUri(intentDescription, 0);
838 } catch (URISyntaxException e) {
839 Log.e(TAG, "Unable to parse intent", e);
840 continue;
841 }
842
Sunny Goyal9dbb27c2019-07-17 15:12:56 -0700843 if (!PackageManagerHelper.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700844 continue;
845 }
846
Sunny Goyalefb7e842018-10-04 15:11:00 -0700847 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700849 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700850 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700851 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 } catch (SQLException ex) {
853 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700854 }
855 }
856
Adam Cohen091440a2015-03-18 14:16:05 -0700857 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700858 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800859 if (addRankColumn) {
860 // Insert new column for holding rank
861 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
862 }
863
864 // Get a map for folder ID to folder width
865 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
866 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
867 + " GROUP BY container;",
868 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
869
870 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800871 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
872 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800873 new Object[] {c.getLong(1) + 1, c.getLong(0)});
874 }
875
876 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700877 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800878 } catch (SQLException ex) {
879 // Old version remains, which means we wipe old data
880 Log.e(TAG, ex.getMessage(), ex);
881 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800882 }
883 return true;
884 }
885
Sunny Goyal5d85c442015-03-10 13:14:47 -0700886 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700887 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700888 db.execSQL("ALTER TABLE favorites ADD COLUMN "
889 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700890 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100891 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100892 Log.e(TAG, ex.getMessage(), ex);
893 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100894 }
895 return true;
896 }
897
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700898 // Generates a new ID to use for an object in your database. This method should be only
899 // called from the main UI thread. As an exception, we do call it when we call the
900 // constructor from the worker thread; however, this doesn't extend until after the
901 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
902 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700903 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700904 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700905 if (mMaxItemId < 0) {
906 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700907 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700908 mMaxItemId += 1;
909 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700910 }
911
Sunny Goyal55fddc82017-04-06 15:02:52 -0700912 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700913 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700914 }
915
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700916 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700917 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700918 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700919 }
920
Sunny Goyalc5939392018-12-07 11:43:47 -0800921 public void checkId(ContentValues values) {
922 int id = values.getAsInteger(Favorites._ID);
923 mMaxItemId = Math.max(id, mMaxItemId);
924
925 Integer screen = values.getAsInteger(Favorites.SCREEN);
926 Integer container = values.getAsInteger(Favorites.CONTAINER);
927 if (screen != null && container != null
928 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
929 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500930 }
931 }
932
Sunny Goyalefb7e842018-10-04 15:11:00 -0700933 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800934 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700935 }
936
937 // Generates a new ID to use for an workspace screen in your database. This method
938 // should be only called from the main UI thread. As an exception, we do call it when we
939 // call the constructor from the worker thread; however, this doesn't extend until after the
940 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
941 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700942 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700943 if (mMaxScreenId < 0) {
944 throw new RuntimeException("Error: max screen id was not initialized");
945 }
946 mMaxScreenId += 1;
947 return mMaxScreenId;
948 }
949
Sunny Goyalefb7e842018-10-04 15:11:00 -0700950 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800951 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
952 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
953 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700954 }
955
Adam Cohen091440a2015-03-18 14:16:05 -0700956 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700957 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800958 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700959
960 // Ensure that the max ids are initialized
961 mMaxItemId = initializeMaxItemId(db);
962 mMaxScreenId = initializeMaxScreenId(db);
963 return count;
964 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700965 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700966
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800967 /**
968 * @return the max _id in the provided table.
969 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800970 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
971 int max = (int) DatabaseUtils.longForQuery(db,
972 String.format(Locale.ENGLISH, query, args),
973 null);
974 if (max < 0) {
975 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800976 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800977 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800978 }
979
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800980 static class SqlArguments {
981 public final String table;
982 public final String where;
983 public final String[] args;
984
985 SqlArguments(Uri url, String where, String[] args) {
986 if (url.getPathSegments().size() == 1) {
987 this.table = url.getPathSegments().get(0);
988 this.where = where;
989 this.args = args;
990 } else if (url.getPathSegments().size() != 2) {
991 throw new IllegalArgumentException("Invalid URI: " + url);
992 } else if (!TextUtils.isEmpty(where)) {
993 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
994 } else {
995 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700996 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800997 this.args = null;
998 }
999 }
1000
1001 SqlArguments(Uri url) {
1002 if (url.getPathSegments().size() == 1) {
1003 table = url.getPathSegments().get(0);
1004 where = null;
1005 args = null;
1006 } else {
1007 throw new IllegalArgumentException("Invalid URI: " + url);
1008 }
1009 }
1010 }
Adam Cohen72960972014-01-15 18:13:55 -08001011}