blob: cf984c0a554a1d584d5cbc956f2cd7ca9548a943 [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;
37import android.database.sqlite.SQLiteOpenHelper;
38import android.database.sqlite.SQLiteQueryBuilder;
Sunny Goyal0b037782015-04-02 10:27:03 -070039import android.database.sqlite.SQLiteStatement;
Adam Cohen228da5a2011-07-27 22:23:47 -070040import android.net.Uri;
Sunny Goyal7779d622015-06-11 16:18:39 -070041import android.os.Binder;
Sunny Goyal22ca9ec2017-05-18 15:03:13 -070042import android.os.Build;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070043import android.os.Bundle;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070044import android.os.Handler;
45import android.os.Message;
Sunny Goyal7779d622015-06-11 16:18:39 -070046import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080047import android.os.UserHandle;
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070048import android.os.UserManager;
Adam Cohen228da5a2011-07-27 22:23:47 -070049import android.text.TextUtils;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050import android.util.Log;
Adam Cohen228da5a2011-07-27 22:23:47 -070051
Sunny Goyal0fe505b2014-08-06 09:55:36 -070052import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
53import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070054import com.android.launcher3.LauncherSettings.WorkspaceScreens;
Kenny Guyed131872014-04-30 03:02:21 +010055import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070056import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfdbef272017-02-01 12:52:54 -080057import com.android.launcher3.logging.FileLog;
Sunny Goyal05f30882017-05-03 12:42:18 -070058import com.android.launcher3.model.DbDowngradeHelper;
Sunny Goyala9e2f5a2016-06-10 12:22:04 -070059import com.android.launcher3.provider.LauncherDbUtils;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070060import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
Sunny Goyale8f7d5a2016-05-24 11:30:14 -070061import com.android.launcher3.provider.RestoreDbTask;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070062import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070063import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070064import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070065
Sunny Goyal05f30882017-05-03 12:42:18 -070066import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070069import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070070import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070071import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070072import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070073import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070076 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080077 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Sunny Goyal05f30882017-05-03 12:42:18 -070079 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
80
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070081 /**
82 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
83 */
Sunny Goyal05f30882017-05-03 12:42:18 -070084 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085
Sunny Goyal85525172017-11-06 13:00:42 -080086 public static final String AUTHORITY = FeatureFlags.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070087
Sunny Goyale87e6ab2014-11-21 22:42:53 -080088 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070090 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
91
Sunny Goyalb5b55c82016-05-10 12:28:59 -070092 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
93 private Handler mListenerHandler;
94
Sunny Goyalf076eae2016-01-11 12:25:10 -080095 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096
Hyunyoung Song6aa37292017-02-06 10:46:24 -080097 /**
98 * $ adb shell dumpsys activity provider com.android.launcher3
99 */
100 @Override
101 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
102 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
103 if (appState == null || !appState.getModel().isModelLoaded()) {
104 return;
105 }
106 appState.getModel().dumpState("", fd, writer, args);
107 }
108
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109 @Override
110 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800111 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700112 Log.d(TAG, "Launcher process started");
113 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700114 mListenerHandler = new Handler(mListenerWrapper);
115
Sunny Goyalfdbef272017-02-01 12:52:54 -0800116 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800117 // is the first component to get created.
118 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119 return true;
120 }
121
Sunny Goyald3849d12015-10-29 10:28:32 -0700122 /**
123 * Sets a provider listener.
124 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700125 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700126 Preconditions.assertUIThread();
127 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700128 }
129
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800130 @Override
131 public String getType(Uri uri) {
132 SqlArguments args = new SqlArguments(uri, null, null);
133 if (TextUtils.isEmpty(args.where)) {
134 return "vnd.android.cursor.dir/" + args.table;
135 } else {
136 return "vnd.android.cursor.item/" + args.table;
137 }
138 }
139
Sunny Goyalf076eae2016-01-11 12:25:10 -0800140 /**
141 * Overridden in tests
142 */
143 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700144 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700145 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700146
147 if (RestoreDbTask.isPending(getContext())) {
148 if (!RestoreDbTask.performRestore(mOpenHelper)) {
149 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
150 }
151 // Set is pending to false irrespective of the result, so that it doesn't get
152 // executed again.
153 RestoreDbTask.setPending(getContext(), false);
154 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700155 }
156 }
157
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800158 @Override
159 public Cursor query(Uri uri, String[] projection, String selection,
160 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700161 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800162
163 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
164 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
165 qb.setTables(args.table);
166
Romain Guy73b979d2009-06-09 12:57:21 -0700167 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800168 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
169 result.setNotificationUri(getContext().getContentResolver(), uri);
170
171 return result;
172 }
173
Adam Cohen091440a2015-03-18 14:16:05 -0700174 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700175 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500176 if (values == null) {
177 throw new RuntimeException("Error: attempting to insert null values");
178 }
Adam Cohen71483f42014-05-15 14:04:01 -0700179 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700180 throw new RuntimeException("Error: attempting to add item without specifying an id");
181 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500182 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700183 return db.insert(table, nullColumnHack, values);
184 }
185
Sunny Goyald1064182015-08-13 12:08:30 -0700186 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700187 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700188 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
189 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800190 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700191 }
192 }
193 }
194
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 @Override
196 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700197 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198 SqlArguments args = new SqlArguments(uri);
199
Sunny Goyald1064182015-08-13 12:08:30 -0700200 // In very limited cases, we support system|signature permission apps to modify the db.
201 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700202 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700203 return null;
204 }
205 }
206
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800207 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400208 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700209 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800210 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211
212 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700213 notifyListeners();
214
Sunny Goyalc74e4192015-09-08 14:01:03 -0700215 if (Utilities.ATLEAST_MARSHMALLOW) {
216 reloadLauncherIfExternal();
217 } else {
218 // Deprecated behavior to support legacy devices which rely on provider callbacks.
219 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
220 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800221 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700222 }
223
224 String notify = uri.getQueryParameter("notify");
225 if (notify == null || "true".equals(notify)) {
226 getContext().getContentResolver().notifyChange(uri, null);
227 }
228 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 return uri;
230 }
231
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700232 private boolean initializeExternalAdd(ContentValues values) {
233 // 1. Ensure that externally added items have a valid item id
234 long id = mOpenHelper.generateNewItemId();
235 values.put(LauncherSettings.Favorites._ID, id);
236
237 // 2. In the case of an app widget, and if no app widget id is specified, we
238 // attempt allocate and bind the widget.
239 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
240 if (itemType != null &&
241 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
242 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
243
244 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
245 ComponentName cn = ComponentName.unflattenFromString(
246 values.getAsString(Favorites.APPWIDGET_PROVIDER));
247
248 if (cn != null) {
249 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700250 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
251 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700252 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
253 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700254 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700255 return false;
256 }
257 } catch (RuntimeException e) {
258 Log.e(TAG, "Failed to initialize external widget", e);
259 return false;
260 }
261 } else {
262 return false;
263 }
264 }
265
266 // Add screen id if not present
267 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
268 SQLiteStatement stmp = null;
269 try {
270 stmp = mOpenHelper.getWritableDatabase().compileStatement(
271 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
272 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
273 stmp.bindLong(1, screenId);
274
275 ContentValues valuesInserted = new ContentValues();
276 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
277 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
278 return true;
279 } catch (Exception e) {
280 return false;
281 } finally {
282 Utilities.closeSilently(stmp);
283 }
284 }
285
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800286 @Override
287 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700288 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800289 SqlArguments args = new SqlArguments(uri);
290
291 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700292 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800293 int numValues = values.length;
294 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400295 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700296 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
297 return 0;
298 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800299 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700300 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800301 }
302
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700303 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700304 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800305 return values.length;
306 }
307
308 @Override
Yura085c8532014-02-11 15:15:29 +0000309 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
310 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700311 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700312 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000313 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700314 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700315 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000316 return result;
Yura085c8532014-02-11 15:15:29 +0000317 }
318 }
319
320 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800321 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700322 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800323 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
324
325 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800326
Louis Begina9c21c62016-08-15 15:18:41 -0700327 if (Binder.getCallingPid() != Process.myPid()
328 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700329 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700330 }
331 int count = db.delete(args.table, args.where, args.args);
332 if (count > 0) {
333 notifyListeners();
334 reloadLauncherIfExternal();
335 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336 return count;
337 }
338
339 @Override
340 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700341 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
343
Chris Wren1ada10d2013-09-13 18:01:38 -0400344 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
346 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700347 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800348
Sunny Goyald1064182015-08-13 12:08:30 -0700349 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 return count;
351 }
352
Sunny Goyal7779d622015-06-11 16:18:39 -0700353 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700354 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700355 if (Binder.getCallingUid() != Process.myUid()) {
356 return null;
357 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700358 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700359
360 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700361 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
362 clearFlagEmptyDbCreated();
363 return null;
364 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700365 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
366 Bundle result = new Bundle();
367 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
368 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
369 return result;
370 }
Sunny Goyald2497482015-09-22 18:24:19 -0700371 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
372 Bundle result = new Bundle();
373 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
374 return result;
375 }
376 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
377 Bundle result = new Bundle();
378 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
379 return result;
380 }
381 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
382 Bundle result = new Bundle();
383 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
384 return result;
385 }
386 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800387 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700388 return null;
389 }
390 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
391 loadDefaultFavoritesIfNecessary();
392 return null;
393 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700394 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
395 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
396 return null;
397 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700398 }
399 return null;
400 }
401
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700402 /**
403 * Deletes any empty folder from the DB.
404 * @return Ids of deleted folders.
405 */
Sunny Goyald2497482015-09-22 18:24:19 -0700406 private ArrayList<Long> deleteEmptyFolders() {
407 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700408 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700409 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700410 // Select folders whose id do not match any container value.
411 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
412 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
413 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
414 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700415 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700416 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700417 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700418 selection, null, null, null, null)) {
419 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700420 }
Sunny Goyald2497482015-09-22 18:24:19 -0700421 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700422 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700423 LauncherSettings.Favorites._ID, folderIds), null);
424 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700425 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700426 } catch (SQLException ex) {
427 Log.e(TAG, ex.getMessage(), ex);
428 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700429 }
430 return folderIds;
431 }
432
Sunny Goyalf076eae2016-01-11 12:25:10 -0800433 /**
434 * Overridden in tests
435 */
436 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700437 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400438 }
439
Adam Cohen091440a2015-03-18 14:16:05 -0700440 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400441 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800442 }
443
Sunny Goyald2497482015-09-22 18:24:19 -0700444 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700445 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700446 }
447
Sunny Goyal42de82f2014-09-26 22:09:29 -0700448 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700449 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700450 * 1) From the app restrictions
451 * 2) From a package provided by play store
452 * 3) From a partner configuration APK, already in the system image
453 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700454 */
Sunny Goyald2497482015-09-22 18:24:19 -0700455 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700456 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700457
Winson Chungc763c4e2013-07-19 13:49:06 -0700458 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500459 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200460
Sunny Goyal55fddc82017-04-06 15:02:52 -0700461 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700462 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700463 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700464 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700465 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700466 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700467 final Partner partner = Partner.get(getContext().getPackageManager());
468 if (partner != null && partner.hasDefaultLayout()) {
469 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700470 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700471 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700472 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700473 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700474 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700475 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700476 }
477 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700478
Sunny Goyal9d219682014-10-23 14:21:02 -0700479 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700480 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700481 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700482 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800483
484 // There might be some partially restored DB items, due to buggy restore logic in
485 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800486 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700487 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700488 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
489 && usingExternallyProvidedLayout) {
490 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800491 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700492 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700493 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700494 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700495 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700496 }
497 }
498
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700499 /**
500 * Creates workspace loader from an XML resource listed in the app restrictions.
501 *
502 * @return the loader if the restrictions are set and the resource exists; null otherwise.
503 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700504 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700505 Context ctx = getContext();
506 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
507 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700508 if (bundle == null) {
509 return null;
510 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700511
Sunny Goyal35ca8732015-04-06 10:45:31 -0700512 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700513 if (packageName != null) {
514 try {
515 Resources targetResources = ctx.getPackageManager()
516 .getResourcesForApplication(packageName);
517 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700518 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700519 } catch (NameNotFoundException e) {
520 Log.e(TAG, "Target package for restricted profile not found", e);
521 return null;
522 }
523 }
524 return null;
525 }
526
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700527 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700528 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
529 int defaultLayout = idp.defaultLayoutId;
530
531 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
532 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
533 defaultLayout = idp.demoModeLayoutId;
534 }
535
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700536 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700537 mOpenHelper, getContext().getResources(), defaultLayout);
538 }
539
Sunny Goyald3849d12015-10-29 10:28:32 -0700540 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800541 * The class is subclassed in tests to create an in-memory db.
542 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700543 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700544 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800545 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700546 private long mMaxItemId = -1;
547 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800548
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700549 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
550 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700551 // Table creation sometimes fails silently, which leads to a crash loop.
552 // This way, we will try to create a table every time after crash, so the device
553 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700554 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700555 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
556 // This operation is a no-op if the table already exists.
557 addFavoritesTable(getWritableDatabase(), true);
558 addWorkspacesTable(getWritableDatabase(), true);
559 }
560
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700561 initIds();
562 }
563
564 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700565 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700566 */
567 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700568 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700569 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700570 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700571 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700572 }
573
574 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700575 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
576 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700577 if (mMaxItemId == -1) {
578 mMaxItemId = initializeMaxItemId(getWritableDatabase());
579 }
580 if (mMaxScreenId == -1) {
581 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700582 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800583 }
584
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700585 private boolean tableExists(String tableName) {
586 Cursor c = getReadableDatabase().query(
587 true, "sqlite_master", new String[] {"tbl_name"},
588 "tbl_name = ?", new String[] {tableName},
589 null, null, null, null, null);
590 try {
591 return c.getCount() > 0;
592 } finally {
593 c.close();
594 }
595 }
596
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 @Override
598 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800599 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700600
Adam Cohendcd297f2013-06-18 13:13:40 -0700601 mMaxItemId = 1;
602 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700603
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700604 addFavoritesTable(db, false);
605 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800607 // Fresh and clean launcher DB.
608 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800609 onEmptyDbCreated();
610 }
611
612 /**
613 * Overriden in tests.
614 */
615 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700616 // Database was just created, so wipe any previous widgets
617 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700618 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700619 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530620 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700621 }
622
Sunny Goyalf076eae2016-01-11 12:25:10 -0800623 // Set the flag for empty DB
624 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyalf076eae2016-01-11 12:25:10 -0800625 }
626
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700627 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800628 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800629 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 }
631
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700632 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700633 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700634 }
635
636 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
637 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700638 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800639 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400640 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
641 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700642 ");");
643 }
644
Adam Cohen119285e2014-04-02 16:59:08 -0700645 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700646 // Delete items directly on the workspace who's screen id doesn't exist
647 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
648 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700649 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700650 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700651 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700652 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700653 " AND " +
654 LauncherSettings.Favorites.CONTAINER + " = " +
655 LauncherSettings.Favorites.CONTAINER_DESKTOP;
656 db.execSQL(removeOrphanedDesktopItems);
657
658 // Delete items contained in folders which no longer exist (after above statement)
659 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
660 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700661 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700662 " WHERE " +
663 LauncherSettings.Favorites.CONTAINER + " <> " +
664 LauncherSettings.Favorites.CONTAINER_DESKTOP +
665 " AND "
666 + LauncherSettings.Favorites.CONTAINER + " <> " +
667 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
668 " AND "
669 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700670 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700671 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
672 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
673 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700674 }
675
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800676 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700677 public void onOpen(SQLiteDatabase db) {
678 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700679
680 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
681 if (!schemaFile.exists()) {
682 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700683 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700684 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
685 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700686 }
687
688 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700689 * One-time data updated before support of onDowngrade was added. This update is backwards
690 * compatible and can safely be run multiple times.
691 * Note: No new logic should be added here after release, as the new logic might not get
692 * executed on an existing device.
693 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700694 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700695 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
696 // Remove "profile extra"
697 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
698 for (UserHandle user : um.getUserProfiles()) {
699 long serial = um.getSerialNumberForUser(user);
700 String sql = "update favorites set intent = replace(intent, "
701 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
702 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700703 }
704 }
705
706 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700708 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800709 switch (oldVersion) {
710 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800711 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800712 case 12: {
713 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
714 // to persist workspace screens and their relative order.
715 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700716 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800717 }
718 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700719 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800720 // Insert new column for holding widget provider name
721 db.execSQL("ALTER TABLE favorites " +
722 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700723 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800724 } catch (SQLException ex) {
725 Log.e(TAG, ex.getMessage(), ex);
726 // Old version remains, which means we wipe old data
727 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800728 }
729 }
730 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700731 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800732 // Insert new column for holding update timestamp
733 db.execSQL("ALTER TABLE favorites " +
734 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
735 db.execSQL("ALTER TABLE workspaceScreens " +
736 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700737 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800738 } catch (SQLException ex) {
739 Log.e(TAG, ex.getMessage(), ex);
740 // Old version remains, which means we wipe old data
741 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800742 }
743 }
744 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700745 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800746 // Old version remains, which means we wipe old data
747 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800748 }
749 }
750 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700751 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800752 }
753 case 17: {
754 // No-op
755 }
756 case 18: {
757 // Due to a data loss bug, some users may have items associated with screen ids
758 // which no longer exist. Since this can cause other problems, and since the user
759 // will never see these items anyway, we use database upgrade as an opportunity to
760 // clean things up.
761 removeOrphanedItems(db);
762 }
763 case 19: {
764 // Add userId column
765 if (!addProfileColumn(db)) {
766 // Old version remains, which means we wipe old data
767 break;
768 }
769 }
770 case 20:
771 if (!updateFolderItemsRank(db, true)) {
772 break;
773 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800774 case 21:
775 // Recreate workspace table with screen id a primary key
776 if (!recreateWorkspaceTable(db)) {
777 break;
778 }
779 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700780 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
781 // Old version remains, which means we wipe old data
782 break;
783 }
784 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700785 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700786 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700787 case 24:
Tony Mak1b6826c2018-02-27 15:06:12 +0000788 // No-op
Sunny Goyal5c97f512015-05-19 16:03:28 -0700789 case 25:
790 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700791 case 26:
792 // QSB was moved to the grid. Clear the first row on screen 0.
793 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800794 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700795 break;
796 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700797 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800798 // DB Upgraded successfully
799 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400800 }
801
Sunny Goyala2cc6242015-01-14 14:23:02 -0800802 // DB was not upgraded
803 Log.w(TAG, "Destroying all old data.");
804 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800805 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800806
Adam Cohen9b1d0622014-05-21 19:01:57 -0700807 @Override
808 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700809 try {
810 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
811 .onDowngrade(db, oldVersion, newVersion);
812 } catch (Exception e) {
813 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
814 ". Wiping databse.", e);
815 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700816 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700817 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700818
Sunny Goyal42de82f2014-09-26 22:09:29 -0700819 /**
820 * Clears all the data for a fresh start.
821 */
822 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700823 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800824 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
825 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
826 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700827 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800828 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700829 }
830
Sunny Goyald2f38192015-02-25 10:46:34 -0800831 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700832 * Removes widgets which are registered to the Launcher's host, but are not present
833 * in our model.
834 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700835 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700836 public void removeGhostWidgets(SQLiteDatabase db) {
837 // Get all existing widget ids.
838 final AppWidgetHost host = newLauncherWidgetHost();
839 final int[] allWidgets;
840 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700841 // Although the method was defined in O, it has existed since the beginning of time,
842 // so it might work on older platforms as well.
843 allWidgets = host.getAppWidgetIds();
844 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700845 Log.e(TAG, "getAppWidgetIds not supported", e);
846 return;
847 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700848 final HashSet<Integer> validWidgets = new HashSet<>();
849 try (Cursor c = db.query(Favorites.TABLE_NAME,
850 new String[] {Favorites.APPWIDGET_ID },
851 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700852 while (c.moveToNext()) {
853 validWidgets.add(c.getInt(0));
854 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700855 } catch (SQLException ex) {
856 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700857 return;
858 }
859 for (int widgetId : allWidgets) {
860 if (!validWidgets.contains(widgetId)) {
861 try {
862 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
863 host.deleteAppWidgetId(widgetId);
864 } catch (RuntimeException e) {
865 // Ignore
866 }
867 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700868 }
869 }
870
871 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700872 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
873 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
874 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700875 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700876 try (SQLiteTransaction t = new SQLiteTransaction(db);
877 // Only consider the primary user as other users can't have a shortcut.
878 Cursor c = db.query(Favorites.TABLE_NAME,
879 new String[] { Favorites._ID, Favorites.INTENT},
880 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
881 " AND profileId=" + getDefaultUserSerial(),
882 null, null, null, null);
883 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
884 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
885 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700886 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
887 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
888
889 while (c.moveToNext()) {
890 String intentDescription = c.getString(intentIndex);
891 Intent intent;
892 try {
893 intent = Intent.parseUri(intentDescription, 0);
894 } catch (URISyntaxException e) {
895 Log.e(TAG, "Unable to parse intent", e);
896 continue;
897 }
898
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700899 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700900 continue;
901 }
902
903 long id = c.getLong(idIndex);
904 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700905 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700906 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700907 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700908 } catch (SQLException ex) {
909 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700910 }
911 }
912
913 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800914 * Recreates workspace table and migrates data to the new table.
915 */
916 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700917 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
918 final ArrayList<Long> sortedIDs;
919
920 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800921 new String[] {LauncherSettings.WorkspaceScreens._ID},
922 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700923 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
924 // Use LinkedHashSet so that ordering is preserved
925 sortedIDs = new ArrayList<>(
926 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800927 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700928 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700929 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800930
931 // Add all screen ids back
932 int total = sortedIDs.size();
933 for (int i = 0; i < total; i++) {
934 ContentValues values = new ContentValues();
935 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
936 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
937 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700938 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800939 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700940 t.commit();
941 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800942 } catch (SQLException ex) {
943 // Old version remains, which means we wipe old data
944 Log.e(TAG, ex.getMessage(), ex);
945 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800946 }
947 return true;
948 }
949
Adam Cohen091440a2015-03-18 14:16:05 -0700950 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700951 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800952 if (addRankColumn) {
953 // Insert new column for holding rank
954 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
955 }
956
957 // Get a map for folder ID to folder width
958 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
959 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
960 + " GROUP BY container;",
961 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
962
963 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800964 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
965 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800966 new Object[] {c.getLong(1) + 1, c.getLong(0)});
967 }
968
969 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700970 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800971 } catch (SQLException ex) {
972 // Old version remains, which means we wipe old data
973 Log.e(TAG, ex.getMessage(), ex);
974 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800975 }
976 return true;
977 }
978
Kenny Guyed131872014-04-30 03:02:21 +0100979 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700980 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700981 }
982
983 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700984 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700985 db.execSQL("ALTER TABLE favorites ADD COLUMN "
986 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700987 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100988 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100989 Log.e(TAG, ex.getMessage(), ex);
990 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100991 }
992 return true;
993 }
994
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700995 // Generates a new ID to use for an object in your database. This method should be only
996 // called from the main UI thread. As an exception, we do call it when we call the
997 // constructor from the worker thread; however, this doesn't extend until after the
998 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
999 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001000 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001001 public long generateNewItemId() {
1002 if (mMaxItemId < 0) {
1003 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001004 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001005 mMaxItemId += 1;
1006 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001007 }
1008
Sunny Goyal55fddc82017-04-06 15:02:52 -07001009 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001010 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001011 }
1012
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001013 @Override
1014 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001015 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001016 }
1017
Chris Wren5dee7af2013-12-20 17:22:11 -05001018 public void checkId(String table, ContentValues values) {
1019 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001020 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001021 mMaxScreenId = Math.max(id, mMaxScreenId);
1022 } else {
1023 mMaxItemId = Math.max(id, mMaxItemId);
1024 }
1025 }
1026
Adam Cohendcd297f2013-06-18 13:13:40 -07001027 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001028 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001029 }
1030
1031 // Generates a new ID to use for an workspace screen in your database. This method
1032 // should be only called from the main UI thread. As an exception, we do call it when we
1033 // call the constructor from the worker thread; however, this doesn't extend until after the
1034 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1035 // after that point
1036 public long generateNewScreenId() {
1037 if (mMaxScreenId < 0) {
1038 throw new RuntimeException("Error: max screen id was not initialized");
1039 }
1040 mMaxScreenId += 1;
1041 return mMaxScreenId;
1042 }
1043
Adam Cohendcd297f2013-06-18 13:13:40 -07001044 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001045 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001046 }
1047
Adam Cohen091440a2015-03-18 14:16:05 -07001048 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001049 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001050 // TODO: Use multiple loaders with fall-back and transaction.
1051 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001052
1053 // Add the screens specified by the items above
1054 Collections.sort(screenIds);
1055 int rank = 0;
1056 ContentValues values = new ContentValues();
1057 for (Long id : screenIds) {
1058 values.clear();
1059 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1060 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001061 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001062 throw new RuntimeException("Failed initialize screen table"
1063 + "from default layout");
1064 }
1065 rank++;
1066 }
1067
1068 // Ensure that the max ids are initialized
1069 mMaxItemId = initializeMaxItemId(db);
1070 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001071
Adam Cohen71483f42014-05-15 14:04:01 -07001072 return count;
1073 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001074 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001075
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001076 /**
1077 * @return the max _id in the provided table.
1078 */
Adam Cohen091440a2015-03-18 14:16:05 -07001079 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001080 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1081 // get the result
1082 long id = -1;
1083 if (c != null && c.moveToNext()) {
1084 id = c.getLong(0);
1085 }
1086 if (c != null) {
1087 c.close();
1088 }
1089
1090 if (id == -1) {
1091 throw new RuntimeException("Error: could not query max id in " + table);
1092 }
1093
1094 return id;
1095 }
1096
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001097 static class SqlArguments {
1098 public final String table;
1099 public final String where;
1100 public final String[] args;
1101
1102 SqlArguments(Uri url, String where, String[] args) {
1103 if (url.getPathSegments().size() == 1) {
1104 this.table = url.getPathSegments().get(0);
1105 this.where = where;
1106 this.args = args;
1107 } else if (url.getPathSegments().size() != 2) {
1108 throw new IllegalArgumentException("Invalid URI: " + url);
1109 } else if (!TextUtils.isEmpty(where)) {
1110 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1111 } else {
1112 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001113 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001114 this.args = null;
1115 }
1116 }
1117
1118 SqlArguments(Uri url) {
1119 if (url.getPathSegments().size() == 1) {
1120 table = url.getPathSegments().get(0);
1121 where = null;
1122 args = null;
1123 } else {
1124 throw new IllegalArgumentException("Invalid URI: " + url);
1125 }
1126 }
1127 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001128
1129 private static class ChangeListenerWrapper implements Handler.Callback {
1130
1131 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001132 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001133
1134 private LauncherProviderChangeListener mListener;
1135
1136 @Override
1137 public boolean handleMessage(Message msg) {
1138 if (mListener != null) {
1139 switch (msg.what) {
1140 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001141 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001142 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001143 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001144 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001145 break;
1146 }
1147 }
1148 return true;
1149 }
1150 }
Adam Cohen72960972014-01-15 18:13:55 -08001151}