blob: 24dc17a8bb3e4c161f28964ad9cd19404bfde0a5 [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;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070023import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070024import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000027import android.content.ContentProviderOperation;
28import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070029import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000033import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070034import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070035import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.database.Cursor;
Sunny Goyalc5939392018-12-07 11:43:47 -080038import android.database.DatabaseUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070041import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070042import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070043import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070044import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070045import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070046import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070047import android.os.Handler;
48import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070049import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080050import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070051import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080052import android.provider.BaseColumns;
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;
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 Goyalefb7e842018-10-04 15:11:00 -070065import com.android.launcher3.util.IntArray;
66import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080067import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070068import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070069import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070070
Sunny Goyal05f30882017-05-03 12:42:18 -070071import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070074import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070075import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070076import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080077import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070080 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080081 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
Sunny Goyal05f30882017-05-03 12:42:18 -070083 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
84
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070085 /**
86 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080087 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070088 */
Sunny Goyalc5939392018-12-07 11:43:47 -080089 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Sunny Goyal4276e7b2018-11-26 23:44:41 -080091 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070092
Sunny Goyale87e6ab2014-11-21 22:42:53 -080093 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070095 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
96
Sunny Goyalb5b55c82016-05-10 12:28:59 -070097 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
98 private Handler mListenerHandler;
99
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 mListenerHandler = new Handler(mListenerWrapper);
120
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
Sunny Goyald3849d12015-10-29 10:28:32 -0700127 /**
128 * Sets a provider listener.
129 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700130 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700131 Preconditions.assertUIThread();
132 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700133 }
134
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800135 @Override
136 public String getType(Uri uri) {
137 SqlArguments args = new SqlArguments(uri, null, null);
138 if (TextUtils.isEmpty(args.where)) {
139 return "vnd.android.cursor.dir/" + args.table;
140 } else {
141 return "vnd.android.cursor.item/" + args.table;
142 }
143 }
144
Sunny Goyalf076eae2016-01-11 12:25:10 -0800145 /**
146 * Overridden in tests
147 */
148 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700149 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700150 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700151
152 if (RestoreDbTask.isPending(getContext())) {
153 if (!RestoreDbTask.performRestore(mOpenHelper)) {
154 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
155 }
156 // Set is pending to false irrespective of the result, so that it doesn't get
157 // executed again.
158 RestoreDbTask.setPending(getContext(), false);
159 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700160 }
161 }
162
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 @Override
164 public Cursor query(Uri uri, String[] projection, String selection,
165 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700166 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167
168 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
169 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
170 qb.setTables(args.table);
171
Romain Guy73b979d2009-06-09 12:57:21 -0700172 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800173 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
174 result.setNotificationUri(getContext().getContentResolver(), uri);
175
176 return result;
177 }
178
Sunny Goyalefb7e842018-10-04 15:11:00 -0700179 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700180 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500181 if (values == null) {
182 throw new RuntimeException("Error: attempting to insert null values");
183 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800184 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700185 throw new RuntimeException("Error: attempting to add item without specifying an id");
186 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800187 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700188 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700189 }
190
Sunny Goyald1064182015-08-13 12:08:30 -0700191 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700192 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700193 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
194 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800195 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700196 }
197 }
198 }
199
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 @Override
201 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700202 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 SqlArguments args = new SqlArguments(uri);
204
Sunny Goyald1064182015-08-13 12:08:30 -0700205 // In very limited cases, we support system|signature permission apps to modify the db.
206 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700207 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700208 return null;
209 }
210 }
211
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400213 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700214 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800215 if (rowId < 0) return null;
Sunny Goyal161a2142018-10-29 14:02:20 -0700216 mOpenHelper.onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217
218 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700219 notifyListeners();
220
Sunny Goyalc74e4192015-09-08 14:01:03 -0700221 if (Utilities.ATLEAST_MARSHMALLOW) {
222 reloadLauncherIfExternal();
223 } else {
224 // Deprecated behavior to support legacy devices which rely on provider callbacks.
225 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
226 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800227 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700228 }
229
230 String notify = uri.getQueryParameter("notify");
231 if (notify == null || "true".equals(notify)) {
232 getContext().getContentResolver().notifyChange(uri, null);
233 }
234 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800235 return uri;
236 }
237
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700238 private boolean initializeExternalAdd(ContentValues values) {
239 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700240 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700241 values.put(LauncherSettings.Favorites._ID, id);
242
243 // 2. In the case of an app widget, and if no app widget id is specified, we
244 // attempt allocate and bind the widget.
245 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
246 if (itemType != null &&
247 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
248 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
249
250 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
251 ComponentName cn = ComponentName.unflattenFromString(
252 values.getAsString(Favorites.APPWIDGET_PROVIDER));
253
254 if (cn != null) {
255 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
257 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700258 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
259 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700260 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700261 return false;
262 }
263 } catch (RuntimeException e) {
264 Log.e(TAG, "Failed to initialize external widget", e);
265 return false;
266 }
267 } else {
268 return false;
269 }
270 }
271
Sunny Goyalc5939392018-12-07 11:43:47 -0800272 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700273 }
274
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 @Override
276 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700277 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800278 SqlArguments args = new SqlArguments(uri);
279
280 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700281 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800282 int numValues = values.length;
283 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400284 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700285 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
286 return 0;
287 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700289 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700290 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 }
292
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700293 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700294 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 return values.length;
296 }
297
Sunny Goyal161a2142018-10-29 14:02:20 -0700298 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 @Override
Yura085c8532014-02-11 15:15:29 +0000300 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
301 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700302 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700303 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700304 boolean isAddOrDelete = !Utilities.ATLEAST_MARSHMALLOW;
305
306 final int numOperations = operations.size();
307 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
308 for (int i = 0; i < numOperations; i++) {
309 ContentProviderOperation op = operations.get(i);
310 results[i] = op.apply(this, results, i);
311
312 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
313 results[i].count != null && results[i].count > 0;
314 }
315 if (isAddOrDelete) {
316 mOpenHelper.onAddOrDeleteOp(t.getDb());
317 }
318
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700319 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700320 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700321 return results;
Yura085c8532014-02-11 15:15:29 +0000322 }
323 }
324
325 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800326 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700327 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
329
330 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331
Louis Begina9c21c62016-08-15 15:18:41 -0700332 if (Binder.getCallingPid() != Process.myPid()
333 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700334 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700335 }
336 int count = db.delete(args.table, args.where, args.args);
337 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700338 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700339 notifyListeners();
340 reloadLauncherIfExternal();
341 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 return count;
343 }
344
345 @Override
346 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700347 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
349
Chris Wren1ada10d2013-09-13 18:01:38 -0400350 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
352 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700353 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800354
Sunny Goyald1064182015-08-13 12:08:30 -0700355 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 return count;
357 }
358
Sunny Goyal7779d622015-06-11 16:18:39 -0700359 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700360 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700361 if (Binder.getCallingUid() != Process.myUid()) {
362 return null;
363 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700364 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700365
366 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700367 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
368 clearFlagEmptyDbCreated();
369 return null;
370 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700371 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
372 Bundle result = new Bundle();
373 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
374 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
375 return result;
376 }
Sunny Goyald2497482015-09-22 18:24:19 -0700377 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
378 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700379 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
380 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700381 return result;
382 }
383 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
384 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700385 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700386 return result;
387 }
388 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
389 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700390 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700391 return result;
392 }
393 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800394 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700395 return null;
396 }
397 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
398 loadDefaultFavoritesIfNecessary();
399 return null;
400 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700401 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
402 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
403 return null;
404 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700405 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
406 Bundle result = new Bundle();
407 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
408 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
409 return result;
410 }
411 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
412 mOpenHelper.mBackupTableExists =
413 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
414 return null;
415 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700416 }
417 return null;
418 }
419
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700420 /**
421 * Deletes any empty folder from the DB.
422 * @return Ids of deleted folders.
423 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700424 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700425 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700426 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700427 // Select folders whose id do not match any container value.
428 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
429 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
430 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
431 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700432 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800433
434 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
435 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700436 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700437 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700438 LauncherSettings.Favorites._ID, folderIds), null);
439 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700440 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800441 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700442 } catch (SQLException ex) {
443 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800444 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700445 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700446 }
447
Sunny Goyalf076eae2016-01-11 12:25:10 -0800448 /**
449 * Overridden in tests
450 */
451 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700452 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400453 }
454
Adam Cohen091440a2015-03-18 14:16:05 -0700455 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800456 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800457 }
458
Sunny Goyald2497482015-09-22 18:24:19 -0700459 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700460 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700461 }
462
Sunny Goyal42de82f2014-09-26 22:09:29 -0700463 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700464 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700465 * 1) From the app restrictions
466 * 2) From a package provided by play store
467 * 3) From a partner configuration APK, already in the system image
468 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700469 */
Sunny Goyald2497482015-09-22 18:24:19 -0700470 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700471 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700472
Winson Chungc763c4e2013-07-19 13:49:06 -0700473 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500474 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200475
Sunny Goyal55fddc82017-04-06 15:02:52 -0700476 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700477 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700478 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700479 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700480 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700482 final Partner partner = Partner.get(getContext().getPackageManager());
483 if (partner != null && partner.hasDefaultLayout()) {
484 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700485 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700486 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700487 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700488 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700489 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700490 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700491 }
492 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700493
Sunny Goyal9d219682014-10-23 14:21:02 -0700494 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700495 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700496 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700497 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800498
499 // There might be some partially restored DB items, due to buggy restore logic in
500 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800501 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700502 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700503 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
504 && usingExternallyProvidedLayout) {
505 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800506 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700507 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700508 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700509 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700510 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700511 }
512 }
513
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700514 /**
515 * Creates workspace loader from an XML resource listed in the app restrictions.
516 *
517 * @return the loader if the restrictions are set and the resource exists; null otherwise.
518 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 Context ctx = getContext();
521 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
522 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700523 if (bundle == null) {
524 return null;
525 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700526
Sunny Goyal35ca8732015-04-06 10:45:31 -0700527 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700528 if (packageName != null) {
529 try {
530 Resources targetResources = ctx.getPackageManager()
531 .getResourcesForApplication(packageName);
532 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700533 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700534 } catch (NameNotFoundException e) {
535 Log.e(TAG, "Target package for restricted profile not found", e);
536 return null;
537 }
538 }
539 return null;
540 }
541
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700542 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700543 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
544 int defaultLayout = idp.defaultLayoutId;
545
546 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
547 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
548 defaultLayout = idp.demoModeLayoutId;
549 }
550
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700551 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700552 mOpenHelper, getContext().getResources(), defaultLayout);
553 }
554
Sunny Goyald3849d12015-10-29 10:28:32 -0700555 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800556 * The class is subclassed in tests to create an in-memory db.
557 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800558 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700559 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800560 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700561 private int mMaxItemId = -1;
562 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700563 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800564
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700565 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
566 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700567 // Table creation sometimes fails silently, which leads to a crash loop.
568 // This way, we will try to create a table every time after crash, so the device
569 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700570 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700571 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
572 // This operation is a no-op if the table already exists.
573 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700574 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700575 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700576
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 initIds();
578 }
579
580 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700581 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700582 */
583 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700584 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800585 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700586 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700587 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700588 }
589
590 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700591 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
592 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700593 if (mMaxItemId == -1) {
594 mMaxItemId = initializeMaxItemId(getWritableDatabase());
595 }
596 if (mMaxScreenId == -1) {
597 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700598 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
600
601 @Override
602 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800603 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700604
Adam Cohendcd297f2013-06-18 13:13:40 -0700605 mMaxItemId = 1;
606 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700607
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700608 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800610 // Fresh and clean launcher DB.
611 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800612 onEmptyDbCreated();
613 }
614
Sunny Goyal161a2142018-10-29 14:02:20 -0700615 protected void onAddOrDeleteOp(SQLiteDatabase db) {
616 if (mBackupTableExists) {
617 dropTable(db, Favorites.BACKUP_TABLE_NAME);
618 mBackupTableExists = false;
619 }
620 }
621
Sunny Goyalf076eae2016-01-11 12:25:10 -0800622 /**
623 * Overriden in tests.
624 */
625 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700626 // Database was just created, so wipe any previous widgets
627 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700628 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700629 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530630 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700631 }
632
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 // Set the flag for empty DB
634 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800635 }
636
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700637 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800638 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800639 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 }
641
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700642 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700643 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700644 }
645
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800646 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700647 public void onOpen(SQLiteDatabase db) {
648 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700649
650 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
651 if (!schemaFile.exists()) {
652 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700653 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800654 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700655 }
656
657 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700658 * One-time data updated before support of onDowngrade was added. This update is backwards
659 * compatible and can safely be run multiple times.
660 * Note: No new logic should be added here after release, as the new logic might not get
661 * executed on an existing device.
662 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700663 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700664 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
665 // Remove "profile extra"
666 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
667 for (UserHandle user : um.getUserProfiles()) {
668 long serial = um.getSerialNumberForUser(user);
669 String sql = "update favorites set intent = replace(intent, "
670 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
671 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700672 }
673 }
674
675 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800676 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700677 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800678 switch (oldVersion) {
679 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800680 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800681 case 12:
682 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800683 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700684 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800685 // Insert new column for holding widget provider name
686 db.execSQL("ALTER TABLE favorites " +
687 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700688 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 } catch (SQLException ex) {
690 Log.e(TAG, ex.getMessage(), ex);
691 // Old version remains, which means we wipe old data
692 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800693 }
694 }
695 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800696 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 // Old version remains, which means we wipe old data
698 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800699 }
700 }
701 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700702 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800703 // Old version remains, which means we wipe old data
704 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800705 }
706 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800707 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700708 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800709 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800710 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800711 case 18:
712 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800713 case 19: {
714 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800715 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 // Old version remains, which means we wipe old data
717 break;
718 }
719 }
720 case 20:
721 if (!updateFolderItemsRank(db, true)) {
722 break;
723 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800724 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800725 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800726 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700727 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
728 // Old version remains, which means we wipe old data
729 break;
730 }
731 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700732 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700733 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700734 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000735 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700736 case 25:
737 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700738 case 26:
739 // QSB was moved to the grid. Clear the first row on screen 0.
Ryan Lothianfa530cd2018-10-12 14:14:16 -0400740 if (FeatureFlags.QSB_ON_FIRST_SCREEN.get() &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800741 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700742 break;
743 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800744 case 27: {
745 // Update the favorites table so that the screen ids are ordered based on
746 // workspace page rank.
747 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
748 BaseColumns._ID, null, null, "screenRank");
749 int[] original = finalScreens.toArray();
750 Arrays.sort(original);
751 String updatemap = "";
752 for (int i = 0; i < original.length; i++) {
753 if (finalScreens.get(i) != original[i]) {
754 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
755 Favorites.SCREEN, finalScreens.get(i), original[i]);
756 }
757 }
758 if (!TextUtils.isEmpty(updatemap)) {
759 String query = String.format(Locale.ENGLISH,
760 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
761 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
762 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
763 db.execSQL(query);
764 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700765 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800766 }
767 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800768 // DB Upgraded successfully
769 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400770 }
771
Sunny Goyala2cc6242015-01-14 14:23:02 -0800772 // DB was not upgraded
773 Log.w(TAG, "Destroying all old data.");
774 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800775 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800776
Adam Cohen9b1d0622014-05-21 19:01:57 -0700777 @Override
778 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700779 try {
780 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
781 .onDowngrade(db, oldVersion, newVersion);
782 } catch (Exception e) {
783 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
784 ". Wiping databse.", e);
785 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700786 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700787 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700788
Sunny Goyal42de82f2014-09-26 22:09:29 -0700789 /**
790 * Clears all the data for a fresh start.
791 */
792 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700793 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700794 dropTable(db, Favorites.TABLE_NAME);
795 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800796 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700797 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800798 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700799 }
800
Sunny Goyald2f38192015-02-25 10:46:34 -0800801 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700802 * Removes widgets which are registered to the Launcher's host, but are not present
803 * in our model.
804 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700805 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700806 public void removeGhostWidgets(SQLiteDatabase db) {
807 // Get all existing widget ids.
808 final AppWidgetHost host = newLauncherWidgetHost();
809 final int[] allWidgets;
810 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700811 // Although the method was defined in O, it has existed since the beginning of time,
812 // so it might work on older platforms as well.
813 allWidgets = host.getAppWidgetIds();
814 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700815 Log.e(TAG, "getAppWidgetIds not supported", e);
816 return;
817 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800818 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
819 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
820 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700821 for (int widgetId : allWidgets) {
822 if (!validWidgets.contains(widgetId)) {
823 try {
824 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
825 host.deleteAppWidgetId(widgetId);
826 } catch (RuntimeException e) {
827 // Ignore
828 }
829 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700830 }
831 }
832
833 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700834 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
835 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
836 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700837 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700838 try (SQLiteTransaction t = new SQLiteTransaction(db);
839 // Only consider the primary user as other users can't have a shortcut.
840 Cursor c = db.query(Favorites.TABLE_NAME,
841 new String[] { Favorites._ID, Favorites.INTENT},
842 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
843 " AND profileId=" + getDefaultUserSerial(),
844 null, null, null, null);
845 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
846 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
847 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
849 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
850
851 while (c.moveToNext()) {
852 String intentDescription = c.getString(intentIndex);
853 Intent intent;
854 try {
855 intent = Intent.parseUri(intentDescription, 0);
856 } catch (URISyntaxException e) {
857 Log.e(TAG, "Unable to parse intent", e);
858 continue;
859 }
860
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700861 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700862 continue;
863 }
864
Sunny Goyalefb7e842018-10-04 15:11:00 -0700865 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700866 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700867 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700868 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700869 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700870 } catch (SQLException ex) {
871 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700872 }
873 }
874
Adam Cohen091440a2015-03-18 14:16:05 -0700875 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700876 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800877 if (addRankColumn) {
878 // Insert new column for holding rank
879 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
880 }
881
882 // Get a map for folder ID to folder width
883 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
884 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
885 + " GROUP BY container;",
886 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
887
888 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800889 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
890 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800891 new Object[] {c.getLong(1) + 1, c.getLong(0)});
892 }
893
894 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700895 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800896 } catch (SQLException ex) {
897 // Old version remains, which means we wipe old data
898 Log.e(TAG, ex.getMessage(), ex);
899 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800900 }
901 return true;
902 }
903
Sunny Goyal5d85c442015-03-10 13:14:47 -0700904 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700905 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700906 db.execSQL("ALTER TABLE favorites ADD COLUMN "
907 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700908 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100909 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100910 Log.e(TAG, ex.getMessage(), ex);
911 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100912 }
913 return true;
914 }
915
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700916 // Generates a new ID to use for an object in your database. This method should be only
917 // called from the main UI thread. As an exception, we do call it when we call the
918 // constructor from the worker thread; however, this doesn't extend until after the
919 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
920 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700921 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700922 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700923 if (mMaxItemId < 0) {
924 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700925 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700926 mMaxItemId += 1;
927 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700928 }
929
Sunny Goyal55fddc82017-04-06 15:02:52 -0700930 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700931 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700932 }
933
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700934 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700935 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700936 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700937 }
938
Sunny Goyalc5939392018-12-07 11:43:47 -0800939 public void checkId(ContentValues values) {
940 int id = values.getAsInteger(Favorites._ID);
941 mMaxItemId = Math.max(id, mMaxItemId);
942
943 Integer screen = values.getAsInteger(Favorites.SCREEN);
944 Integer container = values.getAsInteger(Favorites.CONTAINER);
945 if (screen != null && container != null
946 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
947 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500948 }
949 }
950
Sunny Goyalefb7e842018-10-04 15:11:00 -0700951 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800952 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700953 }
954
955 // Generates a new ID to use for an workspace screen in your database. This method
956 // should be only called from the main UI thread. As an exception, we do call it when we
957 // call the constructor from the worker thread; however, this doesn't extend until after the
958 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
959 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700960 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700961 if (mMaxScreenId < 0) {
962 throw new RuntimeException("Error: max screen id was not initialized");
963 }
964 mMaxScreenId += 1;
965 return mMaxScreenId;
966 }
967
Sunny Goyalefb7e842018-10-04 15:11:00 -0700968 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800969 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
970 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
971 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700972 }
973
Adam Cohen091440a2015-03-18 14:16:05 -0700974 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700975 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800976 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700977
978 // Ensure that the max ids are initialized
979 mMaxItemId = initializeMaxItemId(db);
980 mMaxScreenId = initializeMaxScreenId(db);
981 return count;
982 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700983 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700984
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800985 /**
986 * @return the max _id in the provided table.
987 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800988 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
989 int max = (int) DatabaseUtils.longForQuery(db,
990 String.format(Locale.ENGLISH, query, args),
991 null);
992 if (max < 0) {
993 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800994 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800995 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800996 }
997
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800998 static class SqlArguments {
999 public final String table;
1000 public final String where;
1001 public final String[] args;
1002
1003 SqlArguments(Uri url, String where, String[] args) {
1004 if (url.getPathSegments().size() == 1) {
1005 this.table = url.getPathSegments().get(0);
1006 this.where = where;
1007 this.args = args;
1008 } else if (url.getPathSegments().size() != 2) {
1009 throw new IllegalArgumentException("Invalid URI: " + url);
1010 } else if (!TextUtils.isEmpty(where)) {
1011 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1012 } else {
1013 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001014 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 this.args = null;
1016 }
1017 }
1018
1019 SqlArguments(Uri url) {
1020 if (url.getPathSegments().size() == 1) {
1021 table = url.getPathSegments().get(0);
1022 where = null;
1023 args = null;
1024 } else {
1025 throw new IllegalArgumentException("Invalid URI: " + url);
1026 }
1027 }
1028 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001029
1030 private static class ChangeListenerWrapper implements Handler.Callback {
1031
1032 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001033 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001034
1035 private LauncherProviderChangeListener mListener;
1036
1037 @Override
1038 public boolean handleMessage(Message msg) {
1039 if (mListener != null) {
1040 switch (msg.what) {
1041 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001042 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001043 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001044 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001045 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001046 break;
1047 }
1048 }
1049 return true;
1050 }
1051 }
Adam Cohen72960972014-01-15 18:13:55 -08001052}