blob: 138ea0f65012b3c8daebef6fdc7771d7614ce517 [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 Goyale2fba6c2015-05-12 10:39:59 -070062import com.android.launcher3.util.ManagedProfileHeuristic;
Sunny Goyalbf67f3b2016-03-15 15:30:11 -070063import com.android.launcher3.util.NoLocaleSqliteContext;
Sunny Goyalb5b55c82016-05-10 12:28:59 -070064import com.android.launcher3.util.Preconditions;
Adam Cohen091440a2015-03-18 14:16:05 -070065import com.android.launcher3.util.Thunk;
Michael Jurka8b805b12012-04-18 14:23:14 -070066
Sunny Goyal05f30882017-05-03 12:42:18 -070067import java.io.File;
Hyunyoung Song6aa37292017-02-06 10:46:24 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Mike Cleronb87bd162009-10-30 16:36:56 -070070import java.net.URISyntaxException;
Adam Cohen228da5a2011-07-27 22:23:47 -070071import java.util.ArrayList;
Adam Cohen71483f42014-05-15 14:04:01 -070072import java.util.Collections;
Sunny Goyal55fddc82017-04-06 15:02:52 -070073import java.util.HashSet;
Sunny Goyaldbfc9012017-04-17 16:58:36 -070074import java.util.LinkedHashSet;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076public class LauncherProvider extends ContentProvider {
Sunny Goyalc74e4192015-09-08 14:01:03 -070077 private static final String TAG = "LauncherProvider";
Joe Onoratoa30ce8e2009-11-11 08:16:49 -080078 private static final boolean LOGD = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Sunny Goyal05f30882017-05-03 12:42:18 -070080 private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
81
Sunny Goyal3c7d55b2017-04-13 12:01:47 -070082 /**
83 * Represents the schema of the database. Changes in scheme need not be backwards compatible.
84 */
Sunny Goyal05f30882017-05-03 12:42:18 -070085 public static final int SCHEMA_VERSION = 27;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
Sunny Goyal85525172017-11-06 13:00:42 -080087 public static final String AUTHORITY = FeatureFlags.AUTHORITY;
Winson Chung3d503fb2011-07-13 17:25:49 -070088
Sunny Goyale87e6ab2014-11-21 22:42:53 -080089 static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Sunny Goyalb2d46ce2015-03-26 11:32:11 -070091 private static final String RESTRICTION_PACKAGE_NAME = "workspace.configuration.package.name";
92
Sunny Goyalb5b55c82016-05-10 12:28:59 -070093 private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
94 private Handler mListenerHandler;
95
Sunny Goyalf076eae2016-01-11 12:25:10 -080096 protected DatabaseHelper mOpenHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
Hyunyoung Song6aa37292017-02-06 10:46:24 -080098 /**
99 * $ adb shell dumpsys activity provider com.android.launcher3
100 */
101 @Override
102 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
103 LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
104 if (appState == null || !appState.getModel().isModelLoaded()) {
105 return;
106 }
107 appState.getModel().dumpState("", fd, writer, args);
108 }
109
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110 @Override
111 public boolean onCreate() {
Sunny Goyal3d706ad2017-03-06 16:56:39 -0800112 if (FeatureFlags.IS_DOGFOOD_BUILD) {
Sunny Goyale26d1002016-06-20 14:52:14 -0700113 Log.d(TAG, "Launcher process started");
114 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700115 mListenerHandler = new Handler(mListenerWrapper);
116
Sunny Goyalfdbef272017-02-01 12:52:54 -0800117 // The content provider exists for the entire duration of the launcher main process and
Sunny Goyal66f2b352018-02-09 10:57:12 -0800118 // is the first component to get created.
119 MainProcessInitializer.initialize(getContext().getApplicationContext());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120 return true;
121 }
122
Sunny Goyald3849d12015-10-29 10:28:32 -0700123 /**
124 * Sets a provider listener.
125 */
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700126 public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700127 Preconditions.assertUIThread();
128 mListenerWrapper.mListener = listener;
Anjali Koppal67e7cae2014-03-13 12:14:12 -0700129 }
130
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131 @Override
132 public String getType(Uri uri) {
133 SqlArguments args = new SqlArguments(uri, null, null);
134 if (TextUtils.isEmpty(args.where)) {
135 return "vnd.android.cursor.dir/" + args.table;
136 } else {
137 return "vnd.android.cursor.item/" + args.table;
138 }
139 }
140
Sunny Goyalf076eae2016-01-11 12:25:10 -0800141 /**
142 * Overridden in tests
143 */
144 protected synchronized void createDbIfNotExists() {
Sunny Goyald3849d12015-10-29 10:28:32 -0700145 if (mOpenHelper == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700146 mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700147
148 if (RestoreDbTask.isPending(getContext())) {
149 if (!RestoreDbTask.performRestore(mOpenHelper)) {
150 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
151 }
152 // Set is pending to false irrespective of the result, so that it doesn't get
153 // executed again.
154 RestoreDbTask.setPending(getContext(), false);
155 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700156 }
157 }
158
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800159 @Override
160 public Cursor query(Uri uri, String[] projection, String selection,
161 String[] selectionArgs, String sortOrder) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700162 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163
164 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
165 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
166 qb.setTables(args.table);
167
Romain Guy73b979d2009-06-09 12:57:21 -0700168 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800169 Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
170 result.setNotificationUri(getContext().getContentResolver(), uri);
171
172 return result;
173 }
174
Adam Cohen091440a2015-03-18 14:16:05 -0700175 @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700176 SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
Dan Sandlerd5024042014-01-09 15:01:33 -0500177 if (values == null) {
178 throw new RuntimeException("Error: attempting to insert null values");
179 }
Adam Cohen71483f42014-05-15 14:04:01 -0700180 if (!values.containsKey(LauncherSettings.ChangeLogColumns._ID)) {
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700181 throw new RuntimeException("Error: attempting to add item without specifying an id");
182 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500183 helper.checkId(table, values);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700184 return db.insert(table, nullColumnHack, values);
185 }
186
Sunny Goyald1064182015-08-13 12:08:30 -0700187 private void reloadLauncherIfExternal() {
Sunny Goyalc74e4192015-09-08 14:01:03 -0700188 if (Utilities.ATLEAST_MARSHMALLOW && Binder.getCallingPid() != Process.myPid()) {
Sunny Goyald1064182015-08-13 12:08:30 -0700189 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
190 if (app != null) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800191 app.getModel().forceReload();
Sunny Goyald1064182015-08-13 12:08:30 -0700192 }
193 }
194 }
195
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800196 @Override
197 public Uri insert(Uri uri, ContentValues initialValues) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700198 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199 SqlArguments args = new SqlArguments(uri);
200
Sunny Goyald1064182015-08-13 12:08:30 -0700201 // In very limited cases, we support system|signature permission apps to modify the db.
202 if (Binder.getCallingPid() != Process.myPid()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700203 if (!initializeExternalAdd(initialValues)) {
Adam Cohena043fa82014-07-23 14:49:38 -0700204 return null;
205 }
206 }
207
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Chris Wren1ada10d2013-09-13 18:01:38 -0400209 addModifiedTime(initialValues);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700210 final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
Sunny Goyale72f3d52015-03-02 14:24:21 -0800211 if (rowId < 0) return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212
213 uri = ContentUris.withAppendedId(uri, rowId);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700214 notifyListeners();
215
Sunny Goyalc74e4192015-09-08 14:01:03 -0700216 if (Utilities.ATLEAST_MARSHMALLOW) {
217 reloadLauncherIfExternal();
218 } else {
219 // Deprecated behavior to support legacy devices which rely on provider callbacks.
220 LauncherAppState app = LauncherAppState.getInstanceNoCreate();
221 if (app != null && "true".equals(uri.getQueryParameter("isExternalAdd"))) {
Sunny Goyaldd96a5e2017-02-17 11:22:34 -0800222 app.getModel().forceReload();
Sunny Goyalc74e4192015-09-08 14:01:03 -0700223 }
224
225 String notify = uri.getQueryParameter("notify");
226 if (notify == null || "true".equals(notify)) {
227 getContext().getContentResolver().notifyChange(uri, null);
228 }
229 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800230 return uri;
231 }
232
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700233 private boolean initializeExternalAdd(ContentValues values) {
234 // 1. Ensure that externally added items have a valid item id
235 long id = mOpenHelper.generateNewItemId();
236 values.put(LauncherSettings.Favorites._ID, id);
237
238 // 2. In the case of an app widget, and if no app widget id is specified, we
239 // attempt allocate and bind the widget.
240 Integer itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
241 if (itemType != null &&
242 itemType.intValue() == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET &&
243 !values.containsKey(LauncherSettings.Favorites.APPWIDGET_ID)) {
244
245 final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getContext());
246 ComponentName cn = ComponentName.unflattenFromString(
247 values.getAsString(Favorites.APPWIDGET_PROVIDER));
248
249 if (cn != null) {
250 try {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700251 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
252 int appWidgetId = widgetHost.allocateAppWidgetId();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700253 values.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId);
254 if (!appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,cn)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700255 widgetHost.deleteAppWidgetId(appWidgetId);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700256 return false;
257 }
258 } catch (RuntimeException e) {
259 Log.e(TAG, "Failed to initialize external widget", e);
260 return false;
261 }
262 } else {
263 return false;
264 }
265 }
266
267 // Add screen id if not present
268 long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
269 SQLiteStatement stmp = null;
270 try {
271 stmp = mOpenHelper.getWritableDatabase().compileStatement(
272 "INSERT OR IGNORE INTO workspaceScreens (_id, screenRank) " +
273 "select ?, (ifnull(MAX(screenRank), -1)+1) from workspaceScreens");
274 stmp.bindLong(1, screenId);
275
276 ContentValues valuesInserted = new ContentValues();
277 valuesInserted.put(LauncherSettings.BaseLauncherColumns._ID, stmp.executeInsert());
278 mOpenHelper.checkId(WorkspaceScreens.TABLE_NAME, valuesInserted);
279 return true;
280 } catch (Exception e) {
281 return false;
282 } finally {
283 Utilities.closeSilently(stmp);
284 }
285 }
286
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 @Override
288 public int bulkInsert(Uri uri, ContentValues[] values) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700289 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800290 SqlArguments args = new SqlArguments(uri);
291
292 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700293 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800294 int numValues = values.length;
295 for (int i = 0; i < numValues; i++) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400296 addModifiedTime(values[i]);
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700297 if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
298 return 0;
299 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800300 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700301 t.commit();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 }
303
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700304 notifyListeners();
Sunny Goyald1064182015-08-13 12:08:30 -0700305 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800306 return values.length;
307 }
308
309 @Override
Yura085c8532014-02-11 15:15:29 +0000310 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
311 throws OperationApplicationException {
Sunny Goyald3849d12015-10-29 10:28:32 -0700312 createDbIfNotExists();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700313 try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
Yura085c8532014-02-11 15:15:29 +0000314 ContentProviderResult[] result = super.applyBatch(operations);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700315 t.commit();
Sunny Goyald1064182015-08-13 12:08:30 -0700316 reloadLauncherIfExternal();
Yura085c8532014-02-11 15:15:29 +0000317 return result;
Yura085c8532014-02-11 15:15:29 +0000318 }
319 }
320
321 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 public int delete(Uri uri, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700323 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
325
326 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327
Louis Begina9c21c62016-08-15 15:18:41 -0700328 if (Binder.getCallingPid() != Process.myPid()
329 && Favorites.TABLE_NAME.equalsIgnoreCase(args.table)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700330 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
Louis Begina9c21c62016-08-15 15:18:41 -0700331 }
332 int count = db.delete(args.table, args.where, args.args);
333 if (count > 0) {
334 notifyListeners();
335 reloadLauncherIfExternal();
336 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800337 return count;
338 }
339
340 @Override
341 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Sunny Goyald3849d12015-10-29 10:28:32 -0700342 createDbIfNotExists();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800343 SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
344
Chris Wren1ada10d2013-09-13 18:01:38 -0400345 addModifiedTime(values);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800346 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
347 int count = db.update(args.table, values, args.where, args.args);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700348 if (count > 0) notifyListeners();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800349
Sunny Goyald1064182015-08-13 12:08:30 -0700350 reloadLauncherIfExternal();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800351 return count;
352 }
353
Sunny Goyal7779d622015-06-11 16:18:39 -0700354 @Override
Tony Wickham827cef22016-03-17 15:39:39 -0700355 public Bundle call(String method, final String arg, final Bundle extras) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700356 if (Binder.getCallingUid() != Process.myUid()) {
357 return null;
358 }
Sunny Goyald3849d12015-10-29 10:28:32 -0700359 createDbIfNotExists();
Sunny Goyal7779d622015-06-11 16:18:39 -0700360
361 switch (method) {
Sunny Goyald2497482015-09-22 18:24:19 -0700362 case LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG: {
363 clearFlagEmptyDbCreated();
364 return null;
365 }
Sunny Goyala5c8a9e2016-07-08 08:32:44 -0700366 case LauncherSettings.Settings.METHOD_WAS_EMPTY_DB_CREATED : {
367 Bundle result = new Bundle();
368 result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
369 Utilities.getPrefs(getContext()).getBoolean(EMPTY_DATABASE_CREATED, false));
370 return result;
371 }
Sunny Goyald2497482015-09-22 18:24:19 -0700372 case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
373 Bundle result = new Bundle();
374 result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
375 return result;
376 }
377 case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
378 Bundle result = new Bundle();
379 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
380 return result;
381 }
382 case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
383 Bundle result = new Bundle();
384 result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
385 return result;
386 }
387 case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800388 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyald2497482015-09-22 18:24:19 -0700389 return null;
390 }
391 case LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES: {
392 loadDefaultFavoritesIfNecessary();
393 return null;
394 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700395 case LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS: {
396 mOpenHelper.removeGhostWidgets(mOpenHelper.getWritableDatabase());
397 return null;
398 }
Sunny Goyal7779d622015-06-11 16:18:39 -0700399 }
400 return null;
401 }
402
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700403 /**
404 * Deletes any empty folder from the DB.
405 * @return Ids of deleted folders.
406 */
Sunny Goyald2497482015-09-22 18:24:19 -0700407 private ArrayList<Long> deleteEmptyFolders() {
408 ArrayList<Long> folderIds = new ArrayList<>();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700409 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700410 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700411 // Select folders whose id do not match any container value.
412 String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
413 + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
414 + LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
415 LauncherSettings.Favorites.CONTAINER + " FROM "
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700416 + Favorites.TABLE_NAME + ")";
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700417 try (Cursor c = db.query(Favorites.TABLE_NAME,
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700418 new String[] {LauncherSettings.Favorites._ID},
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700419 selection, null, null, null, null)) {
420 LauncherDbUtils.iterateCursor(c, 0, folderIds);
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700421 }
Sunny Goyald2497482015-09-22 18:24:19 -0700422 if (!folderIds.isEmpty()) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700423 db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700424 LauncherSettings.Favorites._ID, folderIds), null);
425 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700426 t.commit();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700427 } catch (SQLException ex) {
428 Log.e(TAG, ex.getMessage(), ex);
429 folderIds.clear();
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700430 }
431 return folderIds;
432 }
433
Sunny Goyalf076eae2016-01-11 12:25:10 -0800434 /**
435 * Overridden in tests
436 */
437 protected void notifyListeners() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700438 mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400439 }
440
Adam Cohen091440a2015-03-18 14:16:05 -0700441 @Thunk static void addModifiedTime(ContentValues values) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400442 values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800443 }
444
Sunny Goyald2497482015-09-22 18:24:19 -0700445 private void clearFlagEmptyDbCreated() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700446 Utilities.getPrefs(getContext()).edit().remove(EMPTY_DATABASE_CREATED).commit();
Sunny Goyal33d44382014-10-16 09:24:19 -0700447 }
448
Sunny Goyal42de82f2014-09-26 22:09:29 -0700449 /**
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700450 * Loads the default workspace based on the following priority scheme:
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700451 * 1) From the app restrictions
452 * 2) From a package provided by play store
453 * 3) From a partner configuration APK, already in the system image
454 * 4) The default configuration for the particular device
Brian Muramatsu5524b492012-10-02 16:55:54 -0700455 */
Sunny Goyald2497482015-09-22 18:24:19 -0700456 synchronized private void loadDefaultFavoritesIfNecessary() {
Sunny Goyalf7258242015-10-19 16:59:07 -0700457 SharedPreferences sp = Utilities.getPrefs(getContext());
Adam Cohene25af792013-06-06 23:08:25 -0700458
Winson Chungc763c4e2013-07-19 13:49:06 -0700459 if (sp.getBoolean(EMPTY_DATABASE_CREATED, false)) {
Chris Wren5dee7af2013-12-20 17:22:11 -0500460 Log.d(TAG, "loading default workspace");
Michael Jurka45355c42012-10-08 13:21:35 +0200461
Sunny Goyal55fddc82017-04-06 15:02:52 -0700462 AppWidgetHost widgetHost = mOpenHelper.newLauncherWidgetHost();
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700463 AutoInstallsLayout loader = createWorkspaceLoaderFromAppRestriction(widgetHost);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700464 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700465 loader = AutoInstallsLayout.get(getContext(),widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700466 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700467 if (loader == null) {
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700468 final Partner partner = Partner.get(getContext().getPackageManager());
469 if (partner != null && partner.hasDefaultLayout()) {
470 final Resources partnerRes = partner.getResources();
Adam Cohen4ae96ce2014-08-29 15:05:48 -0700471 int workspaceResId = partnerRes.getIdentifier(Partner.RES_DEFAULT_LAYOUT,
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700472 "xml", partner.getPackageName());
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700473 if (workspaceResId != 0) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700474 loader = new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal3a5a9d12014-10-01 15:33:41 -0700475 mOpenHelper, partnerRes, workspaceResId);
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700476 }
Adam Cohen9b8f51f2014-05-30 15:34:09 -0700477 }
478 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700479
Sunny Goyal9d219682014-10-23 14:21:02 -0700480 final boolean usingExternallyProvidedLayout = loader != null;
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481 if (loader == null) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700482 loader = getDefaultLayoutParser(widgetHost);
Brian Muramatsu5524b492012-10-02 16:55:54 -0700483 }
Sunny Goyalc6c8fef2015-03-04 09:51:18 -0800484
485 // There might be some partially restored DB items, due to buggy restore logic in
486 // previous versions of launcher.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800487 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Michael Jurkab85f8a42012-04-25 15:48:32 -0700488 // Populate favorites table with initial favorites
Sunny Goyal9d219682014-10-23 14:21:02 -0700489 if ((mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(), loader) <= 0)
490 && usingExternallyProvidedLayout) {
491 // Unable to load external layout. Cleanup and load the internal layout.
Sunny Goyale05b08f2017-02-23 18:30:22 -0800492 mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
Sunny Goyal9d219682014-10-23 14:21:02 -0700493 mOpenHelper.loadFavorites(mOpenHelper.getWritableDatabase(),
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700494 getDefaultLayoutParser(widgetHost));
Sunny Goyal9d219682014-10-23 14:21:02 -0700495 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700496 clearFlagEmptyDbCreated();
Michael Jurkab85f8a42012-04-25 15:48:32 -0700497 }
498 }
499
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700500 /**
501 * Creates workspace loader from an XML resource listed in the app restrictions.
502 *
503 * @return the loader if the restrictions are set and the resource exists; null otherwise.
504 */
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700505 private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700506 Context ctx = getContext();
507 UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
508 Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
Sunny Goyal35ca8732015-04-06 10:45:31 -0700509 if (bundle == null) {
510 return null;
511 }
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700512
Sunny Goyal35ca8732015-04-06 10:45:31 -0700513 String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700514 if (packageName != null) {
515 try {
516 Resources targetResources = ctx.getPackageManager()
517 .getResourcesForApplication(packageName);
518 return AutoInstallsLayout.get(ctx, packageName, targetResources,
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700519 widgetHost, mOpenHelper);
Sunny Goyalb2d46ce2015-03-26 11:32:11 -0700520 } catch (NameNotFoundException e) {
521 Log.e(TAG, "Target package for restricted profile not found", e);
522 return null;
523 }
524 }
525 return null;
526 }
527
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700528 private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
Adam Cohen27824492017-09-22 17:10:55 -0700529 InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
530 int defaultLayout = idp.defaultLayoutId;
531
532 UserManagerCompat um = UserManagerCompat.getInstance(getContext());
533 if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
534 defaultLayout = idp.demoModeLayoutId;
535 }
536
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700537 return new DefaultLayoutParser(getContext(), widgetHost,
Sunny Goyal9d219682014-10-23 14:21:02 -0700538 mOpenHelper, getContext().getResources(), defaultLayout);
539 }
540
Sunny Goyald3849d12015-10-29 10:28:32 -0700541 /**
Sunny Goyalf076eae2016-01-11 12:25:10 -0800542 * The class is subclassed in tests to create an in-memory db.
543 */
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700544 public static class DatabaseHelper extends SQLiteOpenHelper implements LayoutParserCallback {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700545 private final Handler mWidgetHostResetHandler;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800546 private final Context mContext;
Adam Cohendcd297f2013-06-18 13:13:40 -0700547 private long mMaxItemId = -1;
548 private long mMaxScreenId = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800549
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700550 DatabaseHelper(Context context, Handler widgetHostResetHandler) {
551 this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700552 // Table creation sometimes fails silently, which leads to a crash loop.
553 // This way, we will try to create a table every time after crash, so the device
554 // would eventually be able to recover.
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700555 if (!tableExists(Favorites.TABLE_NAME) || !tableExists(WorkspaceScreens.TABLE_NAME)) {
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700556 Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
557 // This operation is a no-op if the table already exists.
558 addFavoritesTable(getWritableDatabase(), true);
559 addWorkspacesTable(getWritableDatabase(), true);
560 }
561
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700562 initIds();
563 }
564
565 /**
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700566 * Constructor used in tests and for restore.
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700567 */
568 public DatabaseHelper(
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700569 Context context, Handler widgetHostResetHandler, String tableName) {
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700570 super(new NoLocaleSqliteContext(context), tableName, null, SCHEMA_VERSION);
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700571 mContext = context;
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700572 mWidgetHostResetHandler = widgetHostResetHandler;
Sunny Goyal7eab3cc2016-03-18 17:42:55 -0700573 }
574
575 protected void initIds() {
Winson Chung3d503fb2011-07-13 17:25:49 -0700576 // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from
577 // the DB here
Adam Cohendcd297f2013-06-18 13:13:40 -0700578 if (mMaxItemId == -1) {
579 mMaxItemId = initializeMaxItemId(getWritableDatabase());
580 }
581 if (mMaxScreenId == -1) {
582 mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
Winson Chung3d503fb2011-07-13 17:25:49 -0700583 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800584 }
585
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700586 private boolean tableExists(String tableName) {
587 Cursor c = getReadableDatabase().query(
588 true, "sqlite_master", new String[] {"tbl_name"},
589 "tbl_name = ?", new String[] {tableName},
590 null, null, null, null, null);
591 try {
592 return c.getCount() > 0;
593 } finally {
594 c.close();
595 }
596 }
597
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800598 @Override
599 public void onCreate(SQLiteDatabase db) {
Joe Onoratoa30ce8e2009-11-11 08:16:49 -0800600 if (LOGD) Log.d(TAG, "creating new launcher database");
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700601
Adam Cohendcd297f2013-06-18 13:13:40 -0700602 mMaxItemId = 1;
603 mMaxScreenId = 0;
Michael Jurkaa8c760d2011-04-28 14:59:33 -0700604
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700605 addFavoritesTable(db, false);
606 addWorkspacesTable(db, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800608 // Fresh and clean launcher DB.
609 mMaxItemId = initializeMaxItemId(db);
Sunny Goyalf076eae2016-01-11 12:25:10 -0800610 onEmptyDbCreated();
611 }
612
613 /**
614 * Overriden in tests.
615 */
616 protected void onEmptyDbCreated() {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700617 // Database was just created, so wipe any previous widgets
618 if (mWidgetHostResetHandler != null) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700619 newLauncherWidgetHost().deleteHost();
Sunny Goyal2e013ea2016-10-07 16:17:19 -0700620 mWidgetHostResetHandler.sendEmptyMessage(
Sunny Goyal72db9af2016-11-29 07:25:49 +0530621 ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700622 }
623
Sunny Goyalf076eae2016-01-11 12:25:10 -0800624 // Set the flag for empty DB
625 Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700626
627 // When a new DB is created, remove all previously stored managed profile information.
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800628 ManagedProfileHeuristic.processAllUsers(Collections.<UserHandle>emptyList(),
Sunny Goyalf076eae2016-01-11 12:25:10 -0800629 mContext);
630 }
631
Sunny Goyale8f7d5a2016-05-24 11:30:14 -0700632 public long getDefaultUserSerial() {
Sunny Goyalf076eae2016-01-11 12:25:10 -0800633 return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800634 Process.myUserHandle());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 }
636
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700637 private void addFavoritesTable(SQLiteDatabase db, boolean optional) {
Sunny Goyalc190dbf2016-05-05 14:37:05 -0700638 Favorites.addTableToDb(db, getDefaultUserSerial(), optional);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700639 }
640
641 private void addWorkspacesTable(SQLiteDatabase db, boolean optional) {
642 String ifNotExists = optional ? " IF NOT EXISTS " : "";
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700643 db.execSQL("CREATE TABLE " + ifNotExists + WorkspaceScreens.TABLE_NAME + " (" +
Sunny Goyald2f38192015-02-25 10:46:34 -0800644 LauncherSettings.WorkspaceScreens._ID + " INTEGER PRIMARY KEY," +
Chris Wren1ada10d2013-09-13 18:01:38 -0400645 LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
646 LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
Adam Cohendcd297f2013-06-18 13:13:40 -0700647 ");");
648 }
649
Adam Cohen119285e2014-04-02 16:59:08 -0700650 private void removeOrphanedItems(SQLiteDatabase db) {
Adam Cohenf9c14de2014-04-17 18:20:45 -0700651 // Delete items directly on the workspace who's screen id doesn't exist
652 // "DELETE FROM favorites WHERE screen NOT IN (SELECT _id FROM workspaceScreens)
653 // AND container = -100"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700654 String removeOrphanedDesktopItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700655 " WHERE " +
Adam Cohen119285e2014-04-02 16:59:08 -0700656 LauncherSettings.Favorites.SCREEN + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700657 LauncherSettings.WorkspaceScreens._ID + " FROM " + WorkspaceScreens.TABLE_NAME + ")" +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700658 " AND " +
659 LauncherSettings.Favorites.CONTAINER + " = " +
660 LauncherSettings.Favorites.CONTAINER_DESKTOP;
661 db.execSQL(removeOrphanedDesktopItems);
662
663 // Delete items contained in folders which no longer exist (after above statement)
664 // "DELETE FROM favorites WHERE container <> -100 AND container <> -101 AND container
665 // NOT IN (SELECT _id FROM favorites WHERE itemType = 2)"
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700666 String removeOrphanedFolderItems = "DELETE FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700667 " WHERE " +
668 LauncherSettings.Favorites.CONTAINER + " <> " +
669 LauncherSettings.Favorites.CONTAINER_DESKTOP +
670 " AND "
671 + LauncherSettings.Favorites.CONTAINER + " <> " +
672 LauncherSettings.Favorites.CONTAINER_HOTSEAT +
673 " AND "
674 + LauncherSettings.Favorites.CONTAINER + " NOT IN (SELECT " +
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700675 LauncherSettings.Favorites._ID + " FROM " + Favorites.TABLE_NAME +
Adam Cohenf9c14de2014-04-17 18:20:45 -0700676 " WHERE " + LauncherSettings.Favorites.ITEM_TYPE + " = " +
677 LauncherSettings.Favorites.ITEM_TYPE_FOLDER + ")";
678 db.execSQL(removeOrphanedFolderItems);
Adam Cohen119285e2014-04-02 16:59:08 -0700679 }
680
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 @Override
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700682 public void onOpen(SQLiteDatabase db) {
683 super.onOpen(db);
Sunny Goyal05f30882017-05-03 12:42:18 -0700684
685 File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
686 if (!schemaFile.exists()) {
687 handleOneTimeDataUpgrade(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700688 }
Sunny Goyal05f30882017-05-03 12:42:18 -0700689 DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
690 R.raw.downgrade_schema);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700691 }
692
693 /**
Sunny Goyal05f30882017-05-03 12:42:18 -0700694 * One-time data updated before support of onDowngrade was added. This update is backwards
695 * compatible and can safely be run multiple times.
696 * Note: No new logic should be added here after release, as the new logic might not get
697 * executed on an existing device.
698 * TODO: Move this to db upgrade path, once the downgrade path is released.
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700699 */
Sunny Goyal05f30882017-05-03 12:42:18 -0700700 protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
701 // Remove "profile extra"
702 UserManagerCompat um = UserManagerCompat.getInstance(mContext);
703 for (UserHandle user : um.getUserProfiles()) {
704 long serial = um.getSerialNumberForUser(user);
705 String sql = "update favorites set intent = replace(intent, "
706 + "';l.profile=" + serial + ";', ';') where itemType = 0;";
707 db.execSQL(sql);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700708 }
709 }
710
711 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800712 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700713 if (LOGD) Log.d(TAG, "onUpgrade triggered: " + oldVersion);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800714 switch (oldVersion) {
715 // The version cannot be lower that 12, as Launcher3 never supported a lower
Sunny Goyale87e6ab2014-11-21 22:42:53 -0800716 // version of the DB.
Sunny Goyala2cc6242015-01-14 14:23:02 -0800717 case 12: {
718 // With the new shrink-wrapped and re-orderable workspaces, it makes sense
719 // to persist workspace screens and their relative order.
720 mMaxScreenId = 0;
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700721 addWorkspacesTable(db, false);
Sunny Goyala2cc6242015-01-14 14:23:02 -0800722 }
723 case 13: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700724 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800725 // Insert new column for holding widget provider name
726 db.execSQL("ALTER TABLE favorites " +
727 "ADD COLUMN appWidgetProvider TEXT;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700728 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800729 } catch (SQLException ex) {
730 Log.e(TAG, ex.getMessage(), ex);
731 // Old version remains, which means we wipe old data
732 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800733 }
734 }
735 case 14: {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700736 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800737 // Insert new column for holding update timestamp
738 db.execSQL("ALTER TABLE favorites " +
739 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
740 db.execSQL("ALTER TABLE workspaceScreens " +
741 "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700742 t.commit();
Sunny Goyala2cc6242015-01-14 14:23:02 -0800743 } catch (SQLException ex) {
744 Log.e(TAG, ex.getMessage(), ex);
745 // Old version remains, which means we wipe old data
746 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800747 }
748 }
749 case 15: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700750 if (!addIntegerColumn(db, Favorites.RESTORED, 0)) {
Sunny Goyala2cc6242015-01-14 14:23:02 -0800751 // Old version remains, which means we wipe old data
752 break;
Sunny Goyala2cc6242015-01-14 14:23:02 -0800753 }
754 }
755 case 16: {
Sunny Goyal10629b02016-09-01 12:50:11 -0700756 // No-op
Sunny Goyala2cc6242015-01-14 14:23:02 -0800757 }
758 case 17: {
759 // No-op
760 }
761 case 18: {
762 // Due to a data loss bug, some users may have items associated with screen ids
763 // which no longer exist. Since this can cause other problems, and since the user
764 // will never see these items anyway, we use database upgrade as an opportunity to
765 // clean things up.
766 removeOrphanedItems(db);
767 }
768 case 19: {
769 // Add userId column
770 if (!addProfileColumn(db)) {
771 // Old version remains, which means we wipe old data
772 break;
773 }
774 }
775 case 20:
776 if (!updateFolderItemsRank(db, true)) {
777 break;
778 }
Sunny Goyald2f38192015-02-25 10:46:34 -0800779 case 21:
780 // Recreate workspace table with screen id a primary key
781 if (!recreateWorkspaceTable(db)) {
782 break;
783 }
784 case 22: {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700785 if (!addIntegerColumn(db, Favorites.OPTIONS, 0)) {
786 // Old version remains, which means we wipe old data
787 break;
788 }
789 }
Sunny Goyal0b037782015-04-02 10:27:03 -0700790 case 23:
Sunny Goyal5c97f512015-05-19 16:03:28 -0700791 // No-op
Sunny Goyale2fba6c2015-05-12 10:39:59 -0700792 case 24:
793 ManagedProfileHeuristic.markExistingUsersForNoFolderCreation(mContext);
Sunny Goyal5c97f512015-05-19 16:03:28 -0700794 case 25:
795 convertShortcutsToLauncherActivities(db);
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700796 case 26:
797 // QSB was moved to the grid. Clear the first row on screen 0.
798 if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
Sunny Goyal8ad02b82016-12-29 13:31:43 -0800799 !LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
Sunny Goyala9e2f5a2016-06-10 12:22:04 -0700800 break;
801 }
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700802 case 27:
Sunny Goyala2cc6242015-01-14 14:23:02 -0800803 // DB Upgraded successfully
804 return;
Chris Wrend5e66bf2013-09-16 14:02:29 -0400805 }
806
Sunny Goyala2cc6242015-01-14 14:23:02 -0800807 // DB was not upgraded
808 Log.w(TAG, "Destroying all old data.");
809 createEmptyDB(db);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800810 }
Romain Guy7eb9e5e2009-12-02 20:10:07 -0800811
Adam Cohen9b1d0622014-05-21 19:01:57 -0700812 @Override
813 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Sunny Goyal05f30882017-05-03 12:42:18 -0700814 try {
815 DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
816 .onDowngrade(db, oldVersion, newVersion);
817 } catch (Exception e) {
818 Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
819 ". Wiping databse.", e);
820 createEmptyDB(db);
Sunny Goyal3c7d55b2017-04-13 12:01:47 -0700821 }
Sunny Goyal42de82f2014-09-26 22:09:29 -0700822 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700823
Sunny Goyal42de82f2014-09-26 22:09:29 -0700824 /**
825 * Clears all the data for a fresh start.
826 */
827 public void createEmptyDB(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700828 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyale05b08f2017-02-23 18:30:22 -0800829 db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
830 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
831 onCreate(db);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700832 t.commit();
Sunny Goyale05b08f2017-02-23 18:30:22 -0800833 }
Adam Cohen9b1d0622014-05-21 19:01:57 -0700834 }
835
Sunny Goyald2f38192015-02-25 10:46:34 -0800836 /**
Sunny Goyal55fddc82017-04-06 15:02:52 -0700837 * Removes widgets which are registered to the Launcher's host, but are not present
838 * in our model.
839 */
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700840 @TargetApi(Build.VERSION_CODES.O)
Sunny Goyal55fddc82017-04-06 15:02:52 -0700841 public void removeGhostWidgets(SQLiteDatabase db) {
842 // Get all existing widget ids.
843 final AppWidgetHost host = newLauncherWidgetHost();
844 final int[] allWidgets;
845 try {
Sunny Goyal22ca9ec2017-05-18 15:03:13 -0700846 // Although the method was defined in O, it has existed since the beginning of time,
847 // so it might work on older platforms as well.
848 allWidgets = host.getAppWidgetIds();
849 } catch (IncompatibleClassChangeError e) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700850 Log.e(TAG, "getAppWidgetIds not supported", e);
851 return;
852 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700853 final HashSet<Integer> validWidgets = new HashSet<>();
854 try (Cursor c = db.query(Favorites.TABLE_NAME,
855 new String[] {Favorites.APPWIDGET_ID },
856 "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
Sunny Goyal55fddc82017-04-06 15:02:52 -0700857 while (c.moveToNext()) {
858 validWidgets.add(c.getInt(0));
859 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700860 } catch (SQLException ex) {
861 Log.w(TAG, "Error getting widgets list", ex);
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700862 return;
863 }
864 for (int widgetId : allWidgets) {
865 if (!validWidgets.contains(widgetId)) {
866 try {
867 FileLog.d(TAG, "Deleting invalid widget " + widgetId);
868 host.deleteAppWidgetId(widgetId);
869 } catch (RuntimeException e) {
870 // Ignore
871 }
872 }
Sunny Goyal55fddc82017-04-06 15:02:52 -0700873 }
874 }
875
876 /**
Sunny Goyal0b037782015-04-02 10:27:03 -0700877 * Replaces all shortcuts of type {@link Favorites#ITEM_TYPE_SHORTCUT} which have a valid
878 * launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
879 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700880 @Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700881 try (SQLiteTransaction t = new SQLiteTransaction(db);
882 // Only consider the primary user as other users can't have a shortcut.
883 Cursor c = db.query(Favorites.TABLE_NAME,
884 new String[] { Favorites._ID, Favorites.INTENT},
885 "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
886 " AND profileId=" + getDefaultUserSerial(),
887 null, null, null, null);
888 SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
889 + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
890 ) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700891 final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
892 final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
893
894 while (c.moveToNext()) {
895 String intentDescription = c.getString(intentIndex);
896 Intent intent;
897 try {
898 intent = Intent.parseUri(intentDescription, 0);
899 } catch (URISyntaxException e) {
900 Log.e(TAG, "Unable to parse intent", e);
901 continue;
902 }
903
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700904 if (!Utilities.isLauncherAppTarget(intent)) {
Sunny Goyal0b037782015-04-02 10:27:03 -0700905 continue;
906 }
907
908 long id = c.getLong(idIndex);
909 updateStmt.bindLong(1, id);
Sunny Goyalc22841b2015-07-13 19:59:50 -0700910 updateStmt.executeUpdateDelete();
Sunny Goyal0b037782015-04-02 10:27:03 -0700911 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700912 t.commit();
Sunny Goyal0b037782015-04-02 10:27:03 -0700913 } catch (SQLException ex) {
914 Log.w(TAG, "Error deduping shortcuts", ex);
Sunny Goyal0b037782015-04-02 10:27:03 -0700915 }
916 }
917
918 /**
Sunny Goyald2f38192015-02-25 10:46:34 -0800919 * Recreates workspace table and migrates data to the new table.
920 */
921 public boolean recreateWorkspaceTable(SQLiteDatabase db) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700922 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
923 final ArrayList<Long> sortedIDs;
924
925 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
Sunny Goyald2f38192015-02-25 10:46:34 -0800926 new String[] {LauncherSettings.WorkspaceScreens._ID},
927 null, null, null, null,
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700928 LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
929 // Use LinkedHashSet so that ordering is preserved
930 sortedIDs = new ArrayList<>(
931 LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
Sunny Goyald2f38192015-02-25 10:46:34 -0800932 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700933 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
Sunny Goyal6fb929e2015-09-23 11:40:53 -0700934 addWorkspacesTable(db, false);
Sunny Goyald2f38192015-02-25 10:46:34 -0800935
936 // Add all screen ids back
937 int total = sortedIDs.size();
938 for (int i = 0; i < total; i++) {
939 ContentValues values = new ContentValues();
940 values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
941 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
942 addModifiedTime(values);
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700943 db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
Sunny Goyald2f38192015-02-25 10:46:34 -0800944 }
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700945 t.commit();
946 mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
Sunny Goyald2f38192015-02-25 10:46:34 -0800947 } catch (SQLException ex) {
948 // Old version remains, which means we wipe old data
949 Log.e(TAG, ex.getMessage(), ex);
950 return false;
Sunny Goyald2f38192015-02-25 10:46:34 -0800951 }
952 return true;
953 }
954
Adam Cohen091440a2015-03-18 14:16:05 -0700955 @Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700956 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal08f72612015-01-05 13:41:43 -0800957 if (addRankColumn) {
958 // Insert new column for holding rank
959 db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
960 }
961
962 // Get a map for folder ID to folder width
963 Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
964 + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
965 + " GROUP BY container;",
966 new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});
967
968 while (c.moveToNext()) {
Sunny Goyalc87775d2015-02-10 19:52:36 -0800969 db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
970 + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
Sunny Goyal08f72612015-01-05 13:41:43 -0800971 new Object[] {c.getLong(1) + 1, c.getLong(0)});
972 }
973
974 c.close();
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700975 t.commit();
Sunny Goyal08f72612015-01-05 13:41:43 -0800976 } catch (SQLException ex) {
977 // Old version remains, which means we wipe old data
978 Log.e(TAG, ex.getMessage(), ex);
979 return false;
Sunny Goyal08f72612015-01-05 13:41:43 -0800980 }
981 return true;
982 }
983
Kenny Guyed131872014-04-30 03:02:21 +0100984 private boolean addProfileColumn(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -0700985 return addIntegerColumn(db, Favorites.PROFILE_ID, getDefaultUserSerial());
Sunny Goyal5d85c442015-03-10 13:14:47 -0700986 }
987
988 private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700989 try (SQLiteTransaction t = new SQLiteTransaction(db)) {
Sunny Goyal5d85c442015-03-10 13:14:47 -0700990 db.execSQL("ALTER TABLE favorites ADD COLUMN "
991 + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
Sunny Goyaldbfc9012017-04-17 16:58:36 -0700992 t.commit();
Kenny Guyed131872014-04-30 03:02:21 +0100993 } catch (SQLException ex) {
Kenny Guyed131872014-04-30 03:02:21 +0100994 Log.e(TAG, ex.getMessage(), ex);
995 return false;
Kenny Guyed131872014-04-30 03:02:21 +0100996 }
997 return true;
998 }
999
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001000 // Generates a new ID to use for an object in your database. This method should be only
1001 // called from the main UI thread. As an exception, we do call it when we call the
1002 // constructor from the worker thread; however, this doesn't extend until after the
1003 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1004 // after that point
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001005 @Override
Adam Cohendcd297f2013-06-18 13:13:40 -07001006 public long generateNewItemId() {
1007 if (mMaxItemId < 0) {
1008 throw new RuntimeException("Error: max item id was not initialized");
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001009 }
Adam Cohendcd297f2013-06-18 13:13:40 -07001010 mMaxItemId += 1;
1011 return mMaxItemId;
Michael Jurkaa8c760d2011-04-28 14:59:33 -07001012 }
1013
Sunny Goyal55fddc82017-04-06 15:02:52 -07001014 public AppWidgetHost newLauncherWidgetHost() {
Sunny Goyal64a75aa2017-07-03 13:50:52 -07001015 return new LauncherAppWidgetHost(mContext);
Sunny Goyal55fddc82017-04-06 15:02:52 -07001016 }
1017
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001018 @Override
1019 public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001020 return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001021 }
1022
Chris Wren5dee7af2013-12-20 17:22:11 -05001023 public void checkId(String table, ContentValues values) {
1024 long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
Sunny Goyal8e0e1d72016-10-10 10:41:41 -07001025 if (WorkspaceScreens.TABLE_NAME.equals(table)) {
Chris Wren5dee7af2013-12-20 17:22:11 -05001026 mMaxScreenId = Math.max(id, mMaxScreenId);
1027 } else {
1028 mMaxItemId = Math.max(id, mMaxItemId);
1029 }
1030 }
1031
Adam Cohendcd297f2013-06-18 13:13:40 -07001032 private long initializeMaxItemId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001033 return getMaxId(db, Favorites.TABLE_NAME);
Adam Cohendcd297f2013-06-18 13:13:40 -07001034 }
1035
1036 // Generates a new ID to use for an workspace screen in your database. This method
1037 // should be only called from the main UI thread. As an exception, we do call it when we
1038 // call the constructor from the worker thread; however, this doesn't extend until after the
1039 // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
1040 // after that point
1041 public long generateNewScreenId() {
1042 if (mMaxScreenId < 0) {
1043 throw new RuntimeException("Error: max screen id was not initialized");
1044 }
1045 mMaxScreenId += 1;
1046 return mMaxScreenId;
1047 }
1048
Adam Cohendcd297f2013-06-18 13:13:40 -07001049 private long initializeMaxScreenId(SQLiteDatabase db) {
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001050 return getMaxId(db, WorkspaceScreens.TABLE_NAME);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001051 }
1052
Adam Cohen091440a2015-03-18 14:16:05 -07001053 @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
Adam Cohen71483f42014-05-15 14:04:01 -07001054 ArrayList<Long> screenIds = new ArrayList<Long>();
Sunny Goyal0fe505b2014-08-06 09:55:36 -07001055 // TODO: Use multiple loaders with fall-back and transaction.
1056 int count = loader.loadLayout(db, screenIds);
Adam Cohen71483f42014-05-15 14:04:01 -07001057
1058 // Add the screens specified by the items above
1059 Collections.sort(screenIds);
1060 int rank = 0;
1061 ContentValues values = new ContentValues();
1062 for (Long id : screenIds) {
1063 values.clear();
1064 values.put(LauncherSettings.WorkspaceScreens._ID, id);
1065 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001066 if (dbInsertAndCheck(this, db, WorkspaceScreens.TABLE_NAME, null, values) < 0) {
Adam Cohen71483f42014-05-15 14:04:01 -07001067 throw new RuntimeException("Failed initialize screen table"
1068 + "from default layout");
1069 }
1070 rank++;
1071 }
1072
1073 // Ensure that the max ids are initialized
1074 mMaxItemId = initializeMaxItemId(db);
1075 mMaxScreenId = initializeMaxScreenId(db);
Adam Cohen7ec3bbf2014-07-31 00:09:45 -07001076
Adam Cohen71483f42014-05-15 14:04:01 -07001077 return count;
1078 }
Mike Cleronb87bd162009-10-30 16:36:56 -07001079 }
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001080
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001081 /**
1082 * @return the max _id in the provided table.
1083 */
Adam Cohen091440a2015-03-18 14:16:05 -07001084 @Thunk static long getMaxId(SQLiteDatabase db, String table) {
Sunny Goyalfe4e4b92015-03-04 10:43:45 -08001085 Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
1086 // get the result
1087 long id = -1;
1088 if (c != null && c.moveToNext()) {
1089 id = c.getLong(0);
1090 }
1091 if (c != null) {
1092 c.close();
1093 }
1094
1095 if (id == -1) {
1096 throw new RuntimeException("Error: could not query max id in " + table);
1097 }
1098
1099 return id;
1100 }
1101
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001102 static class SqlArguments {
1103 public final String table;
1104 public final String where;
1105 public final String[] args;
1106
1107 SqlArguments(Uri url, String where, String[] args) {
1108 if (url.getPathSegments().size() == 1) {
1109 this.table = url.getPathSegments().get(0);
1110 this.where = where;
1111 this.args = args;
1112 } else if (url.getPathSegments().size() != 2) {
1113 throw new IllegalArgumentException("Invalid URI: " + url);
1114 } else if (!TextUtils.isEmpty(where)) {
1115 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
1116 } else {
1117 this.table = url.getPathSegments().get(0);
Daniel Lehmannc3a80402012-04-23 21:35:11 -07001118 this.where = "_id=" + ContentUris.parseId(url);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001119 this.args = null;
1120 }
1121 }
1122
1123 SqlArguments(Uri url) {
1124 if (url.getPathSegments().size() == 1) {
1125 table = url.getPathSegments().get(0);
1126 where = null;
1127 args = null;
1128 } else {
1129 throw new IllegalArgumentException("Invalid URI: " + url);
1130 }
1131 }
1132 }
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001133
1134 private static class ChangeListenerWrapper implements Handler.Callback {
1135
1136 private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
Sunny Goyalf2dd4212017-09-28 11:31:39 -07001137 private static final int MSG_APP_WIDGET_HOST_RESET = 2;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001138
1139 private LauncherProviderChangeListener mListener;
1140
1141 @Override
1142 public boolean handleMessage(Message msg) {
1143 if (mListener != null) {
1144 switch (msg.what) {
1145 case MSG_LAUNCHER_PROVIDER_CHANGED:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001146 mListener.onLauncherProviderChanged();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001147 break;
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001148 case MSG_APP_WIDGET_HOST_RESET:
Sunny Goyal2e013ea2016-10-07 16:17:19 -07001149 mListener.onAppWidgetHostReset();
Sunny Goyalb5b55c82016-05-10 12:28:59 -07001150 break;
1151 }
1152 }
1153 return true;
1154 }
1155 }
Adam Cohen72960972014-01-15 18:13:55 -08001156}