blob: 7d208d48d3ad6c0c4bf6e8f653724e822fea7714 [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 Goyal19026b22018-03-09 14:37:37 -080061import com.android.launcher3.util.NoLocaleSQLiteHelper;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070062import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070063import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070064
Sunny Goyal05f30882017-05-03 12:42:18 -070065import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080066import java.io.FileDescriptor;
67import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070068import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070069import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070070import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070071import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070072import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070075 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080076 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Sunny Goyal05f30882017-05-03 12:42:18 -070078 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
79
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070080 /**
81 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
82 */
Sunny Goyal05f30882017-05-03 12:42:18 -070083 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
Sunny Goyal85525172017-11-06 13:00:42 -080085 public static final String AUTHORITY = FeatureFlags.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070086
Sunny Goyale87e6ab2014-11-21 22:42:53 -080087 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070089 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
90
Sunny Goyalb5b55c82016-05-10 12:28:59 -070091 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
92 private Handler mListenerHandler;
93
Sunny Goyalf076eae2016-01-11 12:25:10 -080094 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095
Hyunyoung Song6aa37292017-02-06 10:46:24 -080096 /**
97 * $ adb shell dumpsys activity provider com.android.launcher3
98 */
99 @Override
100 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
101 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
102 if (appState == null || !appState.getModel().isModelLoaded()) {
103 return;
104 }
105 appState.getModel().dumpState("", fd, writer, args);
106 }
107
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108 @Override
109 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800110 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700111 Log.d(TAG, "Launcher process started");
112 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700113 mListenerHandler = new Handler(mListenerWrapper);
114
Sunny Goyalfdbef272017-02-01 12:52:54 -0800115 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800116 // is the first component to get created.
117 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800118 return true;
119 }
120
Sunny Goyald3849d12015-10-29 10:28:32 -0700121 /**
122 * Sets a provider listener.
123 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700124 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700125 Preconditions.assertUIThread();
126 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700127 }
128
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800129 @Override
130 public String getType(Uri uri) {
131 SqlArguments args = new SqlArguments(uri, null, null);
132 if (TextUtils.isEmpty(args.where)) {
133 return "vnd.android.cursor.dir/" + args.table;
134 } else {
135 return "vnd.android.cursor.item/" + args.table;
136 }
137 }
138
Sunny Goyalf076eae2016-01-11 12:25:10 -0800139 /**
140 * Overridden in tests
141 */
142 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700143 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700144 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700145
146 if (RestoreDbTask.isPending(getContext())) {
147 if (!RestoreDbTask.performRestore(mOpenHelper)) {
148 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
149 }
150 // Set is pending to false irrespective of the result, so that it doesn't get
151 // executed again.
152 RestoreDbTask.setPending(getContext(), false);
153 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700154 }
155 }
156
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800157 @Override
158 public Cursor query(Uri uri, String[] projection, String selection,
159 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700160 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800161
162 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
163 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
164 qb.setTables(args.table);
165
Romain Guy73b979d2009-06-09 12:57:21 -0700166 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
168 result.setNotificationUri(getContext().getContentResolver(), uri);
169
170 return result;
171 }
172
Adam Cohen091440a2015-03-18 14:16:05 -0700173 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700174 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500175 if (values == null) {
176 throw new RuntimeException("Error: attempting to insert null values");
177 }
Adam Cohen71483f42014-05-15 14:04:01 -0700178 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700179 throw new RuntimeException("Error: attempting to add item without specifying an id");
180 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500181 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700182 return db.insert(table, nullColumnHack, values);
183 }
184
Sunny Goyald1064182015-08-13 12:08:30 -0700185 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700186 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700187 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
188 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800189 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700190 }
191 }
192 }
193
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 @Override
195 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700196 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197 SqlArguments args = new SqlArguments(uri);
198
Sunny Goyald1064182015-08-13 12:08:30 -0700199 // In very limited cases, we support system|signature permission apps to modify the db.
200 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700201 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700202 return null;
203 }
204 }
205
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400207 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700208 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800209 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
211 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700212 notifyListeners();
213
Sunny Goyalc74e4192015-09-08 14:01:03 -0700214 if (Utilities.ATLEAST_MARSHMALLOW) {
215 reloadLauncherIfExternal();
216 } else {
217 // Deprecated behavior to support legacy devices which rely on provider callbacks.
218 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
219 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800220 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700221 }
222
223 String notify = uri.getQueryParameter("notify");
224 if (notify == null || "true".equals(notify)) {
225 getContext().getContentResolver().notifyChange(uri, null);
226 }
227 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800228 return uri;
229 }
230
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700231 private boolean initializeExternalAdd(ContentValues values) {
232 // 1. Ensure that externally added items have a valid item id
233 long id = mOpenHelper.generateNewItemId();
234 values.put(LauncherSettings.Favorites._ID, id);
235
236 // 2. In the case of an app widget, and if no app widget id is specified, we
237 // attempt allocate and bind the widget.
238 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
239 if (itemType != null &&
240 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
241 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
242
243 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
244 ComponentName cn = ComponentName.unflattenFromString(
245 values.getAsString(Favorites.APPWIDGET_PROVIDER));
246
247 if (cn != null) {
248 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700249 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
250 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700251 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
252 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700253 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700254 return false;
255 }
256 } catch (RuntimeException e) {
257 Log.e(TAG, "Failed to initialize external widget", e);
258 return false;
259 }
260 } else {
261 return false;
262 }
263 }
264
265 // Add screen id if not present
266 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
267 SQLiteStatement stmp = null;
268 try {
269 stmp = mOpenHelper.getWritableDatabase().compileStatement(
270 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
271 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
272 stmp.bindLong(1, screenId);
273
274 ContentValues valuesInserted = new ContentValues();
275 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
276 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
277 return true;
278 } catch (Exception e) {
279 return false;
280 } finally {
281 Utilities.closeSilently(stmp);
282 }
283 }
284
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800285 @Override
286 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700287 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800288 SqlArguments args = new SqlArguments(uri);
289
290 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700291 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800292 int numValues = values.length;
293 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400294 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700295 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
296 return 0;
297 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800298 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700299 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 }
301
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700302 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700303 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800304 return values.length;
305 }
306
307 @Override
Yura085c8532014-02-11 15:15:29 +0000308 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
309 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700310 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700311 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000312 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700313 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700314 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000315 return result;
Yura085c8532014-02-11 15:15:29 +0000316 }
317 }
318
319 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800320 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700321 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
323
324 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800325
Louis Begina9c21c62016-08-15 15:18:41 -0700326 if (Binder.getCallingPid() != Process.myPid()
327 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700328 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700329 }
330 int count = db.delete(args.table, args.where, args.args);
331 if (count > 0) {
332 notifyListeners();
333 reloadLauncherIfExternal();
334 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 return count;
336 }
337
338 @Override
339 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700340 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
342
Chris Wren1ada10d2013-09-13 18:01:38 -0400343 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
345 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700346 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800347
Sunny Goyald1064182015-08-13 12:08:30 -0700348 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349 return count;
350 }
351
Sunny Goyal7779d622015-06-11 16:18:39 -0700352 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700353 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700354 if (Binder.getCallingUid() != Process.myUid()) {
355 return null;
356 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700357 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700358
359 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700360 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
361 clearFlagEmptyDbCreated();
362 return null;
363 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700364 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
365 Bundle result = new Bundle();
366 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
367 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
368 return result;
369 }
Sunny Goyald2497482015-09-22 18:24:19 -0700370 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
371 Bundle result = new Bundle();
372 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
373 return result;
374 }
375 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
376 Bundle result = new Bundle();
377 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
378 return result;
379 }
380 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
381 Bundle result = new Bundle();
382 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
383 return result;
384 }
385 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800386 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700387 return null;
388 }
389 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
390 loadDefaultFavoritesIfNecessary();
391 return null;
392 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700393 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
394 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
395 return null;
396 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700397 }
398 return null;
399 }
400
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700401 /**
402 * Deletes any empty folder from the DB.
403 * @return Ids of deleted folders.
404 */
Sunny Goyald2497482015-09-22 18:24:19 -0700405 private ArrayList<Long> deleteEmptyFolders() {
406 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700407 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700408 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700409 // Select folders whose id do not match any container value.
410 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
411 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
412 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
413 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700414 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700415 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700416 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700417 selection, null, null, null, null)) {
418 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700419 }
Sunny Goyald2497482015-09-22 18:24:19 -0700420 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700421 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700422 LauncherSettings.Favorites._ID, folderIds), null);
423 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700424 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700425 } catch (SQLException ex) {
426 Log.e(TAG, ex.getMessage(), ex);
427 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700428 }
429 return folderIds;
430 }
431
Sunny Goyalf076eae2016-01-11 12:25:10 -0800432 /**
433 * Overridden in tests
434 */
435 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700436 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 }
438
Adam Cohen091440a2015-03-18 14:16:05 -0700439 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400440 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800441 }
442
Sunny Goyald2497482015-09-22 18:24:19 -0700443 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700444 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700445 }
446
Sunny Goyal42de82f2014-09-26 22:09:29 -0700447 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700448 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700449 * 1) From the app restrictions
450 * 2) From a package provided by play store
451 * 3) From a partner configuration APK, already in the system image
452 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700453 */
Sunny Goyald2497482015-09-22 18:24:19 -0700454 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700455 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700456
Winson Chungc763c4e2013-07-19 13:49:06 -0700457 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500458 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200459
Sunny Goyal55fddc82017-04-06 15:02:52 -0700460 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700461 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700462 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700463 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700464 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700465 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700466 final Partner partner = Partner.get(getContext().getPackageManager());
467 if (partner != null && partner.hasDefaultLayout()) {
468 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700469 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700470 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700471 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700472 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700473 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700474 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700475 }
476 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700477
Sunny Goyal9d219682014-10-23 14:21:02 -0700478 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700480 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700481 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800482
483 // There might be some partially restored DB items, due to buggy restore logic in
484 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800485 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700486 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700487 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
488 && usingExternallyProvidedLayout) {
489 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800490 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700491 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700492 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700493 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700494 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700495 }
496 }
497
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700498 /**
499 * Creates workspace loader from an XML resource listed in the app restrictions.
500 *
501 * @return the loader if the restrictions are set and the resource exists; null otherwise.
502 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700503 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700504 Context ctx = getContext();
505 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
506 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700507 if (bundle == null) {
508 return null;
509 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700510
Sunny Goyal35ca8732015-04-06 10:45:31 -0700511 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512 if (packageName != null) {
513 try {
514 Resources targetResources = ctx.getPackageManager()
515 .getResourcesForApplication(packageName);
516 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700517 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700518 } catch (NameNotFoundException e) {
519 Log.e(TAG, "Target package for restricted profile not found", e);
520 return null;
521 }
522 }
523 return null;
524 }
525
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700526 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700527 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
528 int defaultLayout = idp.defaultLayoutId;
529
530 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
531 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
532 defaultLayout = idp.demoModeLayoutId;
533 }
534
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700535 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700536 mOpenHelper, getContext().getResources(), defaultLayout);
537 }
538
Sunny Goyald3849d12015-10-29 10:28:32 -0700539 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800540 * The class is subclassed in tests to create an in-memory db.
541 */
Sunny Goyal19026b22018-03-09 14:37:37 -0800542 public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700543 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800544 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700545 private long mMaxItemId = -1;
546 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800547
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700548 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
549 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700550 // Table creation sometimes fails silently, which leads to a crash loop.
551 // This way, we will try to create a table every time after crash, so the device
552 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700553 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700554 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
555 // This operation is a no-op if the table already exists.
556 addFavoritesTable(getWritableDatabase(), true);
557 addWorkspacesTable(getWritableDatabase(), true);
558 }
559
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700560 initIds();
561 }
562
563 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700564 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700565 */
566 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700567 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal19026b22018-03-09 14:37:37 -0800568 super(context, tableName, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700569 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700570 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700571 }
572
573 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700574 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
575 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700576 if (mMaxItemId == -1) {
577 mMaxItemId = initializeMaxItemId(getWritableDatabase());
578 }
579 if (mMaxScreenId == -1) {
580 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700581 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 }
583
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700584 private boolean tableExists(String tableName) {
585 Cursor c = getReadableDatabase().query(
586 true, "sqlite_master", new String[] {"tbl_name"},
587 "tbl_name = ?", new String[] {tableName},
588 null, null, null, null, null);
589 try {
590 return c.getCount() > 0;
591 } finally {
592 c.close();
593 }
594 }
595
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 @Override
597 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800598 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700599
Adam Cohendcd297f2013-06-18 13:13:40 -0700600 mMaxItemId = 1;
601 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700602
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700603 addFavoritesTable(db, false);
604 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800606 // Fresh and clean launcher DB.
607 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800608 onEmptyDbCreated();
609 }
610
611 /**
612 * Overriden in tests.
613 */
614 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700615 // Database was just created, so wipe any previous widgets
616 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700617 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700618 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530619 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700620 }
621
Sunny Goyalf076eae2016-01-11 12:25:10 -0800622 // Set the flag for empty DB
623 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800624 }
625
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700626 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800627 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800628 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 }
630
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700631 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700632 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700633 }
634
635 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
636 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700637 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800638 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400639 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
640 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700641 ");");
642 }
643
Adam Cohen119285e2014-04-02 16:59:08 -0700644 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700645 // Delete items directly on the workspace who's screen id doesn't exist
646 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
647 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700648 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700649 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700650 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700651 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700652 " AND " +
653 LauncherSettings.Favorites.CONTAINER + " = " +
654 LauncherSettings.Favorites.CONTAINER_DESKTOP;
655 db.execSQL(removeOrphanedDesktopItems);
656
657 // Delete items contained in folders which no longer exist (after above statement)
658 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
659 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700660 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700661 " WHERE " +
662 LauncherSettings.Favorites.CONTAINER + " <> " +
663 LauncherSettings.Favorites.CONTAINER_DESKTOP +
664 " AND "
665 + LauncherSettings.Favorites.CONTAINER + " <> " +
666 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
667 " AND "
668 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700669 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700670 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
671 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
672 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700673 }
674
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800675 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700676 public void onOpen(SQLiteDatabase db) {
677 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700678
679 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
680 if (!schemaFile.exists()) {
681 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700682 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700683 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
684 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700685 }
686
687 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700688 * One-time data updated before support of onDowngrade was added. This update is backwards
689 * compatible and can safely be run multiple times.
690 * Note: No new logic should be added here after release, as the new logic might not get
691 * executed on an existing device.
692 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700693 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700694 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
695 // Remove "profile extra"
696 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
697 for (UserHandle user : um.getUserProfiles()) {
698 long serial = um.getSerialNumberForUser(user);
699 String sql = "update favorites set intent = replace(intent, "
700 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
701 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700702 }
703 }
704
705 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800706 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700707 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800708 switch (oldVersion) {
709 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800710 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800711 case 12: {
712 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
713 // to persist workspace screens and their relative order.
714 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700715 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800716 }
717 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700718 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800719 // Insert new column for holding widget provider name
720 db.execSQL("ALTER TABLE favorites " +
721 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700722 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800723 } catch (SQLException ex) {
724 Log.e(TAG, ex.getMessage(), ex);
725 // Old version remains, which means we wipe old data
726 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800727 }
728 }
729 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700730 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800731 // Insert new column for holding update timestamp
732 db.execSQL("ALTER TABLE favorites " +
733 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
734 db.execSQL("ALTER TABLE workspaceScreens " +
735 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700736 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 } catch (SQLException ex) {
738 Log.e(TAG, ex.getMessage(), ex);
739 // Old version remains, which means we wipe old data
740 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800741 }
742 }
743 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700744 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800745 // Old version remains, which means we wipe old data
746 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800747 }
748 }
749 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700750 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 }
752 case 17: {
753 // No-op
754 }
755 case 18: {
756 // Due to a data loss bug, some users may have items associated with screen ids
757 // which no longer exist. Since this can cause other problems, and since the user
758 // will never see these items anyway, we use database upgrade as an opportunity to
759 // clean things up.
760 removeOrphanedItems(db);
761 }
762 case 19: {
763 // Add userId column
764 if (!addProfileColumn(db)) {
765 // Old version remains, which means we wipe old data
766 break;
767 }
768 }
769 case 20:
770 if (!updateFolderItemsRank(db, true)) {
771 break;
772 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800773 case 21:
774 // Recreate workspace table with screen id a primary key
775 if (!recreateWorkspaceTable(db)) {
776 break;
777 }
778 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700779 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
780 // Old version remains, which means we wipe old data
781 break;
782 }
783 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700784 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700785 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700786 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000787 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700788 case 25:
789 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700790 case 26:
791 // QSB was moved to the grid. Clear the first row on screen 0.
792 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800793 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700794 break;
795 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700796 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800797 // DB Upgraded successfully
798 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400799 }
800
Sunny Goyala2cc6242015-01-14 14:23:02 -0800801 // DB was not upgraded
802 Log.w(TAG, "Destroying all old data.");
803 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800804 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800805
Adam Cohen9b1d0622014-05-21 19:01:57 -0700806 @Override
807 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700808 try {
809 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
810 .onDowngrade(db, oldVersion, newVersion);
811 } catch (Exception e) {
812 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
813 ". Wiping databse.", e);
814 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700815 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700816 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700817
Sunny Goyal42de82f2014-09-26 22:09:29 -0700818 /**
819 * Clears all the data for a fresh start.
820 */
821 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700822 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800823 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
824 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
825 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700826 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800827 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700828 }
829
Sunny Goyald2f38192015-02-25 10:46:34 -0800830 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700831 * Removes widgets which are registered to the Launcher's host, but are not present
832 * in our model.
833 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700834 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700835 public void removeGhostWidgets(SQLiteDatabase db) {
836 // Get all existing widget ids.
837 final AppWidgetHost host = newLauncherWidgetHost();
838 final int[] allWidgets;
839 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700840 // Although the method was defined in O, it has existed since the beginning of time,
841 // so it might work on older platforms as well.
842 allWidgets = host.getAppWidgetIds();
843 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700844 Log.e(TAG, "getAppWidgetIds not supported", e);
845 return;
846 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700847 final HashSet<Integer> validWidgets = new HashSet<>();
848 try (Cursor c = db.query(Favorites.TABLE_NAME,
849 new String[] {Favorites.APPWIDGET_ID },
850 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700851 while (c.moveToNext()) {
852 validWidgets.add(c.getInt(0));
853 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700854 } catch (SQLException ex) {
855 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700856 return;
857 }
858 for (int widgetId : allWidgets) {
859 if (!validWidgets.contains(widgetId)) {
860 try {
861 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
862 host.deleteAppWidgetId(widgetId);
863 } catch (RuntimeException e) {
864 // Ignore
865 }
866 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700867 }
868 }
869
870 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700871 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
872 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
873 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700874 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700875 try (SQLiteTransaction t = new SQLiteTransaction(db);
876 // Only consider the primary user as other users can't have a shortcut.
877 Cursor c = db.query(Favorites.TABLE_NAME,
878 new String[] { Favorites._ID, Favorites.INTENT},
879 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
880 " AND profileId=" + getDefaultUserSerial(),
881 null, null, null, null);
882 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
883 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
884 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700885 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
886 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
887
888 while (c.moveToNext()) {
889 String intentDescription = c.getString(intentIndex);
890 Intent intent;
891 try {
892 intent = Intent.parseUri(intentDescription, 0);
893 } catch (URISyntaxException e) {
894 Log.e(TAG, "Unable to parse intent", e);
895 continue;
896 }
897
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700898 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700899 continue;
900 }
901
902 long id = c.getLong(idIndex);
903 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700904 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700905 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700906 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700907 } catch (SQLException ex) {
908 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700909 }
910 }
911
912 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800913 * Recreates workspace table and migrates data to the new table.
914 */
915 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700916 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
917 final ArrayList<Long> sortedIDs;
918
919 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800920 new String[] {LauncherSettings.WorkspaceScreens._ID},
921 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700922 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
923 // Use LinkedHashSet so that ordering is preserved
924 sortedIDs = new ArrayList<>(
925 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800926 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700927 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700928 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800929
930 // Add all screen ids back
931 int total = sortedIDs.size();
932 for (int i = 0; i < total; i++) {
933 ContentValues values = new ContentValues();
934 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
935 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
936 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700937 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800938 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700939 t.commit();
940 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800941 } catch (SQLException ex) {
942 // Old version remains, which means we wipe old data
943 Log.e(TAG, ex.getMessage(), ex);
944 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800945 }
946 return true;
947 }
948
Adam Cohen091440a2015-03-18 14:16:05 -0700949 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700950 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800951 if (addRankColumn) {
952 // Insert new column for holding rank
953 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
954 }
955
956 // Get a map for folder ID to folder width
957 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
958 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
959 + " GROUP BY container;",
960 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
961
962 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800963 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
964 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800965 new Object[] {c.getLong(1) + 1, c.getLong(0)});
966 }
967
968 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700969 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800970 } catch (SQLException ex) {
971 // Old version remains, which means we wipe old data
972 Log.e(TAG, ex.getMessage(), ex);
973 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800974 }
975 return true;
976 }
977
Kenny Guyed131872014-04-30 03:02:21 +0100978 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700979 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700980 }
981
982 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700983 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700984 db.execSQL("ALTER TABLE favorites ADD COLUMN "
985 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700986 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100987 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100988 Log.e(TAG, ex.getMessage(), ex);
989 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100990 }
991 return true;
992 }
993
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700994 // Generates a new ID to use for an object in your database. This method should be only
995 // called from the main UI thread. As an exception, we do call it when we call the
996 // constructor from the worker thread; however, this doesn't extend until after the
997 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
998 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700999 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001000 public long generateNewItemId() {
1001 if (mMaxItemId < 0) {
1002 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001003 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001004 mMaxItemId += 1;
1005 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001006 }
1007
Sunny Goyal55fddc82017-04-06 15:02:52 -07001008 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001009 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001010 }
1011
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001012 @Override
1013 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001014 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001015 }
1016
Chris Wren5dee7af2013-12-20 17:22:11 -05001017 public void checkId(String table, ContentValues values) {
1018 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001019 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001020 mMaxScreenId = Math.max(id, mMaxScreenId);
1021 } else {
1022 mMaxItemId = Math.max(id, mMaxItemId);
1023 }
1024 }
1025
Adam Cohendcd297f2013-06-18 13:13:40 -07001026 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001027 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001028 }
1029
1030 // Generates a new ID to use for an workspace screen in your database. This method
1031 // should be only called from the main UI thread. As an exception, we do call it when we
1032 // call the constructor from the worker thread; however, this doesn't extend until after the
1033 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1034 // after that point
1035 public long generateNewScreenId() {
1036 if (mMaxScreenId < 0) {
1037 throw new RuntimeException("Error: max screen id was not initialized");
1038 }
1039 mMaxScreenId += 1;
1040 return mMaxScreenId;
1041 }
1042
Adam Cohendcd297f2013-06-18 13:13:40 -07001043 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001044 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001045 }
1046
Adam Cohen091440a2015-03-18 14:16:05 -07001047 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001048 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001049 // TODO: Use multiple loaders with fall-back and transaction.
1050 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001051
1052 // Add the screens specified by the items above
1053 Collections.sort(screenIds);
1054 int rank = 0;
1055 ContentValues values = new ContentValues();
1056 for (Long id : screenIds) {
1057 values.clear();
1058 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1059 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001060 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001061 throw new RuntimeException("Failed initialize screen table"
1062 + "from default layout");
1063 }
1064 rank++;
1065 }
1066
1067 // Ensure that the max ids are initialized
1068 mMaxItemId = initializeMaxItemId(db);
1069 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001070
Adam Cohen71483f42014-05-15 14:04:01 -07001071 return count;
1072 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001073 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001074
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001075 /**
1076 * @return the max _id in the provided table.
1077 */
Adam Cohen091440a2015-03-18 14:16:05 -07001078 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001079 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1080 // get the result
1081 long id = -1;
1082 if (c != null && c.moveToNext()) {
1083 id = c.getLong(0);
1084 }
1085 if (c != null) {
1086 c.close();
1087 }
1088
1089 if (id == -1) {
1090 throw new RuntimeException("Error: could not query max id in " + table);
1091 }
1092
1093 return id;
1094 }
1095
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001096 static class SqlArguments {
1097 public final String table;
1098 public final String where;
1099 public final String[] args;
1100
1101 SqlArguments(Uri url, String where, String[] args) {
1102 if (url.getPathSegments().size() == 1) {
1103 this.table = url.getPathSegments().get(0);
1104 this.where = where;
1105 this.args = args;
1106 } else if (url.getPathSegments().size() != 2) {
1107 throw new IllegalArgumentException("Invalid URI: " + url);
1108 } else if (!TextUtils.isEmpty(where)) {
1109 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1110 } else {
1111 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001112 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001113 this.args = null;
1114 }
1115 }
1116
1117 SqlArguments(Uri url) {
1118 if (url.getPathSegments().size() == 1) {
1119 table = url.getPathSegments().get(0);
1120 where = null;
1121 args = null;
1122 } else {
1123 throw new IllegalArgumentException("Invalid URI: " + url);
1124 }
1125 }
1126 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001127
1128 private static class ChangeListenerWrapper implements Handler.Callback {
1129
1130 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001131 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001132
1133 private LauncherProviderChangeListener mListener;
1134
1135 @Override
1136 public boolean handleMessage(Message msg) {
1137 if (mListener != null) {
1138 switch (msg.what) {
1139 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001140 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001141 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001142 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001143 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001144 break;
1145 }
1146 }
1147 return true;
1148 }
1149 }
Adam Cohen72960972014-01-15 18:13:55 -08001150}