blob: fb336943438a9cb4ff12b76eed3635084f11dda5 [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 Goyal8c48d8b2019-01-25 15:10:18 -0800192 if (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();
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800220 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 return uri;
222 }
223
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700224 private boolean initializeExternalAdd(ContentValues values) {
225 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700226 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700227 values.put(LauncherSettings.Favorites._ID, id);
228
229 // 2. In the case of an app widget, and if no app widget id is specified, we
230 // attempt allocate and bind the widget.
231 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
232 if (itemType != null &&
233 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
234 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
235
236 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
237 ComponentName cn = ComponentName.unflattenFromString(
238 values.getAsString(Favorites.APPWIDGET_PROVIDER));
239
240 if (cn != null) {
241 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700242 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
243 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700244 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
245 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700246 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700247 return false;
248 }
249 } catch (RuntimeException e) {
250 Log.e(TAG, "Failed to initialize external widget", e);
251 return false;
252 }
253 } else {
254 return false;
255 }
256 }
257
Sunny Goyalc5939392018-12-07 11:43:47 -0800258 return true;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700259 }
260
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800261 @Override
262 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700263 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 SqlArguments args = new SqlArguments(uri);
265
266 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700267 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800268 int numValues = values.length;
269 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400270 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700271 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
272 return 0;
273 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800274 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700275 mOpenHelper.onAddOrDeleteOp(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700276 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800277 }
278
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700279 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700280 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800281 return values.length;
282 }
283
Sunny Goyal161a2142018-10-29 14:02:20 -0700284 @TargetApi(Build.VERSION_CODES.M)
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800285 @Override
Yura085c8532014-02-11 15:15:29 +0000286 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
287 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700288 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700289 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Sunny Goyal8c48d8b2019-01-25 15:10:18 -0800290 boolean isAddOrDelete = false;
Sunny Goyal161a2142018-10-29 14:02:20 -0700291
292 final int numOperations = operations.size();
293 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
294 for (int i = 0; i < numOperations; i++) {
295 ContentProviderOperation op = operations.get(i);
296 results[i] = op.apply(this, results, i);
297
298 isAddOrDelete |= (op.isInsert() || op.isDelete()) &&
299 results[i].count != null && results[i].count > 0;
300 }
301 if (isAddOrDelete) {
302 mOpenHelper.onAddOrDeleteOp(t.getDb());
303 }
304
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700305 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700306 reloadLauncherIfExternal();
Sunny Goyal161a2142018-10-29 14:02:20 -0700307 return results;
Yura085c8532014-02-11 15:15:29 +0000308 }
309 }
310
311 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800312 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700313 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800314 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
315
316 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800317
Louis Begina9c21c62016-08-15 15:18:41 -0700318 if (Binder.getCallingPid() != Process.myPid()
319 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700320 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700321 }
322 int count = db.delete(args.table, args.where, args.args);
323 if (count > 0) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700324 mOpenHelper.onAddOrDeleteOp(db);
Louis Begina9c21c62016-08-15 15:18:41 -0700325 notifyListeners();
326 reloadLauncherIfExternal();
327 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 return count;
329 }
330
331 @Override
332 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700333 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800334 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
335
Chris Wren1ada10d2013-09-13 18:01:38 -0400336 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
338 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700339 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340
Sunny Goyald1064182015-08-13 12:08:30 -0700341 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 return count;
343 }
344
Sunny Goyal7779d622015-06-11 16:18:39 -0700345 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700346 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700347 if (Binder.getCallingUid() != Process.myUid()) {
348 return null;
349 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700350 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700351
352 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700353 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
354 clearFlagEmptyDbCreated();
355 return null;
356 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700357 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
358 Bundle result = new Bundle();
359 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
360 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
361 return result;
362 }
Sunny Goyald2497482015-09-22 18:24:19 -0700363 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
364 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700365 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
366 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700367 return result;
368 }
369 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
370 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700371 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700372 return result;
373 }
374 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
375 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700376 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700377 return result;
378 }
379 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800380 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700381 return null;
382 }
383 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
384 loadDefaultFavoritesIfNecessary();
385 return null;
386 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700387 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
388 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
389 return null;
390 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700391 case LauncherSettings.Settings.METHOD_NEW_TRANSACTION: {
392 Bundle result = new Bundle();
393 result.putBinder(LauncherSettings.Settings.EXTRA_VALUE,
394 new SQLiteTransaction(mOpenHelper.getWritableDatabase()));
395 return result;
396 }
397 case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
398 mOpenHelper.mBackupTableExists =
399 tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
400 return null;
401 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700402 }
403 return null;
404 }
405
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700406 /**
407 * Deletes any empty folder from the DB.
408 * @return Ids of deleted folders.
409 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700410 private IntArray deleteEmptyFolders() {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700411 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700412 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700413 // Select folders whose id do not match any container value.
414 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
415 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
416 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
417 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700418 + Favorites.TABLE_NAME + ")";
Sunny Goyalc5939392018-12-07 11:43:47 -0800419
420 IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
421 Favorites._ID, selection, null, null);
Sunny Goyald2497482015-09-22 18:24:19 -0700422 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700423 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700424 LauncherSettings.Favorites._ID, folderIds), null);
425 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700426 t.commit();
Sunny Goyalc5939392018-12-07 11:43:47 -0800427 return folderIds;
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 } catch (SQLException ex) {
429 Log.e(TAG, ex.getMessage(), ex);
Sunny Goyalc5939392018-12-07 11:43:47 -0800430 return new IntArray();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700431 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 }
433
Sunny Goyalf076eae2016-01-11 12:25:10 -0800434 /**
435 * Overridden in tests
436 */
437 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700438 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400439 }
440
Adam Cohen091440a2015-03-18 14:16:05 -0700441 @Thunk static void addModifiedTime(ContentValues values) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800442 values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800443 }
444
Sunny Goyald2497482015-09-22 18:24:19 -0700445 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700446 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700447 }
448
Sunny Goyal42de82f2014-09-26 22:09:29 -0700449 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700450 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700451 * 1) From the app restrictions
452 * 2) From a package provided by play store
453 * 3) From a partner configuration APK, already in the system image
454 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700455 */
Sunny Goyald2497482015-09-22 18:24:19 -0700456 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700457 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700458
Winson Chungc763c4e2013-07-19 13:49:06 -0700459 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500460 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200461
Sunny Goyal55fddc82017-04-06 15:02:52 -0700462 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700463 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700464 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700465 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700466 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700468 final Partner partner = Partner.get(getContext().getPackageManager());
469 if (partner != null && partner.hasDefaultLayout()) {
470 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700471 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700472 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700474 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700475 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700476 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700477 }
478 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479
Sunny Goyal9d219682014-10-23 14:21:02 -0700480 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700482 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700483 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800484
485 // There might be some partially restored DB items, due to buggy restore logic in
486 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800487 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700488 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700489 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
490 && usingExternallyProvidedLayout) {
491 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800492 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700493 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700494 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700496 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700497 }
498 }
499
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700500 /**
501 * Creates workspace loader from an XML resource listed in the app restrictions.
502 *
503 * @return the loader if the restrictions are set and the resource exists; null otherwise.
504 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700506 Context ctx = getContext();
507 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
508 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700509 if (bundle == null) {
510 return null;
511 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512
Sunny Goyal35ca8732015-04-06 10:45:31 -0700513 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700514 if (packageName != null) {
515 try {
516 Resources targetResources = ctx.getPackageManager()
517 .getResourcesForApplication(packageName);
518 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 } catch (NameNotFoundException e) {
521 Log.e(TAG, "Target package for restricted profile not found", e);
522 return null;
523 }
524 }
525 return null;
526 }
527
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700528 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700529 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
530 int defaultLayout = idp.defaultLayoutId;
531
532 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
533 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
534 defaultLayout = idp.demoModeLayoutId;
535 }
536
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700537 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700538 mOpenHelper, getContext().getResources(), defaultLayout);
539 }
540
Sunny Goyald3849d12015-10-29 10:28:32 -0700541 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800542 * The class is subclassed in tests to create an in-memory db.
543 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800544 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546 private final Context mContext;
Sunny Goyalefb7e842018-10-04 15:11:00 -0700547 private int mMaxItemId = -1;
548 private int mMaxScreenId = -1;
Sunny Goyal161a2142018-10-29 14:02:20 -0700549 private boolean mBackupTableExists;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800550
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700551 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
552 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700553 // Table creation sometimes fails silently, which leads to a crash loop.
554 // This way, we will try to create a table every time after crash, so the device
555 // would eventually be able to recover.
Sunny Goyal161a2142018-10-29 14:02:20 -0700556 if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700557 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
558 // This operation is a no-op if the table already exists.
559 addFavoritesTable(getWritableDatabase(), true);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700560 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700561 mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700562
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700563 initIds();
564 }
565
566 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700567 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700568 */
569 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700570 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800571 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700573 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700574 }
575
576 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700577 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
578 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700579 if (mMaxItemId == -1) {
580 mMaxItemId = initializeMaxItemId(getWritableDatabase());
581 }
582 if (mMaxScreenId == -1) {
583 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700584 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800585 }
586
587 @Override
588 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800589 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700590
Adam Cohendcd297f2013-06-18 13:13:40 -0700591 mMaxItemId = 1;
592 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700593
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700594 addFavoritesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800595
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800596 // Fresh and clean launcher DB.
597 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800598 onEmptyDbCreated();
599 }
600
Sunny Goyal161a2142018-10-29 14:02:20 -0700601 protected void onAddOrDeleteOp(SQLiteDatabase db) {
602 if (mBackupTableExists) {
603 dropTable(db, Favorites.BACKUP_TABLE_NAME);
604 mBackupTableExists = false;
605 }
606 }
607
Sunny Goyalf076eae2016-01-11 12:25:10 -0800608 /**
609 * Overriden in tests.
610 */
611 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700612 // Database was just created, so wipe any previous widgets
613 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700614 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700615 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530616 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700617 }
618
Sunny Goyalf076eae2016-01-11 12:25:10 -0800619 // Set the flag for empty DB
620 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800621 }
622
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700623 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800624 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800625 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800626 }
627
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700628 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700629 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700630 }
631
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700633 public void onOpen(SQLiteDatabase db) {
634 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700635
636 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
637 if (!schemaFile.exists()) {
638 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700639 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800640 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700641 }
642
643 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700644 * One-time data updated before support of onDowngrade was added. This update is backwards
645 * compatible and can safely be run multiple times.
646 * Note: No new logic should be added here after release, as the new logic might not get
647 * executed on an existing device.
648 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700649 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700650 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
651 // Remove "profile extra"
652 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
653 for (UserHandle user : um.getUserProfiles()) {
654 long serial = um.getSerialNumberForUser(user);
655 String sql = "update favorites set intent = replace(intent, "
656 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
657 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700658 }
659 }
660
661 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800662 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700663 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800664 switch (oldVersion) {
665 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800666 // version of the DB.
Sunny Goyalc5939392018-12-07 11:43:47 -0800667 case 12:
668 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800669 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700670 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800671 // Insert new column for holding widget provider name
672 db.execSQL("ALTER TABLE favorites " +
673 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700674 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800675 } catch (SQLException ex) {
676 Log.e(TAG, ex.getMessage(), ex);
677 // Old version remains, which means we wipe old data
678 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800679 }
680 }
681 case 14: {
Sunny Goyalc5939392018-12-07 11:43:47 -0800682 if (!addIntegerColumn(db, Favorites.MODIFIED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800683 // Old version remains, which means we wipe old data
684 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800685 }
686 }
687 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700688 if (!addIntegerColumn(db, Favorites.RESTORED, 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 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800693 case 16:
Sunny Goyal10629b02016-09-01 12:50:11 -0700694 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800695 case 17:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800696 // No-op
Sunny Goyalc5939392018-12-07 11:43:47 -0800697 case 18:
698 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800699 case 19: {
700 // Add userId column
Sunny Goyalc5939392018-12-07 11:43:47 -0800701 if (!addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial())) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800702 // Old version remains, which means we wipe old data
703 break;
704 }
705 }
706 case 20:
707 if (!updateFolderItemsRank(db, true)) {
708 break;
709 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800710 case 21:
Sunny Goyalc5939392018-12-07 11:43:47 -0800711 // No-op
Sunny Goyald2f38192015-02-25 10:46:34 -0800712 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700713 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
714 // Old version remains, which means we wipe old data
715 break;
716 }
717 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700718 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700719 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700720 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000721 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700722 case 25:
723 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700724 case 26:
725 // QSB was moved to the grid. Clear the first row on screen 0.
Ryan Lothianfa530cd2018-10-12 14:14:16 -0400726 if (FeatureFlags.QSB_ON_FIRST_SCREEN.get() &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800727 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700728 break;
729 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800730 case 27: {
731 // Update the favorites table so that the screen ids are ordered based on
732 // workspace page rank.
733 IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
734 BaseColumns._ID, null, null, "screenRank");
735 int[] original = finalScreens.toArray();
736 Arrays.sort(original);
737 String updatemap = "";
738 for (int i = 0; i < original.length; i++) {
739 if (finalScreens.get(i) != original[i]) {
740 updatemap += String.format(Locale.ENGLISH, " WHEN %1$s=%2$d THEN %3$d",
741 Favorites.SCREEN, finalScreens.get(i), original[i]);
742 }
743 }
744 if (!TextUtils.isEmpty(updatemap)) {
745 String query = String.format(Locale.ENGLISH,
746 "UPDATE %1$s SET %2$s=CASE %3$s ELSE %2$s END WHERE %4$s = %5$d",
747 Favorites.TABLE_NAME, Favorites.SCREEN, updatemap,
748 Favorites.CONTAINER, Favorites.CONTAINER_DESKTOP);
749 db.execSQL(query);
750 }
Sunny Goyal161a2142018-10-29 14:02:20 -0700751 dropTable(db, "workspaceScreens");
Sunny Goyalc5939392018-12-07 11:43:47 -0800752 }
753 case 28:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800754 // DB Upgraded successfully
755 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400756 }
757
Sunny Goyala2cc6242015-01-14 14:23:02 -0800758 // DB was not upgraded
759 Log.w(TAG, "Destroying all old data.");
760 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800761 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800762
Adam Cohen9b1d0622014-05-21 19:01:57 -0700763 @Override
764 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700765 try {
766 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
767 .onDowngrade(db, oldVersion, newVersion);
768 } catch (Exception e) {
769 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
770 ". Wiping databse.", e);
771 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700772 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700773 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700774
Sunny Goyal42de82f2014-09-26 22:09:29 -0700775 /**
776 * Clears all the data for a fresh start.
777 */
778 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700779 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal161a2142018-10-29 14:02:20 -0700780 dropTable(db, Favorites.TABLE_NAME);
781 dropTable(db, "workspaceScreens");
Sunny Goyale05b08f2017-02-23 18:30:22 -0800782 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700783 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800784 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700785 }
786
Sunny Goyald2f38192015-02-25 10:46:34 -0800787 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700788 * Removes widgets which are registered to the Launcher's host, but are not present
789 * in our model.
790 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700791 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700792 public void removeGhostWidgets(SQLiteDatabase db) {
793 // Get all existing widget ids.
794 final AppWidgetHost host = newLauncherWidgetHost();
795 final int[] allWidgets;
796 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700797 // Although the method was defined in O, it has existed since the beginning of time,
798 // so it might work on older platforms as well.
799 allWidgets = host.getAppWidgetIds();
800 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700801 Log.e(TAG, "getAppWidgetIds not supported", e);
802 return;
803 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800804 final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
805 Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
806 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700807 for (int widgetId : allWidgets) {
808 if (!validWidgets.contains(widgetId)) {
809 try {
810 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
811 host.deleteAppWidgetId(widgetId);
812 } catch (RuntimeException e) {
813 // Ignore
814 }
815 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700816 }
817 }
818
819 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700820 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
821 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
822 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700823 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700824 try (SQLiteTransaction t = new SQLiteTransaction(db);
825 // Only consider the primary user as other users can't have a shortcut.
826 Cursor c = db.query(Favorites.TABLE_NAME,
827 new String[] { Favorites._ID, Favorites.INTENT},
828 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
829 " AND profileId=" + getDefaultUserSerial(),
830 null, null, null, null);
831 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
832 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
833 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700834 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
835 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
836
837 while (c.moveToNext()) {
838 String intentDescription = c.getString(intentIndex);
839 Intent intent;
840 try {
841 intent = Intent.parseUri(intentDescription, 0);
842 } catch (URISyntaxException e) {
843 Log.e(TAG, "Unable to parse intent", e);
844 continue;
845 }
846
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700847 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700848 continue;
849 }
850
Sunny Goyalefb7e842018-10-04 15:11:00 -0700851 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700852 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700853 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700854 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700855 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700856 } catch (SQLException ex) {
857 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700858 }
859 }
860
Adam Cohen091440a2015-03-18 14:16:05 -0700861 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700862 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800863 if (addRankColumn) {
864 // Insert new column for holding rank
865 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
866 }
867
868 // Get a map for folder ID to folder width
869 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
870 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
871 + " GROUP BY container;",
872 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
873
874 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800875 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
876 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800877 new Object[] {c.getLong(1) + 1, c.getLong(0)});
878 }
879
880 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700881 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800882 } catch (SQLException ex) {
883 // Old version remains, which means we wipe old data
884 Log.e(TAG, ex.getMessage(), ex);
885 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800886 }
887 return true;
888 }
889
Sunny Goyal5d85c442015-03-10 13:14:47 -0700890 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700891 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700892 db.execSQL("ALTER TABLE favorites ADD COLUMN "
893 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700894 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100895 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100896 Log.e(TAG, ex.getMessage(), ex);
897 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100898 }
899 return true;
900 }
901
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700902 // Generates a new ID to use for an object in your database. This method should be only
903 // called from the main UI thread. As an exception, we do call it when we call the
904 // constructor from the worker thread; however, this doesn't extend until after the
905 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
906 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700907 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700908 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700909 if (mMaxItemId < 0) {
910 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700911 }
Adam Cohendcd297f2013-06-18 13:13:40 -0700912 mMaxItemId += 1;
913 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700914 }
915
Sunny Goyal55fddc82017-04-06 15:02:52 -0700916 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -0700917 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -0700918 }
919
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700920 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -0700921 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700922 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700923 }
924
Sunny Goyalc5939392018-12-07 11:43:47 -0800925 public void checkId(ContentValues values) {
926 int id = values.getAsInteger(Favorites._ID);
927 mMaxItemId = Math.max(id, mMaxItemId);
928
929 Integer screen = values.getAsInteger(Favorites.SCREEN);
930 Integer container = values.getAsInteger(Favorites.CONTAINER);
931 if (screen != null && container != null
932 && container.intValue() == Favorites.CONTAINER_DESKTOP) {
933 mMaxScreenId = Math.max(screen, mMaxScreenId);
Chris Wren5dee7af2013-12-20 17:22:11 -0500934 }
935 }
936
Sunny Goyalefb7e842018-10-04 15:11:00 -0700937 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800938 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -0700939 }
940
941 // Generates a new ID to use for an workspace screen in your database. This method
942 // should be only called from the main UI thread. As an exception, we do call it when we
943 // call the constructor from the worker thread; however, this doesn't extend until after the
944 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
945 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -0700946 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -0700947 if (mMaxScreenId < 0) {
948 throw new RuntimeException("Error: max screen id was not initialized");
949 }
950 mMaxScreenId += 1;
951 return mMaxScreenId;
952 }
953
Sunny Goyalefb7e842018-10-04 15:11:00 -0700954 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalc5939392018-12-07 11:43:47 -0800955 return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
956 Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
957 Favorites.CONTAINER_DESKTOP);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -0700958 }
959
Adam Cohen091440a2015-03-18 14:16:05 -0700960 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700961 // TODO: Use multiple loaders with fall-back and transaction.
Sunny Goyalc5939392018-12-07 11:43:47 -0800962 int count = loader.loadLayout(db, new IntArray());
Adam Cohen71483f42014-05-15 14:04:01 -0700963
964 // Ensure that the max ids are initialized
965 mMaxItemId = initializeMaxItemId(db);
966 mMaxScreenId = initializeMaxScreenId(db);
967 return count;
968 }
Mike Cleronb87bd162009-10-30 16:36:56 -0700969 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -0700970
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800971 /**
972 * @return the max _id in the provided table.
973 */
Sunny Goyalc5939392018-12-07 11:43:47 -0800974 @Thunk static int getMaxId(SQLiteDatabase db, String query, Object... args) {
975 int max = (int) DatabaseUtils.longForQuery(db,
976 String.format(Locale.ENGLISH, query, args),
977 null);
978 if (max < 0) {
979 throw new RuntimeException("Error: could not query max id");
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800980 }
Sunny Goyalc5939392018-12-07 11:43:47 -0800981 return max;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -0800982 }
983
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800984 static class SqlArguments {
985 public final String table;
986 public final String where;
987 public final String[] args;
988
989 SqlArguments(Uri url, String where, String[] args) {
990 if (url.getPathSegments().size() == 1) {
991 this.table = url.getPathSegments().get(0);
992 this.where = where;
993 this.args = args;
994 } else if (url.getPathSegments().size() != 2) {
995 throw new IllegalArgumentException("Invalid URI: " + url);
996 } else if (!TextUtils.isEmpty(where)) {
997 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
998 } else {
999 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001000 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001001 this.args = null;
1002 }
1003 }
1004
1005 SqlArguments(Uri url) {
1006 if (url.getPathSegments().size() == 1) {
1007 table = url.getPathSegments().get(0);
1008 where = null;
1009 args = null;
1010 } else {
1011 throw new IllegalArgumentException("Invalid URI: " + url);
1012 }
1013 }
1014 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001015
1016 private static class ChangeListenerWrapper implements Handler.Callback {
1017
1018 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001019 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001020
1021 private LauncherProviderChangeListener mListener;
1022
1023 @Override
1024 public boolean handleMessage(Message msg) {
1025 if (mListener != null) {
1026 switch (msg.what) {
1027 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001028 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001029 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001030 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001031 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001032 break;
1033 }
1034 }
1035 return true;
1036 }
1037 }
Adam Cohen72960972014-01-15 18:13:55 -08001038}