blob: a423a90f841a5200ffdfb52d37be5cfb5ff396bb [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 Goyal22ca9ec2017-05-18 15:03:13 -070019import android.annotation.TargetApi;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070020import android.appwidget.AppWidgetHost;
Mike Cleronb87bd162009-10-30 16:36:56 -070021import android.appwidget.AppWidgetManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080022import android.content.ComponentName;
Adam Cohen228da5a2011-07-27 22:23:47 -070023import android.content.ContentProvider;
Yura085c8532014-02-11 15:15:29 +000024import android.content.ContentProviderOperation;
25import android.content.ContentProviderResult;
Adam Cohen228da5a2011-07-27 22:23:47 -070026import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Yura085c8532014-02-11 15:15:29 +000030import android.content.OperationApplicationException;
Michael Jurkab85f8a42012-04-25 15:48:32 -070031import android.content.SharedPreferences;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070032import android.content.pm.PackageManager.NameNotFoundException;
Adam Cohen228da5a2011-07-27 22:23:47 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.database.Cursor;
35import android.database.SQLException;
Adam Cohen228da5a2011-07-27 22:23:47 -070036import android.database.sqlite.SQLiteDatabase;
Adam Cohen228da5a2011-07-27 22:23:47 -070037import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070038import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070039import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070040import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070041import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070042import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070043import android.os.Handler;
44import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070045import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080046import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070047import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070048import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070050
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
52import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070053import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010054import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070055import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080056import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070057import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070058import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070059import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070060import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalefb7e842018-10-04 15:11:00 -070061import com.android.launcher3.util.IntArray;
62import com.android.launcher3.util.IntSet;
Sunny Goyal19026b22018-03-09 14:37:37 -080063import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Sunny Goyal05f30882017-05-03 12:42:18 -070067import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070070import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070071import java.util.ArrayList;
Sunny Goyalefb7e842018-10-04 15:11:00 -070072import java.util.Arrays;
Adam Cohen71483f42014-05-15 14:04:01 -070073import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070074import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070075import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070078 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080079 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Sunny Goyal05f30882017-05-03 12:42:18 -070081 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
82
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070083 /**
84 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
85 */
Sunny Goyal05f30882017-05-03 12:42:18 -070086 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Sunny Goyal85525172017-11-06 13:00:42 -080088 public static final String AUTHORITY = FeatureFlags.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070089
Sunny Goyale87e6ab2014-11-21 22:42:53 -080090 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070092 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
93
Sunny Goyalb5b55c82016-05-10 12:28:59 -070094 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
95 private Handler mListenerHandler;
96
Sunny Goyalf076eae2016-01-11 12:25:10 -080097 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Hyunyoung Song6aa37292017-02-06 10:46:24 -080099 /**
100 * $ adb shell dumpsys activity provider com.android.launcher3
101 */
102 @Override
103 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
104 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
105 if (appState == null || !appState.getModel().isModelLoaded()) {
106 return;
107 }
108 appState.getModel().dumpState("", fd, writer, args);
109 }
110
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800111 @Override
112 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800113 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700114 Log.d(TAG, "Launcher process started");
115 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700116 mListenerHandler = new Handler(mListenerWrapper);
117
Sunny Goyalfdbef272017-02-01 12:52:54 -0800118 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800119 // is the first component to get created.
120 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800121 return true;
122 }
123
Sunny Goyald3849d12015-10-29 10:28:32 -0700124 /**
125 * Sets a provider listener.
126 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700127 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700128 Preconditions.assertUIThread();
129 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700130 }
131
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132 @Override
133 public String getType(Uri uri) {
134 SqlArguments args = new SqlArguments(uri, null, null);
135 if (TextUtils.isEmpty(args.where)) {
136 return "vnd.android.cursor.dir/" + args.table;
137 } else {
138 return "vnd.android.cursor.item/" + args.table;
139 }
140 }
141
Sunny Goyalf076eae2016-01-11 12:25:10 -0800142 /**
143 * Overridden in tests
144 */
145 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700146 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700147 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700148
149 if (RestoreDbTask.isPending(getContext())) {
150 if (!RestoreDbTask.performRestore(mOpenHelper)) {
151 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
152 }
153 // Set is pending to false irrespective of the result, so that it doesn't get
154 // executed again.
155 RestoreDbTask.setPending(getContext(), false);
156 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700157 }
158 }
159
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160 @Override
161 public Cursor query(Uri uri, String[] projection, String selection,
162 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700163 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164
165 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
166 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
167 qb.setTables(args.table);
168
Romain Guy73b979d2009-06-09 12:57:21 -0700169 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
171 result.setNotificationUri(getContext().getContentResolver(), uri);
172
173 return result;
174 }
175
Sunny Goyalefb7e842018-10-04 15:11:00 -0700176 @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700177 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500178 if (values == null) {
179 throw new RuntimeException("Error: attempting to insert null values");
180 }
Adam Cohen71483f42014-05-15 14:04:01 -0700181 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 throw new RuntimeException("Error: attempting to add item without specifying an id");
183 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500184 helper.checkId(table, values);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700185 return (int) db.insert(table, nullColumnHack, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700186 }
187
Sunny Goyald1064182015-08-13 12:08:30 -0700188 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700189 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700190 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
191 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800192 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700193 }
194 }
195 }
196
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 @Override
198 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700199 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200 SqlArguments args = new SqlArguments(uri);
201
Sunny Goyald1064182015-08-13 12:08:30 -0700202 // In very limited cases, we support system|signature permission apps to modify the db.
203 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700204 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700205 return null;
206 }
207 }
208
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 addModifiedTime(initialValues);
Sunny Goyalefb7e842018-10-04 15:11:00 -0700211 final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800212 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
214 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700215 notifyListeners();
216
Sunny Goyalc74e4192015-09-08 14:01:03 -0700217 if (Utilities.ATLEAST_MARSHMALLOW) {
218 reloadLauncherIfExternal();
219 } else {
220 // Deprecated behavior to support legacy devices which rely on provider callbacks.
221 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
222 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800223 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700224 }
225
226 String notify = uri.getQueryParameter("notify");
227 if (notify == null || "true".equals(notify)) {
228 getContext().getContentResolver().notifyChange(uri, null);
229 }
230 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 return uri;
232 }
233
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700234 private boolean initializeExternalAdd(ContentValues values) {
235 // 1. Ensure that externally added items have a valid item id
Sunny Goyalefb7e842018-10-04 15:11:00 -0700236 int id = mOpenHelper.generateNewItemId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700237 values.put(LauncherSettings.Favorites._ID, id);
238
239 // 2. In the case of an app widget, and if no app widget id is specified, we
240 // attempt allocate and bind the widget.
241 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
242 if (itemType != null &&
243 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
244 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
245
246 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
247 ComponentName cn = ComponentName.unflattenFromString(
248 values.getAsString(Favorites.APPWIDGET_PROVIDER));
249
250 if (cn != null) {
251 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700252 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
253 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700254 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
255 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700256 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700257 return false;
258 }
259 } catch (RuntimeException e) {
260 Log.e(TAG, "Failed to initialize external widget", e);
261 return false;
262 }
263 } else {
264 return false;
265 }
266 }
267
268 // Add screen id if not present
Sunny Goyalefb7e842018-10-04 15:11:00 -0700269 int screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700270 SQLiteStatement stmp = null;
271 try {
272 stmp = mOpenHelper.getWritableDatabase().compileStatement(
273 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
274 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
275 stmp.bindLong(1, screenId);
276
277 ContentValues valuesInserted = new ContentValues();
278 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
279 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
280 return true;
281 } catch (Exception e) {
282 return false;
283 } finally {
284 Utilities.closeSilently(stmp);
285 }
286 }
287
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 @Override
289 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700290 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 SqlArguments args = new SqlArguments(uri);
292
293 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700294 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800295 int numValues = values.length;
296 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400297 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700298 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
299 return 0;
300 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700302 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800303 }
304
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700305 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700306 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800307 return values.length;
308 }
309
310 @Override
Yura085c8532014-02-11 15:15:29 +0000311 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
312 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700313 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700314 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000315 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700316 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700317 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000318 return result;
Yura085c8532014-02-11 15:15:29 +0000319 }
320 }
321
322 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800323 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700324 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800325 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
326
327 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328
Louis Begina9c21c62016-08-15 15:18:41 -0700329 if (Binder.getCallingPid() != Process.myPid()
330 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700331 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700332 }
333 int count = db.delete(args.table, args.where, args.args);
334 if (count > 0) {
335 notifyListeners();
336 reloadLauncherIfExternal();
337 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800338 return count;
339 }
340
341 @Override
342 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700343 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
345
Chris Wren1ada10d2013-09-13 18:01:38 -0400346 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
348 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700349 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350
Sunny Goyald1064182015-08-13 12:08:30 -0700351 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800352 return count;
353 }
354
Sunny Goyal7779d622015-06-11 16:18:39 -0700355 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700356 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700357 if (Binder.getCallingUid() != Process.myUid()) {
358 return null;
359 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700360 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700361
362 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700363 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
364 clearFlagEmptyDbCreated();
365 return null;
366 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700367 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
368 Bundle result = new Bundle();
369 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
370 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
371 return result;
372 }
Sunny Goyald2497482015-09-22 18:24:19 -0700373 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
374 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700375 result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
376 .toArray());
Sunny Goyald2497482015-09-22 18:24:19 -0700377 return result;
378 }
379 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
380 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700381 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
Sunny Goyald2497482015-09-22 18:24:19 -0700382 return result;
383 }
384 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
385 Bundle result = new Bundle();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700386 result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
Sunny Goyald2497482015-09-22 18:24:19 -0700387 return result;
388 }
389 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800390 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700391 return null;
392 }
393 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
394 loadDefaultFavoritesIfNecessary();
395 return null;
396 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700397 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
398 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
399 return null;
400 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700401 }
402 return null;
403 }
404
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700405 /**
406 * Deletes any empty folder from the DB.
407 * @return Ids of deleted folders.
408 */
Sunny Goyalefb7e842018-10-04 15:11:00 -0700409 private IntArray deleteEmptyFolders() {
410 IntArray folderIds = new IntArray();
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 Goyaldbfc9012017-04-17 16:58:36 -0700419 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700420 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700421 selection, null, null, null, null)) {
422 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700423 }
Sunny Goyald2497482015-09-22 18:24:19 -0700424 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700425 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700426 LauncherSettings.Favorites._ID, folderIds), null);
427 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700428 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 } catch (SQLException ex) {
430 Log.e(TAG, ex.getMessage(), ex);
431 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700432 }
433 return folderIds;
434 }
435
Sunny Goyalf076eae2016-01-11 12:25:10 -0800436 /**
437 * Overridden in tests
438 */
439 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700440 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400441 }
442
Adam Cohen091440a2015-03-18 14:16:05 -0700443 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400444 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800445 }
446
Sunny Goyald2497482015-09-22 18:24:19 -0700447 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700448 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700449 }
450
Sunny Goyal42de82f2014-09-26 22:09:29 -0700451 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700452 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700453 * 1) From the app restrictions
454 * 2) From a package provided by play store
455 * 3) From a partner configuration APK, already in the system image
456 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700457 */
Sunny Goyald2497482015-09-22 18:24:19 -0700458 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700459 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700460
Winson Chungc763c4e2013-07-19 13:49:06 -0700461 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500462 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200463
Sunny Goyal55fddc82017-04-06 15:02:52 -0700464 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700465 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700466 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700467 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700468 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700469 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700470 final Partner partner = Partner.get(getContext().getPackageManager());
471 if (partner != null && partner.hasDefaultLayout()) {
472 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700473 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700474 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700475 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700476 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700477 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700478 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700479 }
480 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481
Sunny Goyal9d219682014-10-23 14:21:02 -0700482 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700483 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700484 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700485 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800486
487 // There might be some partially restored DB items, due to buggy restore logic in
488 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800489 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700490 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700491 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
492 && usingExternallyProvidedLayout) {
493 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800494 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700496 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700497 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700498 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700499 }
500 }
501
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700502 /**
503 * Creates workspace loader from an XML resource listed in the app restrictions.
504 *
505 * @return the loader if the restrictions are set and the resource exists; null otherwise.
506 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700507 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700508 Context ctx = getContext();
509 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
510 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700511 if (bundle == null) {
512 return null;
513 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700514
Sunny Goyal35ca8732015-04-06 10:45:31 -0700515 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700516 if (packageName != null) {
517 try {
518 Resources targetResources = ctx.getPackageManager()
519 .getResourcesForApplication(packageName);
520 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700521 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700522 } catch (NameNotFoundException e) {
523 Log.e(TAG, "Target package for restricted profile not found", e);
524 return null;
525 }
526 }
527 return null;
528 }
529
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700530 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700531 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
532 int defaultLayout = idp.defaultLayoutId;
533
534 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
535 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
536 defaultLayout = idp.demoModeLayoutId;
537 }
538
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700539 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700540 mOpenHelper, getContext().getResources(), defaultLayout);
541 }
542
Sunny Goyald3849d12015-10-29 10:28:32 -0700543 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800544 * The class is subclassed in tests to create an in-memory db.
545 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800546 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800551
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700552 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
553 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700554 // Table creation sometimes fails silently, which leads to a crash loop.
555 // This way, we will try to create a table every time after crash, so the device
556 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700557 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700558 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
559 // This operation is a no-op if the table already exists.
560 addFavoritesTable(getWritableDatabase(), true);
561 addWorkspacesTable(getWritableDatabase(), true);
562 }
563
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700564 initIds();
565 }
566
567 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700568 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700569 */
570 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700571 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800572 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700573 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700574 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700575 }
576
577 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700578 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
579 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700580 if (mMaxItemId == -1) {
581 mMaxItemId = initializeMaxItemId(getWritableDatabase());
582 }
583 if (mMaxScreenId == -1) {
584 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700585 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800586 }
587
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700588 private boolean tableExists(String tableName) {
589 Cursor c = getReadableDatabase().query(
590 true, "sqlite_master", new String[] {"tbl_name"},
591 "tbl_name = ?", new String[] {tableName},
592 null, null, null, null, null);
593 try {
594 return c.getCount() > 0;
595 } finally {
596 c.close();
597 }
598 }
599
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800600 @Override
601 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800602 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700603
Adam Cohendcd297f2013-06-18 13:13:40 -0700604 mMaxItemId = 1;
605 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700606
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700607 addFavoritesTable(db, false);
608 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800610 // Fresh and clean launcher DB.
611 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800612 onEmptyDbCreated();
613 }
614
615 /**
616 * Overriden in tests.
617 */
618 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700619 // Database was just created, so wipe any previous widgets
620 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700621 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700622 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530623 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700624 }
625
Sunny Goyalf076eae2016-01-11 12:25:10 -0800626 // Set the flag for empty DB
627 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800628 }
629
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700630 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800631 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800632 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 }
634
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700635 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700636 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700637 }
638
639 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
640 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700641 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800642 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400643 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
644 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700645 ");");
646 }
647
Adam Cohen119285e2014-04-02 16:59:08 -0700648 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700649 // Delete items directly on the workspace who's screen id doesn't exist
650 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
651 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700652 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700653 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700654 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700655 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700656 " AND " +
657 LauncherSettings.Favorites.CONTAINER + " = " +
658 LauncherSettings.Favorites.CONTAINER_DESKTOP;
659 db.execSQL(removeOrphanedDesktopItems);
660
661 // Delete items contained in folders which no longer exist (after above statement)
662 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
663 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700664 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700665 " WHERE " +
666 LauncherSettings.Favorites.CONTAINER + " <> " +
667 LauncherSettings.Favorites.CONTAINER_DESKTOP +
668 " AND "
669 + LauncherSettings.Favorites.CONTAINER + " <> " +
670 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
671 " AND "
672 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700673 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700674 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
675 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
676 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700677 }
678
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700680 public void onOpen(SQLiteDatabase db) {
681 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700682
683 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
684 if (!schemaFile.exists()) {
685 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700686 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700687 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
688 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700689 }
690
691 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700692 * One-time data updated before support of onDowngrade was added. This update is backwards
693 * compatible and can safely be run multiple times.
694 * Note: No new logic should be added here after release, as the new logic might not get
695 * executed on an existing device.
696 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700697 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700698 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
699 // Remove "profile extra"
700 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
701 for (UserHandle user : um.getUserProfiles()) {
702 long serial = um.getSerialNumberForUser(user);
703 String sql = "update favorites set intent = replace(intent, "
704 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
705 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700706 }
707 }
708
709 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800710 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700711 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800712 switch (oldVersion) {
713 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800714 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800715 case 12: {
716 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
717 // to persist workspace screens and their relative order.
718 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700719 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800720 }
721 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700722 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800723 // Insert new column for holding widget provider name
724 db.execSQL("ALTER TABLE favorites " +
725 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700726 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 } catch (SQLException ex) {
728 Log.e(TAG, ex.getMessage(), ex);
729 // Old version remains, which means we wipe old data
730 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800731 }
732 }
733 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700734 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800735 // Insert new column for holding update timestamp
736 db.execSQL("ALTER TABLE favorites " +
737 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
738 db.execSQL("ALTER TABLE workspaceScreens " +
739 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700740 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800741 } catch (SQLException ex) {
742 Log.e(TAG, ex.getMessage(), ex);
743 // Old version remains, which means we wipe old data
744 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800745 }
746 }
747 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700748 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800749 // Old version remains, which means we wipe old data
750 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 }
752 }
753 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700754 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800755 }
756 case 17: {
757 // No-op
758 }
759 case 18: {
760 // Due to a data loss bug, some users may have items associated with screen ids
761 // which no longer exist. Since this can cause other problems, and since the user
762 // will never see these items anyway, we use database upgrade as an opportunity to
763 // clean things up.
764 removeOrphanedItems(db);
765 }
766 case 19: {
767 // Add userId column
768 if (!addProfileColumn(db)) {
769 // Old version remains, which means we wipe old data
770 break;
771 }
772 }
773 case 20:
774 if (!updateFolderItemsRank(db, true)) {
775 break;
776 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800777 case 21:
778 // Recreate workspace table with screen id a primary key
779 if (!recreateWorkspaceTable(db)) {
780 break;
781 }
782 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700783 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
784 // Old version remains, which means we wipe old data
785 break;
786 }
787 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700788 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700789 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700790 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000791 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700792 case 25:
793 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700794 case 26:
795 // QSB was moved to the grid. Clear the first row on screen 0.
Ryan Lothian688e9892018-10-03 13:32:01 -0400796 if (FeatureFlags.getInstance(mContext).isQsbOnFirstScreenEnabled() &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800797 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700798 break;
799 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700800 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800801 // DB Upgraded successfully
802 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400803 }
804
Sunny Goyala2cc6242015-01-14 14:23:02 -0800805 // DB was not upgraded
806 Log.w(TAG, "Destroying all old data.");
807 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800808 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800809
Adam Cohen9b1d0622014-05-21 19:01:57 -0700810 @Override
811 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700812 try {
813 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
814 .onDowngrade(db, oldVersion, newVersion);
815 } catch (Exception e) {
816 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
817 ". Wiping databse.", e);
818 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700819 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700820 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700821
Sunny Goyal42de82f2014-09-26 22:09:29 -0700822 /**
823 * Clears all the data for a fresh start.
824 */
825 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700826 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800827 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
828 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
829 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700830 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800831 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700832 }
833
Sunny Goyald2f38192015-02-25 10:46:34 -0800834 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700835 * Removes widgets which are registered to the Launcher's host, but are not present
836 * in our model.
837 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700838 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700839 public void removeGhostWidgets(SQLiteDatabase db) {
840 // Get all existing widget ids.
841 final AppWidgetHost host = newLauncherWidgetHost();
842 final int[] allWidgets;
843 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700844 // Although the method was defined in O, it has existed since the beginning of time,
845 // so it might work on older platforms as well.
846 allWidgets = host.getAppWidgetIds();
847 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700848 Log.e(TAG, "getAppWidgetIds not supported", e);
849 return;
850 }
Sunny Goyalefb7e842018-10-04 15:11:00 -0700851 final IntSet validWidgets = new IntSet();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700852 try (Cursor c = db.query(Favorites.TABLE_NAME,
853 new String[] {Favorites.APPWIDGET_ID },
854 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700855 while (c.moveToNext()) {
856 validWidgets.add(c.getInt(0));
857 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700858 } catch (SQLException ex) {
859 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700860 return;
861 }
862 for (int widgetId : allWidgets) {
863 if (!validWidgets.contains(widgetId)) {
864 try {
865 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
866 host.deleteAppWidgetId(widgetId);
867 } catch (RuntimeException e) {
868 // Ignore
869 }
870 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700871 }
872 }
873
874 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700875 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
876 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
877 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700878 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700879 try (SQLiteTransaction t = new SQLiteTransaction(db);
880 // Only consider the primary user as other users can't have a shortcut.
881 Cursor c = db.query(Favorites.TABLE_NAME,
882 new String[] { Favorites._ID, Favorites.INTENT},
883 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
884 " AND profileId=" + getDefaultUserSerial(),
885 null, null, null, null);
886 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
887 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
888 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700889 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
890 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
891
892 while (c.moveToNext()) {
893 String intentDescription = c.getString(intentIndex);
894 Intent intent;
895 try {
896 intent = Intent.parseUri(intentDescription, 0);
897 } catch (URISyntaxException e) {
898 Log.e(TAG, "Unable to parse intent", e);
899 continue;
900 }
901
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700902 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700903 continue;
904 }
905
Sunny Goyalefb7e842018-10-04 15:11:00 -0700906 int id = c.getInt(idIndex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700907 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700908 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700909 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700910 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700911 } catch (SQLException ex) {
912 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700913 }
914 }
915
916 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800917 * Recreates workspace table and migrates data to the new table.
918 */
919 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700920 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalefb7e842018-10-04 15:11:00 -0700921 final IntArray sortedIDs;
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700922
923 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800924 new String[] {LauncherSettings.WorkspaceScreens._ID},
925 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700926 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
927 // Use LinkedHashSet so that ordering is preserved
Sunny Goyalefb7e842018-10-04 15:11:00 -0700928 sortedIDs = LauncherDbUtils.getScreenIdsFromCursor(c);
Sunny Goyald2f38192015-02-25 10:46:34 -0800929 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700930 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700931 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800932
933 // Add all screen ids back
934 int total = sortedIDs.size();
935 for (int i = 0; i < total; i++) {
936 ContentValues values = new ContentValues();
937 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
938 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
939 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700940 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800941 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700942 t.commit();
Sunny Goyalefb7e842018-10-04 15:11:00 -0700943
944 mMaxScreenId = 0;
945 for (int i = 0; i < sortedIDs.size(); i++) {
946 mMaxScreenId = Math.max(mMaxScreenId, sortedIDs.get(i));
947 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800948 } catch (SQLException ex) {
949 // Old version remains, which means we wipe old data
950 Log.e(TAG, ex.getMessage(), ex);
951 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800952 }
953 return true;
954 }
955
Adam Cohen091440a2015-03-18 14:16:05 -0700956 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700957 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800958 if (addRankColumn) {
959 // Insert new column for holding rank
960 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
961 }
962
963 // Get a map for folder ID to folder width
964 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
965 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
966 + " GROUP BY container;",
967 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
968
969 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800970 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
971 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800972 new Object[] {c.getLong(1) + 1, c.getLong(0)});
973 }
974
975 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700976 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800977 } catch (SQLException ex) {
978 // Old version remains, which means we wipe old data
979 Log.e(TAG, ex.getMessage(), ex);
980 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800981 }
982 return true;
983 }
984
Kenny Guyed131872014-04-30 03:02:21 +0100985 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700986 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700987 }
988
989 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700990 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700991 db.execSQL("ALTER TABLE favorites ADD COLUMN "
992 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700993 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100994 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100995 Log.e(TAG, ex.getMessage(), ex);
996 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100997 }
998 return true;
999 }
1000
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001001 // Generates a new ID to use for an object in your database. This method should be only
1002 // called from the main UI thread. As an exception, we do call it when we call the
1003 // constructor from the worker thread; however, this doesn't extend until after the
1004 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1005 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001006 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001007 public int generateNewItemId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001008 if (mMaxItemId < 0) {
1009 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001010 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001011 mMaxItemId += 1;
1012 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001013 }
1014
Sunny Goyal55fddc82017-04-06 15:02:52 -07001015 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001016 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001017 }
1018
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001019 @Override
Sunny Goyalefb7e842018-10-04 15:11:00 -07001020 public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001021 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001022 }
1023
Chris Wren5dee7af2013-12-20 17:22:11 -05001024 public void checkId(String table, ContentValues values) {
Sunny Goyalefb7e842018-10-04 15:11:00 -07001025 int id = values.getAsInteger(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001026 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001027 mMaxScreenId = Math.max(id, mMaxScreenId);
1028 } else {
1029 mMaxItemId = Math.max(id, mMaxItemId);
1030 }
1031 }
1032
Sunny Goyalefb7e842018-10-04 15:11:00 -07001033 private int initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001034 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001035 }
1036
1037 // Generates a new ID to use for an workspace screen in your database. This method
1038 // should be only called from the main UI thread. As an exception, we do call it when we
1039 // call the constructor from the worker thread; however, this doesn't extend until after the
1040 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1041 // after that point
Sunny Goyalefb7e842018-10-04 15:11:00 -07001042 public int generateNewScreenId() {
Adam Cohendcd297f2013-06-18 13:13:40 -07001043 if (mMaxScreenId < 0) {
1044 throw new RuntimeException("Error: max screen id was not initialized");
1045 }
1046 mMaxScreenId += 1;
1047 return mMaxScreenId;
1048 }
1049
Sunny Goyalefb7e842018-10-04 15:11:00 -07001050 private int initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001051 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001052 }
1053
Adam Cohen091440a2015-03-18 14:16:05 -07001054 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Sunny Goyalefb7e842018-10-04 15:11:00 -07001055 IntArray screenIds = new IntArray();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001056 // TODO: Use multiple loaders with fall-back and transaction.
1057 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001058
1059 // Add the screens specified by the items above
Sunny Goyalefb7e842018-10-04 15:11:00 -07001060 int[] sortedScreenIds = screenIds.toArray();
1061 Arrays.sort(sortedScreenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001062 int rank = 0;
1063 ContentValues values = new ContentValues();
Sunny Goyalefb7e842018-10-04 15:11:00 -07001064 for (int id : sortedScreenIds) {
Adam Cohen71483f42014-05-15 14:04:01 -07001065 values.clear();
1066 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1067 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001068 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001069 throw new RuntimeException("Failed initialize screen table"
1070 + "from default layout");
1071 }
1072 rank++;
1073 }
1074
1075 // Ensure that the max ids are initialized
1076 mMaxItemId = initializeMaxItemId(db);
1077 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001078
Adam Cohen71483f42014-05-15 14:04:01 -07001079 return count;
1080 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001081 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001082
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001083 /**
1084 * @return the max _id in the provided table.
1085 */
Sunny Goyalefb7e842018-10-04 15:11:00 -07001086 @Thunk static int getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001087 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1088 // get the result
Sunny Goyalefb7e842018-10-04 15:11:00 -07001089 int id = -1;
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001090 if (c != null && c.moveToNext()) {
Sunny Goyalefb7e842018-10-04 15:11:00 -07001091 id = c.getInt(0);
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001092 }
1093 if (c != null) {
1094 c.close();
1095 }
1096
1097 if (id == -1) {
1098 throw new RuntimeException("Error: could not query max id in " + table);
1099 }
1100
1101 return id;
1102 }
1103
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001104 static class SqlArguments {
1105 public final String table;
1106 public final String where;
1107 public final String[] args;
1108
1109 SqlArguments(Uri url, String where, String[] args) {
1110 if (url.getPathSegments().size() == 1) {
1111 this.table = url.getPathSegments().get(0);
1112 this.where = where;
1113 this.args = args;
1114 } else if (url.getPathSegments().size() != 2) {
1115 throw new IllegalArgumentException("Invalid URI: " + url);
1116 } else if (!TextUtils.isEmpty(where)) {
1117 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1118 } else {
1119 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001120 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001121 this.args = null;
1122 }
1123 }
1124
1125 SqlArguments(Uri url) {
1126 if (url.getPathSegments().size() == 1) {
1127 table = url.getPathSegments().get(0);
1128 where = null;
1129 args = null;
1130 } else {
1131 throw new IllegalArgumentException("Invalid URI: " + url);
1132 }
1133 }
1134 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001135
1136 private static class ChangeListenerWrapper implements Handler.Callback {
1137
1138 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001139 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001140
1141 private LauncherProviderChangeListener mListener;
1142
1143 @Override
1144 public boolean handleMessage(Message msg) {
1145 if (mListener != null) {
1146 switch (msg.what) {
1147 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001148 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001149 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001150 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001151 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001152 break;
1153 }
1154 }
1155 return true;
1156 }
1157 }
Adam Cohen72960972014-01-15 18:13:55 -08001158}