blob: ce732292869913be64a9a90bdb1f44a3cc9f8dd9 [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 Goyalb2d46ce2015-03-26 11:32:11 -070036import android.content.pm.PackageManager.NameNotFoundException;
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 Goyalb5b55c82016-05-10 12:28:59 -070048import android.os.Handler;
49import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070050import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080051import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070052import android.os.UserManager;
Sunny Goyalc5939392018-12-07 11:43:47 -080053import android.provider.BaseColumns;
Adam Cohen228da5a2011-07-27 22:23:47 -070054import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055import android.util.Log;
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;
Kenny Guyed131872014-04-30 03:02:21 +010059import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070060import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080061import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070062import com.android.launcher3.model.DbDowngradeHelper;
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 Goyalefb7e842018-10-04 15:11:00 -070066import com.android.launcher3.util.IntArray;
67import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080068import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070069import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070070import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070071
Sunny Goyal05f30882017-05-03 12:42:18 -070072import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070075import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070076import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070077import java.util.Arrays;
Sunny Goyalc5939392018-12-07 11:43:47 -080078import java.util.Locale;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070081 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080082 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
Sunny Goyal05f30882017-05-03 12:42:18 -070084 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
85
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070086 /**
87 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
Sunny Goyalc5939392018-12-07 11:43:47 -080088 * When increasing the scheme version, ensure that downgrade_schema.json is updated
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070089 */
Sunny Goyalc5939392018-12-07 11:43:47 -080090 public static final int SCHEMA_VERSION = 28;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Sunny Goyal4276e7b2018-11-26 23:44:41 -080092 public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
Winson Chung3d503fb2011-07-13 17:25:49 -070093
Sunny Goyale87e6ab2014-11-21 22:42:53 -080094 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070096 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
97
Sunny Goyalb5b55c82016-05-10 12:28:59 -070098 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
99 private Handler mListenerHandler;
100
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 mListenerHandler = new Handler(mListenerWrapper);
121
Sunny Goyalfdbef272017-02-01 12:52:54 -0800122 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800123 // is the first component to get created.
124 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 return true;
126 }
127
Sunny Goyald3849d12015-10-29 10:28:32 -0700128 /**
129 * Sets a provider listener.
130 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700131 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700132 Preconditions.assertUIThread();
133 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700134 }
135
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800136 @Override
137 public String getType(Uri uri) {
138 SqlArguments args = new SqlArguments(uri, null, null);
139 if (TextUtils.isEmpty(args.where)) {
140 return "vnd.android.cursor.dir/" + args.table;
141 } else {
142 return "vnd.android.cursor.item/" + args.table;
143 }
144 }
145
Sunny Goyalf076eae2016-01-11 12:25:10 -0800146 /**
147 * Overridden in tests
148 */
149 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700150 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700151 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700152
153 if (RestoreDbTask.isPending(getContext())) {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800154 if (!RestoreDbTask.performRestore(mOpenHelper, new BackupManager(getContext()))) {
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700155 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
156 }
157 // Set is pending to false irrespective of the result, so that it doesn't get
158 // executed again.
159 RestoreDbTask.setPending(getContext(), false);
160 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700161 }
162 }
163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 @Override
165 public Cursor query(Uri uri, String[] projection, String selection,
166 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700167 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168
169 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
170 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
171 qb.setTables(args.table);
172
Romain Guy73b979d2009-06-09 12:57:21 -0700173 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
175 result.setNotificationUri(getContext().getContentResolver(), uri);
176
177 return result;
178 }
179
Sunny Goyalefb7e842018-10-04 15:11:00 -0700180 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500182 if (values == null) {
183 throw new RuntimeException("Error: attempting to insert null values");
184 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800185 if (!values.containsKey(LauncherSettings.Favorites._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700186 throw new RuntimeException("Error: attempting to add item without specifying an id");
187 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800188 helper.checkId(values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700189 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700190 }
191
Sunny Goyald1064182015-08-13 12:08:30 -0700192 private void reloadLauncherIfExternal() {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800193 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700194 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
195 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800196 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700197 }
198 }
199 }
200
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800201 @Override
202 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700203 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204 SqlArguments args = new SqlArguments(uri);
205
Sunny Goyald1064182015-08-13 12:08:30 -0700206 // In very limited cases, we support system|signature permission apps to modify the db.
207 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700208 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700209 return null;
210 }
211 }
212
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400214 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700215 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800216 if (rowId < 0) return null;
Sunny Goyal161a2142018-10-29 14:02:20 -0700217 mOpenHelper.onAddOrDeleteOp(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218
219 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700220 notifyListeners();
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800221 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800222 return uri;
223 }
224
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700225 private boolean initializeExternalAdd(ContentValues values) {
226 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700227 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700228 values.put(LauncherSettings.Favorites._ID, id);
229
230 // 2. In the case of an app widget, and if no app widget id is specified, we
231 // attempt allocate and bind the widget.
232 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
233 if (itemType != null &&
234 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
235 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
236
237 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
238 ComponentName cn = ComponentName.unflattenFromString(
239 values.getAsString(Favorites.APPWIDGET_PROVIDER));
240
241 if (cn != null) {
242 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700243 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
244 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700245 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
246 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700247 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700248 return false;
249 }
250 } catch (RuntimeException e) {
251 Log.e(TAG, "Failed to initialize external widget", e);
252 return false;
253 }
254 } else {
255 return false;
256 }
257 }
258
Sunny Goyalc5939392018-12-07 11:43:47 -0800259 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700260 }
261
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800262 @Override
263 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700264 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800265 SqlArguments args = new SqlArguments(uri);
266
267 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700268 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800269 int numValues = values.length;
270 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400271 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700272 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
273 return 0;
274 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800275 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700276 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700277 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800278 }
279
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700280 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700281 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800282 return values.length;
283 }
284
Sunny Goyal161a2142018-10-29 14:02:20 -0700285 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800286 @Override
Yura085c8532014-02-11 15:15:29 +0000287 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
288 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700289 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700290 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800291 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700292
293 final int numOperations = operations.size();
294 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
295 for (int i = 0; i < numOperations; i++) {
296 ContentProviderOperation op = operations.get(i);
297 results[i] = op.apply(this, results, i);
298
299 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
300 results[i].count != null && results[i].count > 0;
301 }
302 if (isAddOrDelete) {
303 mOpenHelper.onAddOrDeleteOp(t.getDb());
304 }
305
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700306 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700307 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700308 return results;
Yura085c8532014-02-11 15:15:29 +0000309 }
310 }
311
312 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800313 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700314 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800315 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
316
317 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800318
Louis Begina9c21c62016-08-15 15:18:41 -0700319 if (Binder.getCallingPid() != Process.myPid()
320 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700321 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700322 }
323 int count = db.delete(args.table, args.where, args.args);
324 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700325 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700326 notifyListeners();
327 reloadLauncherIfExternal();
328 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 return count;
330 }
331
332 @Override
333 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700334 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
336
Chris Wren1ada10d2013-09-13 18:01:38 -0400337 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
339 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700340 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341
Sunny Goyald1064182015-08-13 12:08:30 -0700342 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343 return count;
344 }
345
Sunny Goyal7779d622015-06-11 16:18:39 -0700346 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700347 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700348 if (Binder.getCallingUid() != Process.myUid()) {
349 return null;
350 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700351 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700352
353 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700354 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
355 clearFlagEmptyDbCreated();
356 return null;
357 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700358 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
359 Bundle result = new Bundle();
360 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
361 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
362 return result;
363 }
Sunny Goyald2497482015-09-22 18:24:19 -0700364 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
365 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700366 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
367 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700368 return result;
369 }
370 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
371 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700372 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700373 return result;
374 }
375 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
376 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700377 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700378 return result;
379 }
380 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800381 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700382 return null;
383 }
384 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
385 loadDefaultFavoritesIfNecessary();
386 return null;
387 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700388 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
389 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
390 return null;
391 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700392 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
393 Bundle result = new Bundle();
394 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
395 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
396 return result;
397 }
398 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
399 mOpenHelper.mBackupTableExists =
400 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
401 return null;
402 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700403 }
404 return null;
405 }
406
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700407 /**
408 * Deletes any empty folder from the DB.
409 * @return Ids of deleted folders.
410 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700411 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700412 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700413 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700414 // Select folders whose id do not match any container value.
415 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
416 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
417 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
418 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700419 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800420
421 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
422 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700423 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700424 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700425 LauncherSettings.Favorites._ID, folderIds), null);
426 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700427 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800428 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 } catch (SQLException ex) {
430 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800431 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700433 }
434
Sunny Goyalf076eae2016-01-11 12:25:10 -0800435 /**
436 * Overridden in tests
437 */
438 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700439 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400440 }
441
Adam Cohen091440a2015-03-18 14:16:05 -0700442 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800443 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800444 }
445
Sunny Goyald2497482015-09-22 18:24:19 -0700446 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700447 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700448 }
449
Sunny Goyal42de82f2014-09-26 22:09:29 -0700450 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700451 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700452 * 1) From the app restrictions
453 * 2) From a package provided by play store
454 * 3) From a partner configuration APK, already in the system image
455 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700456 */
Sunny Goyald2497482015-09-22 18:24:19 -0700457 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700458 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700459
Winson Chungc763c4e2013-07-19 13:49:06 -0700460 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500461 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200462
Sunny Goyal55fddc82017-04-06 15:02:52 -0700463 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700464 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700465 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700466 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700467 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700468 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700469 final Partner partner = Partner.get(getContext().getPackageManager());
470 if (partner != null && partner.hasDefaultLayout()) {
471 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700472 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700473 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700474 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700475 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700476 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700477 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700478 }
479 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480
Sunny Goyal9d219682014-10-23 14:21:02 -0700481 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700482 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700483 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700484 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800485
486 // There might be some partially restored DB items, due to buggy restore logic in
487 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800488 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700489 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700490 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
491 && usingExternallyProvidedLayout) {
492 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800493 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700494 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700495 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700496 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700497 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700498 }
499 }
500
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700501 /**
502 * Creates workspace loader from an XML resource listed in the app restrictions.
503 *
504 * @return the loader if the restrictions are set and the resource exists; null otherwise.
505 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700506 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700507 Context ctx = getContext();
508 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
509 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700510 if (bundle == null) {
511 return null;
512 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700513
Sunny Goyal35ca8732015-04-06 10:45:31 -0700514 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700515 if (packageName != null) {
516 try {
517 Resources targetResources = ctx.getPackageManager()
518 .getResourcesForApplication(packageName);
519 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700520 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700521 } catch (NameNotFoundException e) {
522 Log.e(TAG, "Target package for restricted profile not found", e);
523 return null;
524 }
525 }
526 return null;
527 }
528
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700529 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700530 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
531 int defaultLayout = idp.defaultLayoutId;
532
533 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
534 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
535 defaultLayout = idp.demoModeLayoutId;
536 }
537
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700538 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700539 mOpenHelper, getContext().getResources(), defaultLayout);
540 }
541
Sunny Goyald3849d12015-10-29 10:28:32 -0700542 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800543 * The class is subclassed in tests to create an in-memory db.
544 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800545 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800546 private final BackupManager mBackupManager;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700547 private final Handler mWidgetHostResetHandler;
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 Goyalb5b55c82016-05-10 12:28:59 -0700553 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
554 this(context, widgetHostResetHandler, 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 */
571 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700572 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800573 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700574 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700575 mWidgetHostResetHandler = widgetHostResetHandler;
Jon Miranda2bc6b932019-03-07 15:24:46 -0800576 mBackupManager = new BackupManager(mContext);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700577 }
578
579 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700580 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
581 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700582 if (mMaxItemId == -1) {
583 mMaxItemId = initializeMaxItemId(getWritableDatabase());
584 }
585 if (mMaxScreenId == -1) {
586 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700587 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800588 }
589
590 @Override
591 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800592 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700593
Adam Cohendcd297f2013-06-18 13:13:40 -0700594 mMaxItemId = 1;
595 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700596
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700597 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800598
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800599 // Fresh and clean launcher DB.
600 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800601 onEmptyDbCreated();
602 }
603
Sunny Goyal161a2142018-10-29 14:02:20 -0700604 protected void onAddOrDeleteOp(SQLiteDatabase db) {
605 if (mBackupTableExists) {
606 dropTable(db, Favorites.BACKUP_TABLE_NAME);
607 mBackupTableExists = false;
608 }
609 }
610
Sunny Goyalf076eae2016-01-11 12:25:10 -0800611 /**
612 * Overriden in tests.
613 */
614 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700615 // Database was just created, so wipe any previous widgets
616 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700617 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700618 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530619 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700620 }
621
Sunny Goyalf076eae2016-01-11 12:25:10 -0800622 // Set the flag for empty DB
623 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800624 }
625
Jon Miranda2bc6b932019-03-07 15:24:46 -0800626 public long getSerialNumberForUser(UserHandle user) {
627 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user);
628 }
629
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700630 public long getDefaultUserSerial() {
Jon Miranda2bc6b932019-03-07 15:24:46 -0800631 return getSerialNumberForUser(Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632 }
633
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700634 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700635 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700636 }
637
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700639 public void onOpen(SQLiteDatabase db) {
640 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700641
642 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
643 if (!schemaFile.exists()) {
644 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700645 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800646 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700647 }
648
649 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700650 * One-time data updated before support of onDowngrade was added. This update is backwards
651 * compatible and can safely be run multiple times.
652 * Note: No new logic should be added here after release, as the new logic might not get
653 * executed on an existing device.
654 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700655 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700656 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
657 // Remove "profile extra"
658 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
659 for (UserHandle user : um.getUserProfiles()) {
660 long serial = um.getSerialNumberForUser(user);
661 String sql = "update favorites set intent = replace(intent, "
662 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
663 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700664 }
665 }
666
667 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700669 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800670 switch (oldVersion) {
671 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800672 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800673 case 12:
674 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800675 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700676 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800677 // Insert new column for holding widget provider name
678 db.execSQL("ALTER TABLE favorites " +
679 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700680 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800681 } catch (SQLException ex) {
682 Log.e(TAG, ex.getMessage(), ex);
683 // Old version remains, which means we wipe old data
684 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800685 }
686 }
687 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800688 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800689 // Old version remains, which means we wipe old data
690 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800691 }
692 }
693 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700694 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800695 // Old version remains, which means we wipe old data
696 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800697 }
698 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800699 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700700 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800701 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800703 case 18:
704 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800705 case 19: {
706 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800707 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800708 // Old version remains, which means we wipe old data
709 break;
710 }
711 }
712 case 20:
713 if (!updateFolderItemsRank(db, true)) {
714 break;
715 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800716 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800717 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800718 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700719 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
720 // Old version remains, which means we wipe old data
721 break;
722 }
723 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700724 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700725 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700726 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000727 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700728 case 25:
729 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700730 case 26:
731 // QSB was moved to the grid. Clear the first row on screen 0.
Ryan Lothianfa530cd2018-10-12 14:14:16 -0400732 if (FeatureFlags.QSB_ON_FIRST_SCREEN.get() &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800733 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700734 break;
735 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800736 case 27: {
737 // Update the favorites table so that the screen ids are ordered based on
738 // workspace page rank.
739 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
740 BaseColumns._ID, null, null, "screenRank");
741 int[] original = finalScreens.toArray();
742 Arrays.sort(original);
743 String updatemap = "";
744 for (int i = 0; i < original.length; i++) {
745 if (finalScreens.get(i) != original[i]) {
746 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
747 Favorites.SCREEN, finalScreens.get(i), original[i]);
748 }
749 }
750 if (!TextUtils.isEmpty(updatemap)) {
751 String query = String.format(Locale.ENGLISH,
752 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
753 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
754 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
755 db.execSQL(query);
756 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700757 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800758 }
759 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800760 // DB Upgraded successfully
761 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400762 }
763
Sunny Goyala2cc6242015-01-14 14:23:02 -0800764 // DB was not upgraded
765 Log.w(TAG, "Destroying all old data.");
766 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800767 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800768
Adam Cohen9b1d0622014-05-21 19:01:57 -0700769 @Override
770 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700771 try {
772 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
773 .onDowngrade(db, oldVersion, newVersion);
774 } catch (Exception e) {
775 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
776 ". Wiping databse.", e);
777 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700778 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700779 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700780
Sunny Goyal42de82f2014-09-26 22:09:29 -0700781 /**
782 * Clears all the data for a fresh start.
783 */
784 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700785 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700786 dropTable(db, Favorites.TABLE_NAME);
787 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800788 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700789 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800790 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700791 }
792
Sunny Goyald2f38192015-02-25 10:46:34 -0800793 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700794 * Removes widgets which are registered to the Launcher's host, but are not present
795 * in our model.
796 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700797 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700798 public void removeGhostWidgets(SQLiteDatabase db) {
799 // Get all existing widget ids.
800 final AppWidgetHost host = newLauncherWidgetHost();
801 final int[] allWidgets;
802 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700803 // Although the method was defined in O, it has existed since the beginning of time,
804 // so it might work on older platforms as well.
805 allWidgets = host.getAppWidgetIds();
806 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700807 Log.e(TAG, "getAppWidgetIds not supported", e);
808 return;
809 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800810 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
811 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
812 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700813 for (int widgetId : allWidgets) {
814 if (!validWidgets.contains(widgetId)) {
815 try {
816 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
817 host.deleteAppWidgetId(widgetId);
818 } catch (RuntimeException e) {
819 // Ignore
820 }
821 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700822 }
823 }
824
825 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700826 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
827 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
828 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700829 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700830 try (SQLiteTransaction t = new SQLiteTransaction(db);
831 // Only consider the primary user as other users can't have a shortcut.
832 Cursor c = db.query(Favorites.TABLE_NAME,
833 new String[] { Favorites._ID, Favorites.INTENT},
834 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
835 " AND profileId=" + getDefaultUserSerial(),
836 null, null, null, null);
837 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
838 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
839 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700840 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
841 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
842
843 while (c.moveToNext()) {
844 String intentDescription = c.getString(intentIndex);
845 Intent intent;
846 try {
847 intent = Intent.parseUri(intentDescription, 0);
848 } catch (URISyntaxException e) {
849 Log.e(TAG, "Unable to parse intent", e);
850 continue;
851 }
852
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700853 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700854 continue;
855 }
856
Sunny Goyalefb7e842018-10-04 15:11:00 -0700857 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700858 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700859 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700860 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700861 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700862 } catch (SQLException ex) {
863 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700864 }
865 }
866
Adam Cohen091440a2015-03-18 14:16:05 -0700867 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700868 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800869 if (addRankColumn) {
870 // Insert new column for holding rank
871 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
872 }
873
874 // Get a map for folder ID to folder width
875 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
876 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
877 + " GROUP BY container;",
878 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
879
880 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800881 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
882 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800883 new Object[] {c.getLong(1) + 1, c.getLong(0)});
884 }
885
886 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700887 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800888 } catch (SQLException ex) {
889 // Old version remains, which means we wipe old data
890 Log.e(TAG, ex.getMessage(), ex);
891 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800892 }
893 return true;
894 }
895
Sunny Goyal5d85c442015-03-10 13:14:47 -0700896 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700897 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700898 db.execSQL("ALTER TABLE favorites ADD COLUMN "
899 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700900 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100901 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100902 Log.e(TAG, ex.getMessage(), ex);
903 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100904 }
905 return true;
906 }
907
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700908 // Generates a new ID to use for an object in your database. This method should be only
909 // called from the main UI thread. As an exception, we do call it when we call the
910 // constructor from the worker thread; however, this doesn't extend until after the
911 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
912 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700913 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700914 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700915 if (mMaxItemId < 0) {
916 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700917 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700918 mMaxItemId += 1;
919 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700920 }
921
Sunny Goyal55fddc82017-04-06 15:02:52 -0700922 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700923 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700924 }
925
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700926 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700927 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700928 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700929 }
930
Sunny Goyalc5939392018-12-07 11:43:47 -0800931 public void checkId(ContentValues values) {
932 int id = values.getAsInteger(Favorites._ID);
933 mMaxItemId = Math.max(id, mMaxItemId);
934
935 Integer screen = values.getAsInteger(Favorites.SCREEN);
936 Integer container = values.getAsInteger(Favorites.CONTAINER);
937 if (screen != null && container != null
938 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
939 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500940 }
941 }
942
Sunny Goyalefb7e842018-10-04 15:11:00 -0700943 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800944 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700945 }
946
947 // Generates a new ID to use for an workspace screen in your database. This method
948 // should be only called from the main UI thread. As an exception, we do call it when we
949 // call the constructor from the worker thread; however, this doesn't extend until after the
950 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
951 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700952 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700953 if (mMaxScreenId < 0) {
954 throw new RuntimeException("Error: max screen id was not initialized");
955 }
956 mMaxScreenId += 1;
957 return mMaxScreenId;
958 }
959
Sunny Goyalefb7e842018-10-04 15:11:00 -0700960 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800961 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
962 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
963 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700964 }
965
Adam Cohen091440a2015-03-18 14:16:05 -0700966 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700967 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800968 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700969
970 // Ensure that the max ids are initialized
971 mMaxItemId = initializeMaxItemId(db);
972 mMaxScreenId = initializeMaxScreenId(db);
973 return count;
974 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700975 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700976
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800977 /**
978 * @return the max _id in the provided table.
979 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800980 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
981 int max = (int) DatabaseUtils.longForQuery(db,
982 String.format(Locale.ENGLISH, query, args),
983 null);
984 if (max < 0) {
985 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800986 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800987 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800988 }
989
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800990 static class SqlArguments {
991 public final String table;
992 public final String where;
993 public final String[] args;
994
995 SqlArguments(Uri url, String where, String[] args) {
996 if (url.getPathSegments().size() == 1) {
997 this.table = url.getPathSegments().get(0);
998 this.where = where;
999 this.args = args;
1000 } else if (url.getPathSegments().size() != 2) {
1001 throw new IllegalArgumentException("Invalid URI: " + url);
1002 } else if (!TextUtils.isEmpty(where)) {
1003 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1004 } else {
1005 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001006 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001007 this.args = null;
1008 }
1009 }
1010
1011 SqlArguments(Uri url) {
1012 if (url.getPathSegments().size() == 1) {
1013 table = url.getPathSegments().get(0);
1014 where = null;
1015 args = null;
1016 } else {
1017 throw new IllegalArgumentException("Invalid URI: " + url);
1018 }
1019 }
1020 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001021
1022 private static class ChangeListenerWrapper implements Handler.Callback {
1023
1024 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001025 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001026
1027 private LauncherProviderChangeListener mListener;
1028
1029 @Override
1030 public boolean handleMessage(Message msg) {
1031 if (mListener != null) {
1032 switch (msg.what) {
1033 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001034 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001035 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001036 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001037 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001038 break;
1039 }
1040 }
1041 return true;
1042 }
1043 }
Adam Cohen72960972014-01-15 18:13:55 -08001044}